OpenCV使用cv2.matchShapes()用来对比2个图像是否相似。返回值越低说明2张图片越相似。这个是基于hu-moment值算出来的。
代码如下:
- import cv2
- import numpy as np
-
- img1 = cv2.imread('star.jpg',0)
- img2 = cv2.imread('star2.jpg',0)
-
- ret, thresh = cv2.threshold(img1, 127, 255,0)
- ret, thresh2 = cv2.threshold(img2, 127, 255,0)
- contours,hierarchy = cv2.findContours(thresh,2,1)
- cnt1 = contours[0]
- contours,hierarchy = cv2.findContours(thresh2,2,1)
- cnt2 = contours[0]
-
- ret = cv2.matchShapes(cnt1,cnt2,1,0.0)
- print ret
如下测试图:
结果为:
A图形匹配自身体结果为0.0
A图形匹配B图形结果为0.001946
A图形匹配C图形结果为0.326911
相关解析:
①threshold(img, threshold, maxval, type):
Ⅰ:threshold设定的阈值;
Ⅱ:maxval当灰度值大于(或小于)阈值时将该灰度赋值成的值;
Ⅲ:type规定的是当前二值化的方式。
②findContours():查找轮廓,第一个参数是输入图像,第二个参数是轮廓检索模式,第三参数是轮廓近似方法。