opencv for python (19) 根据矩进行形状匹配

函数 cv2.matchShape() 可以帮我们比较两个形状或轮廓的相似度。如果返回值越小,匹配越好。它是根据 Hu 矩来计算的。Hu 矩是归一化中心矩的线性组合,之所以这样做是为了能够获取代表图像的某个特征的矩函数,这些矩函数对某些变化如缩放,旋转,镜像映射具有不变形。

import cv2
import numpy as np

img1 = cv2.imread('t1_re.png',0)
img2 = cv2.imread('t1_re2.png',0)
img3 = cv2.imread('t1_.png',0)

ret,thresh = cv2.threshold(img1,127,255,0)
ret2,thresh2 = cv2.threshold(img2,127,255,0)
ret3,thresh3 = cv2.threshold(img3,127,255,0)
contours,hierarchy = cv2.findContours(thresh,2,1)
cnt1 = contours[0]
contours2,hierarchy2 = cv2.findContours(thresh2,2,1)
cnt2 = contours2[0]
contours3,hierarchy3 = cv2.findContours(thresh3,2,1)
cnt3 = contours3[0]

ret = cv2.matchShapes(cnt1,cnt2,1,0.0)
ret1 = cv2.matchShapes(cnt1,cnt3,1,0.0)
ret2 = cv2.matchShapes(cnt1,cnt1,1,0.0)

print ret,ret1,ret2

你可能感兴趣的:(opencv for python (19) 根据矩进行形状匹配)