【opencv】Opencv(Python) 教程-轮廓(4)凹缺陷(凸缺陷)/点与轮廓关系/形状匹配

凹缺陷/凸缺陷

前面我们已经学习了轮廓的凸包,对象上的任何凹陷都被成为凸缺陷。OpenCV 中有一个函数 cv.convexityDefect() 可以帮助我们找到凸缺陷。函数调用如下:

[python]  view plain  copy
  1. import cv2  
  2. import numpy as np  
  3. img = cv2.imread('star.jpg')  
  4. img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)  
  5. ret, thresh = cv2.threshold(img_gray, 127255,0)  
  6. contours,hierarchy = cv2.findContours(thresh,2,1)  
  7. cnt = contours[0]  
  8. hull = cv2.convexHull(cnt,returnPoints = False)  ###返回凸包的点的坐标,returnPoints = False时反馈的坐标点在轮廓描述集合中点的编号,  
[python]  view plain  copy
  1. #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.destroyAllWindows()
 


点与轮廓关系

求解图像中的一个点到一个对象轮廓的最短距离。如果点在轮廓的外部,返回值为负。如果在轮廓上,返回值为 0。如果在轮廓内部,返回值为正。

下面我们以点(50,50)为例:

[python]  view plain  copy
  1. dist = cv2.pointPolygonTest(cnt,(50,50),True)  
此函数的第三个参数是 measureDist。如果设置为 True,就会计算最短距离。如果是 False,只会判断这个点与轮廓之间的位置关系(返回值为+1,-1,0)。

形状匹配

函数 cv2.matchShape() 可以帮我们比较两个形状或轮廓的相似度。如果返回值越小,匹配越好。它是根据 Hu 矩来计算的。文档中对不同的方法都有解释。

[python]  view plain  copy
  1. import cv2  
  2. import numpy as np  
  3. img1 = cv2.imread('star.jpg',0)  
  4. img2 = cv2.imread('star2.jpg',0)  
  5. ret, thresh = cv2.threshold(img1, 127255,0)  
  6. ret, thresh2 = cv2.threshold(img2, 127255,0)  
  7. contours,hierarchy = cv2.findContours(thresh,2,1)  
  8. cnt1 = contours[0]  
  9. contours,hierarchy = cv2.findContours(thresh2,2,1)  
  10. cnt2 = contours[0]  
  11. ret = cv2.matchShapes(cnt1,cnt2,1,0.0)  
  12. print ret  

  • 0
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值