简体   繁体   English

python:opencv比较直方图wird结果

[英]python: opencv comparing histograms wird results

I'm using builtin opencv function to open image, remove background, crop image, and then calculate histogram of file, to compare it with histogram of different file. 我正在使用内置的opencv函数打开图像,删除背景,裁剪图像,然后计算文件的直方图,以将其与其他文件的直方图进行比较。

To compare histograms I'm using BGR color space with function: cv2.compareHist(hist_1, hist_2, cv2.HISTCMP_CORREL) 为了比较直方图,我正在使用具有功能的BGR色彩空间: cv2.compareHist(hist_1, hist_2, cv2.HISTCMP_CORREL)

My code is 我的代码是

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)

as on screen below, images have different colors/objects, but I receive very high correlation: 0.9198019904818888 如下面的屏幕所示,图像具有不同的颜色/对象,但是我收到了很高的相关性:0.9198019904818888 在此处输入图片说明

Script works perfect for most of files, any idea WHY so wired results? 脚本适用于大多数文件,为什么有这样的结果呢?

After creating visual histograms for those two images and investigating more, the problem was, after removing background (replacing with black pixels), there was a huge spike in pixels with pitchblack color [0,0,0] which with bin size-10, resulted in very high correlation. 在为这两张图片创建视觉直方图并进行了更多调查之后,问题是,在删除背景(替换为黑色像素)之后,具有黑色黑色[0,0,0]且像素大小为10的像素出现了巨大的尖峰,导致很高的相关性。

To resolve issue I had to create histograms without black pixels, by removing them from histogram range: hist_range=[1, 256, 1, 256, 1, 256] 要解决此问题,我必须通过从直方图范围中删除黑色像素来创建直方图: hist_range=[1, 256, 1, 256, 1, 256]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM