1 凸缺陷

  找到凸缺陷  
hull=cv2.convexHull(cnt,returnPoints=False)
defects=cv2.convexityDefects(cnt,hull)
  它会返回一个数组,其中每一行包含的值是【起点,终点,最远的点,到最远点的近似距离】  
import cv2
import numpy as np
img=cv2.imread('0023.jpg')
img_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh=cv2.threshold(img_gray,127,255,0)
contours=cv2.findContours(thresh,2,1)
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)
while(1):
    cv2.imshow('img',img)
    if cv2.waitKey(1)==ord('q'):
        break
cv2.destroyAllWindows()
 

2.Point Polygon Test

  求解图像中的一个点到一个对象轮廓的最短距离。如果点再轮廓的外部,返回值为负,如果在轮廓上,返回值为0,如果在轮廓内部,返回值为正。   下面我们以点(50,50)为例:  
dist = cv2.pointPolygonTest(cnt,(50,50),True)
  此函数的第三个参数是measureDist。如果设置为True,就会计算最短距离。如果是False,只会判断这个点与轮廓之间的位置关系(返回值为+1,-1,0)  

3.形状匹配

  函数cv2.matchShape()可以帮我们比较两个形状或者轮廓的相似度,如果返回值越小,匹配越好,它是根据Hu矩来计算的。  
import cv2
import numpy as np

img1 = cv2.imread('roi.jpg')
img2 = cv2.imread('0022.jpg')

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)
 

总结

(本系列每周不定期更新,谢谢大家支持!)