# 检查图像是否与OpenCV相似

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

## 比较直方图

OpenCV方法：compareHist（）

## 模板匹配

OpenCV方法：matchTemplate（）

## function匹配

``// 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` `

• 为Visual Studio 2010安装OpenCV-2.3
• cv :: Mat到QImage并返回
• matrixOpenCV的大小
• ios：改变UIImage的颜色
• 在OpenCV中有效地将大的Mat加载到内存中
• algorithm检测照片中的纸张angular落
• iPhone和OpenCV
• 简单的光照校正openCV c ++