python:opencv比较直方图wird结果

时间:2018-10-19 14:44:30

标签: python opencv comparison histogram

我正在使用内置的opencv函数来打开图像,删除背景,裁剪图像,然后计算文件的直方图,以将其与其他文件的直方图进行比较。

要比较直方图,我正在使用具有以下功能的BGR颜色空间: cv2.compareHist(hist_1, hist_2, cv2.HISTCMP_CORREL)

我的代码是

def cv_histogram(image, channels=[0, 1, 2], hist_size=[10, 10, 10], hist_range=[0, 256, 0, 256, 0, 256], hist_type='BGR'):
    #convert to different color space if needed
    if hist_type=='HSV':    image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    elif hist_type=='GRAY': image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    elif hist_type=='RGB':  image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    image_hist = cv2.calcHist([image], channels, None, hist_size, hist_range)
    image_hist = cv2.normalize(image_hist, image_hist).flatten()
    return image_hist

def cv_compare_images_histogram(img_base, img_compare, method='correlation'):
    hist_1 = cv_histogram(img_base)
    hist_2 = cv_histogram(img_compare)

    if method == "intersection":
        comparison = cv2.compareHist(hist_1, hist_2, cv2.HISTCMP_INTERSECT)
    else:
        comparison = cv2.compareHist(hist_1, hist_2, cv2.HISTCMP_CORREL)
    return comparison

im1 = image_remove_background(cv2.imread("1.jpg"), bg_lower_bgr, bg_upper_bgr)
im2 = image_remove_background(cv2.imread("2.jpg"), bg_lower_bgr, bg_upper_bgr)
sim = cv_compare_images_histogram(im1, im2)
img_new = image_stack(im1, im2)
cv2.imshow('img_new', img_new)
print("Histogram similarity is: ", sim)

如下面的屏幕所示,图像具有不同的颜色/对象,但是我收到了很高的相关性:0.9198019904818888 enter image description here

脚本适合大多数文件,为什么可以连接结果呢?

1 个答案:

答案 0 :(得分:0)

为这两个图像创建视觉直方图并进行更多调查之后,问题是,在去除背景(用黑色像素替换)之后,具有黑色黑色[0,0,0]且像素大小为bin的像素出现了巨大的尖峰-10,导致很高的相关性。

要解决此问题,我必须创建无黑色像素的直方图,方法是将其从直方图范围中删除:hist_range=[1, 256, 1, 256, 1, 256]