小言_互联网的博客

在OpenCV里图像外形的比较

530人阅读  评论(0)

在图形里经常会用到比较两个图形的相似程度,因为这是目标识别的一种方法,比如轮胎是圆的,那么就可以拿一个圆来与轮胎的外形进行比较,如果相似度比较高,就有可能是轮胎。在OpenCV里使用cv.matchShapes()函数来进行比较,这个函数返回的值越低,说明匹配越好。其实它是使用图像Hu矩来实现的。对于形状匹配来说,我们希望计算出来的矩具有平移不变性,旋转不变性,尺度不变性,Hu矩就可以满足这一要求;hu矩 是7个数字的组合,每个数字都是利用central moments计算得来,前6个被证明包含平移不变性,旋转不变性,尺度不变性和翻转不变性,第7个的符号与图像翻转有关。计算方式如下:

可以用下面的代码来演示:

#python 3.7.4,opencv4.1
#蔡军生 https://blog.csdn.net/caimouse/article/details/51749579
#
import numpy as np
import cv2
from matplotlib import pyplot as plt

#读取图片
img1 = cv2.imread('star3.png',0)
img2 = cv2.imread('star2.png',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]

img2 = cv2.cvtColor(img2, cv2.COLOR_GRAY2RGB)
count = 1
contours,hierarchy = cv2.findContours(thresh2,2,1)


for cnt in contours:
    ret = cv2.matchShapes(cnt1,cnt,1,0.0)
    print('%d=%f'%(count,ret) )
    cv2.drawContours(img2,[cnt], 0, [0,0,255],count*2)
    count += 1
cv2.imshow('img2',img2)

cv2.waitKey(0)
cv2.destroyAllWindows()

结果输出如下:

比较的星

与三个边缘进行比较结果:

1=0.337367  与第三个图

2=0.000000  与第一个图

3=0.013908  与第二个图

https://blog.csdn.net/caimouse/article/details/102530873


转载:https://blog.csdn.net/caimouse/article/details/102563538
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场