1.获取图像直方图
def plot_demo(image):
plt.hist(image.ravel(),256,[0, 256])
plt.show("直方图")
统计各种像素的数值
def image_hist(image):
color = ('blue','green','red')
for i,color in enumerate(color):
hist = cv.calcHist([image],[i],None,[256],[0,256])
plt.plot(hist, color = color)
plt.xlim([0,256])
plt.show()
统计各颜色的直方图
2.直方图均衡化
#全局直方图均衡化(对比度增强,但有的时候会过度)
def equalHist_demo(image):
gray = cv.cvtColor(image,
cv.COLOR_BGR2GRAY)
dst = cv.equalizeHist(gray)
cv.imshow("equalHist_demo",dst)
#局部直方图均衡化(自适应增加对比度,效果很好)
def clahe_demo(image):
gray = cv.cvtColor(image,
cv.COLOR_BGR2GRAY)
clahe = cv.createCLAHE(clipLimit=2.0,tileGridSize=(8,8))
dst = clahe.apply(gray)
cv.imshow("clahe_demo",dst)
提高图像对比度
3.直方图比较
def create_rgb_hist(image):
h, w, c = image.shape
rgbHist = np.zeros([16*16*16, 1],np.float32)
bsize = 256 / 16
for row in range(h):
for col in range(w):
b = image[row, col, 0]
g = image[row, col, 1]
r = image[row, col, 2]
index = np.int(b/bsize)*16*16 + np.int(g/bsize)*16 +
np.int(r/bsize)
rgbHist[np.int(index), 0] = rgbHist[np.int(index), 0] + 1
return rgbHist
def hist_compare(image1,
image2):
hist1 = create_rgb_hist(image1)
hist2 = create_rgb_hist(image2)
match1 = cv.compareHist(hist1,hist2,
cv.HISTCMP_BHATTACHARYYA)
match2 = cv.compareHist(hist1,hist2,
cv.HISTCMP_CORREL)
match3 = cv.compareHist(hist1,hist2,
cv.HISTCMP_CHISQR)
print("巴氏距离:%s 相关性:%s 卡方:%s"%(match1,match2,match3))
查看两个直方图的相似程度
4.直方图反向投影
def hist2d_demo(image):
hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
hist = cv.calcHist([hsv],[0,1],None,[180,250],[0,180,0,250])
cv.imshow("hist2d",hist)
plt.imshow(hist, interpolation='nearest')
plt.title("2D Histogram")
plt.show()
def back_projection_demo():
sample = cv.imread('C:\\Users\\lieng\\Desktop\\timg.jpg')
target = cv.imread('C:\\Users\\lieng\\Desktop\\text.png')
roi_hsv =
cv.cvtColor(sample,cv.COLOR_BGR2HSV)
target_hsv = cv.cvtColor(target, cv.COLOR_BGR2HSV)
cv.imshow("sampel",sample)
cv.imshow("target",target)
roiHist = cv.calcHist([roi_hsv],[0, 1],None,[180,256],[0,100,0,256])
cv.normalize(roiHist,roiHist,0,255,cv.NORM_MINMAX)
dst = cv.calcBackProject([target_hsv],[0,1], roiHist,[0, 100, 0, 256], 1)
cv.imshow("backproject", dst)
可以理解为在案例图像上寻找目标图像