通过直方图匹配比较图像

时间:2016-05-23 05:07:47

标签: python opencv image-recognition

我希望比较两个图像,使用直方图匹配和方法相关性

enter image description here
enter image description here

显然,这两个图像是相似的。然后,我尝试找出与以下代码的相关性。

import cv2
import numpy as np

#reading the images and convert them to HSV
base = cv2.imread('base.jpg')
test1 = cv2.imread('test1.jpg')
basehsv = cv2.cvtColor(base,cv2.COLOR_BGR2HSV)
test1hsv = cv2.cvtColor(test1,cv2.COLOR_BGR2HSV)

# Calculate the Hist for each images
histbase = cv2.calcHist(basehsv,[0,1],None,[180,256],ranges)
cv2.normalize(histbase,histbase,0,255,cv2.NORM_MINMAX)
histtest1 = cv2.calcHist(test1hsv,[0,1],None,[180,256],ranges)
cv2.normalize(histtest1,histtest1,0,255,cv2.NORM_MINMAX)

# Compare two Hist. and find out the correlation value
base_test1 = cv2.compareHist(histbase,histtest1,0)
print base_test1 

但是,打印出的结果只是0.05xxx

为什么相关性如此之小?

如何改善结果?谢谢。

1 个答案:

答案 0 :(得分:0)

绘制 HSV 直方图时,您会注意到两个问题:

  1. 这两个图像的直方图相似。因此,对整个图像进行 HSV 直方图匹配并不是匹配这些图像或识别军官的好方法。
  2. 饱和度通道的 minmax 归一化效果不佳,因为基础图像的最终 bin 中出现了大尖峰。

HSV Histograms

代码:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Get HSV images
base = cv2.imread("base.jpg")
test = cv2.imread("test1.jpg")
basehsv = cv2.cvtColor(base, cv2.COLOR_BGR2HSV)
testhsv = cv2.cvtColor(test, cv2.COLOR_BGR2HSV)

# Calculate historgrams
hist_base_h = cv2.calcHist(basehsv, [0], None, [180], [0, 180])
hist_base_s = cv2.calcHist(basehsv, [1], None, [256], [0, 256])
hist_base_v = cv2.calcHist(basehsv, [2], None, [256], [0, 256])
hist_test_h = cv2.calcHist(test, [0], None, [180], [0, 180])
hist_test_s = cv2.calcHist(test, [1], None, [256], [0, 256])
hist_test_v = cv2.calcHist(test, [2], None, [256], [0, 256])

# Plot histograms
fig, axs = plt.subplots(3, 1)
axs[0].plot(hist_base_h, "b-", label="Hue base")
axs[0].plot(hist_test_h, "b:", label="Hue test")
axs[1].plot(hist_base_s, "r-", label="Saturation base")
axs[1].plot(hist_test_s, "r:", label="Saturation test")
axs[2].plot(hist_base_v, "g-", label="Value base")
axs[2].plot(hist_test_v, "g:", label="Value test")
axs[0].set_title("HSV Histograms")
axs[0].legend(loc="upper left")
axs[1].legend(loc="upper left")
axs[2].legend(loc="upper left")
fig.show()