opencv python 轮廓/凸缺陷/PointPolygonTest/形状匹配

Contours : More Functions

1 凸缺陷

对象上的任何凹陷都被成为凸缺陷.cv.convexityDefects()

hull = cv2.convexHull(cnt,returnPoints = False)
defects = cv2.convexityDefects(cnt,hull)

它返回一个数组,其中每一行包含这些值 – [起点,终点,最远点,到最远点的近似距离]
NOTE:
必须在找到凸包时传递returnPoints = False,以便找到凸起缺陷.

代码

import cv2
import numpy as np

img = cv2.imread('img7.png')

img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(img_gray, 127, 255,0)
im2,contours,hierarchy = cv2.findContours(thresh,2,1)
cnt = contours[0]

hull = cv2.convexHull(cnt,returnPoints = False)
defects = cv2.convexityDefects(cnt,hull)

for i in range(defects.shape[0]):
    s,e,f,d = defects[i,0]
    start = tuple(cnt[s][0])
    end = tuple(cnt[e][0])
    far = tuple(cnt[f][0])
    cv2.line(img,start,end,[0,255,0],2)
    cv2.circle(img,far,5,[0,0,255],-1)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

《opencv python 轮廓/凸缺陷/PointPolygonTest/形状匹配》

2 PointPolygonTest

此功能可查找图像中的点与轮廓之间的最短距离. 当点在轮廓外时返回负值,当点在内部时返回正值,如果点在轮廓上则返回零.
我们可以检查点(50,50)如下:

dist = cv2.pointPolygonTest(cnt,(50,50),True)

在函数中,第三个参数是measureDist。 如果为True,则查找签名距离. 如果为False,则查找该点是在内部还是外部或在轮廓上(它分别返回+1,-1,0)

NOTE
果您不想找到距离,请确保第三个参数为False,因为这是一个耗时的过程. 因此,将其设为False可提供2-3倍的加速.

3 形状匹配

OpenCV附带了一个函数cv2.matchShapes(),它使我们能够比较两个形状或两个轮廓,并返回一个显示相似性的度量。 结果越低,匹配就越好.它是根据hu-moment值计算的.
代码

import cv2
import numpy as np

img = cv2.imread('img7.png',0)
img2 = cv2.imread('img9.png',0)

ret, thresh = cv2.threshold(img, 127, 255,0)
ret, thresh2 = cv2.threshold(img2, 127, 255,0)
im2,contours,hierarchy = cv2.findContours(thresh,2,1)
cnt1 = contours[0]
im2,contours,hierarchy = cv2.findContours(thresh2,2,1)
cnt2 = contours[0]

ret = cv2.matchShapes(cnt1,cnt2,1,0.0)
print( ret )

《opencv python 轮廓/凸缺陷/PointPolygonTest/形状匹配》

《opencv python 轮廓/凸缺陷/PointPolygonTest/形状匹配》

输出:
0.09604402805803886

    原文作者:sakurala
    原文地址: https://segmentfault.com/a/1190000015665320
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞