主要内容
5-2 彩色图片直方图
import cv2
import numpy as np
def ImageHist(image,type):
color = (255,255,255)
windowName = 'Gray'
if type == 31:
color = (255,0,0)
windowName = 'B Hist'
elif type == 32:
color = (0,255,0)
windowName = 'G Hist'
elif type == 33:
color = (0,0,255)
windowName = 'R Hist'
# 1 image 2 [0] 3 mask None 4 256 5 0-255
hist = cv2.calcHist([image],[0],None,[256],[0.0,255.0])
minV,maxV,minL,maxL = cv2.minMaxLoc(hist)
print(maxV)
histImg = np.zeros([256,256,3],np.uint8)
for h in range(256):
intenNormal = int(hist[h]*256/maxV)
cv2.line(histImg,(h,256),(h,256-intenNormal),color)
cv2.imshow(windowName,histImg)
return histImg
img = cv2.imread('image0.jpg',1)
channels = cv2.split(img)# RGB - R G B
for i in range(0,3):
ImageHist(channels[i],31+i)
cv2.waitKey(0)
imGray = cv2.imread('image0.jpg', 0)
ImageHist(imGray, 0)
cv2.waitKey(0)
#灰度 直方图均衡化
import cv2
import numpy as np
img = cv2.imread('image0.jpg',1)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow('src',gray)
dst = cv2.equalizeHist(gray)
cv2.imshow('dst',dst)
cv2.waitKey(0)
#彩色 直方图均衡化
import cv2
import numpy as np
img = cv2.imread('image0.jpg',1)
cv2.imshow('src',img)
(b,g,r) = cv2.split(img)#通道分解
bH = cv2.equalizeHist(b)
gH = cv2.equalizeHist(g)
rH = cv2.equalizeHist(r)
result = cv2.merge((bH,gH,rH))# 通道合成
cv2.imshow('dst',result)
cv2.waitKey(0)
#YUV 直方图均衡化
import cv2
import numpy as np
img = cv2.imread('image0.jpg',1)
imgYUV = cv2.cvtColor(img,cv2.COLOR_BGR2YCrCb)
cv2.imshow('src',img)
channelYUV = cv2.split(imgYUV)
channelYUV[0] = cv2.equalizeHist(channelYUV[0])
channels = cv2.merge(channelYUV)
result = cv2.cvtColor(channels,cv2.COLOR_YCrCb2BGR)
cv2.imshow('dst',result)
cv2.waitKey(0)