轮廓凸缺陷

凸缺陷

轮廓与其凸包的任何偏差都称为凸缺陷,注:凸曲线没有凸缺陷。如下图所示,其中灰色线条表示手的轮廓,红色的表示轮廓的凸包,黑色的双箭头表示轮廓到凸包最远的点和距离,黄色区域为凸缺陷。


openCV 凸缺陷接口

openCV提供了C++和python函数接口(说明源码)

coutour: 输入参数,可以调用findContours函数从二值图像中得到;
convexhull: 输入参数,可以调用convexHull函数得到;
convexityDefects:输出参数,检测到的最终结果,C++数据类型为std::vector < std::vector < cv::Vec4i> >,Vec4i存储了某段轮廓凸包的开始下标(start_index), 结束下标(end_index), 最远点下标(farthest_pt_index)和最远点到凸包的距离(fixpt_depth),要获取距离的浮点值需要除以256。

示例

C++代码见github

  • 二值图片test.jpg

  • 查找轮廓
import cv2
import numpy as np
img = cv2.imread('test.jpg')
img_gray = cv2.cvtColor(img,cv.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)

  • 凸缺陷
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])
    cv.line(img,start,end,[0,255,0],2)
    cv.circle(img,far,5,[0,0,255],-1)
 
cv2.imshow('final_img',img)
cv2.waitKey(0)

参考链接
基于凹点匹配的重叠分割
用opencv检测convexity defects
Convexity Defects OpenCV

原文地址:https://www.cnblogs.com/xiaxuexiaoab/p/14743840.html