检查图像是否与OpenCV相似

OpenCV支持两个图像比较，返回一些值（可能是一个百分比），表明这些图像有多相似？ 例如，如果两次传递相同的图像，则返回100％，如果图像完全不同，则返回0％。

比较直方图

OpenCV方法：compareHist（）

模板匹配

OpenCV方法：matchTemplate（）

function匹配

• 你可以在这里find更详细的信息和其他类似的技术： http : //answers.opencv.org/question/877/how-to-match-2-hog-for-object-detection/#882

``// Compare two images by getting the L2 error (square-root of sum of squared error). double getSimilarity( const Mat A, const Mat B ) { if ( A.rows > 0 && A.rows == B.rows && A.cols > 0 && A.cols == B.cols ) { // Calculate the L2 relative error between images. double errorL2 = norm( A, B, CV_L2 ); // Convert to a reasonable scale, since L2 error is summed across all pixels of the image. double similarity = errorL2 / (double)( A.rows * A.cols ); return similarity; } else { //Images have a different size return 100000000.0; // Return a bad value }` `

` `import cv2 class CompareImage(object): def __init__(self, image_1_path, image_2_path): self.minimum_commutative_image_diff = 1 self.image_1_path = image_1_path self.image_2_path = image_2_path def compare_image(self): image_1 = cv2.imread(self.image_1_path, 0) image_2 = cv2.imread(self.image_2_path, 0) commutative_image_diff = self.get_image_difference(image_1, image_2) if commutative_image_diff < self.minimum_commutative_image_diff: print "Matched" return commutative_image_diff return 10000 //random failure value @staticmethod def get_image_difference(image_1, image_2): first_image_hist = cv2.calcHist([image_1], [0], None, [256], [0, 256]) second_image_hist = cv2.calcHist([image_2], [0], None, [256], [0, 256]) img_hist_diff = cv2.compareHist(first_image_hist, second_image_hist, cv2.HISTCMP_BHATTACHARYYA) img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0] img_template_diff = 1 - img_template_probability_match # taking only 10% of histogram diff, since it's less accurate than template method commutative_image_diff = (img_hist_diff / 10) + img_template_diff return commutative_image_diff if __name__ == '__main__': compare_image = CompareImage('image1/path', 'image2/path') image_difference = compare_image.compare_image() print image_difference` `

` `import numpy as np picture1 = np.random.rand(100,100) picture2 = np.random.rand(100,100) picture1_norm = picture1/np.sqrt(np.sum(picture1**2)) picture2_norm = picture2/np.sqrt(np.sum(picture2**2))` `

1）如果您比较相似的图片，总和将返回1：

` `In[1]: np.sum(picture1_norm**2) Out[1]: 1.0` `

2）如果他们不相似，你会得到一个介于0和1之间的值（如果乘以100，则为一个百分比）：

` `In[2]: np.sum(picture2_norm*picture1_norm) Out[2]: 0.75389941124629822` `

• openCV程序编译错误“libopencv_core.so.2.4：无法打开共享目标文件：没有这样的文件或目录”在Ubuntu 12.04
• 如何模拟openCV的鱼眼镜头效果？
• OpenCV 2.3编译问题 - Undefined Refence - Ubuntu 11.10
• 如何在OpenCV中裁剪CvMat？
• Eclipse成功编译，但仍然会产生语义错误
• 在OpenCV / Python中设置摄像机参数
• 检测脸部然后autocrop图片
• ImportError：DLL加载失败：％1不是有效的Win32应用程序。 但是DLL在那里
• 在OpenCV中有效地将大的Mat加载到内存中
• 在Ubuntu上安装OpenCV for Python，得到ImportError：没有名为cv2.cv的模块
• OpenCV 2.2中的像素访问