凹缺陷/凸缺陷
前面我们已经学习了轮廓的凸包,对象上的任何凹陷都被成为凸缺陷。OpenCV 中有一个函数 cv.convexityDefect() 可以帮助我们找到凸缺陷。函数调用如下:
import cv2
import numpy as np
img = cv2.imread('star.jpg')
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(img_gray, 127, 255,0)
contours,hierarchy = cv2.findContours(thresh,2,1)
cnt = contours[0]
hull = cv2.convexHull(cnt,returnPoints = False) ###返回凸包的点的坐标,returnPoints = False时反馈的坐标点在轮廓描述集合中点的编号,
#returnPoints = True时反馈的坐标点位置。为了后面cv2.convexityDefects的使用,此处必须为False
defects = cv2.convexityDefects(cnt,hull) ##反馈的是Nx4的数组,第一列表示的是起点(轮廓集合中点的编号)、第二列表示的是终点(轮廓集合中点的编号)
##第三列表示的是最远点(轮廓集合中点的编号),第四列表示的是最远点到凸轮廓的最短距离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.destroyAllWindow