#巴氏距离 相关性
#直方图,颜色有255,然后分别统计有多少个
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
def create_rgb_hist(image):
h, w, c = image.shape
rgbHist = np.zeros([16*16*16, 1], np.float32)#16*16*16为bsize的取值范围 # 初始一个4096*1的矩阵;数据类型必须是np.float32
bsize = 256 / 16 # 降维,由bgr均是 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) #下降成16个bin,由256*256*256降维4096
rgbHist[np.int(index), 0] = rgbHist[np.int(index), 0] + 1 # 由于python没有自增自减操作
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) #9+60qwertyuiop[]asdfghjkl;'
# 巴氏距离比较,距离越小越相似(取值范围0-1)
match2 = cv.compareHist(hist1, hist2, cv.HISTCMP_CORREL) #相关性比较,相关性越大越相似(取值范围0-1)
match3 = cv.compareHist(hist1, hist2, cv.HISTCMP_CHISQR) # 卡方比较,越大越不相似,这个少用
print("巴氏距离: %s, 相关性: %s, 卡方: %s" % (match1, match2, match3))
if __name__ == '__main__':
src = cv.imread("D:/example/1.png ")
src2=cv.imread('Y:/1.png')
# cv.namedWindow("input image",cv.WINDOW_AUTOSIZE)
cv.imshow("source image", src)
hist_compare(src,src2)
cv.waitKey(0)
cv.destroyAllWindows()
结果如下