Opencv:convexity最大轮廓上的缺陷给出错误

时间:2018-08-30 14:21:25

标签: python opencv convexity-defects

我遇到此错误:

OpenCV Error: Assertion failed (hpoints > 0) in cv::convexityDefects, file C:\projects\opencv-python\opencv\modules\imgproc\src\convhull.cpp, line 284
Traceback (most recent call last):
  File "E:/PycharmProjects/ComputerVisionAgain/Image Segmentation/hand_blk/main.py", line 12, in <module>
    hull_defects=cv2.convexityDefects(sorted_cnts[0],hull)
cv2.error: C:\projects\opencv-python\opencv\modules\imgproc\src\convhull.cpp:284: error: (-215) hpoints > 0 in function cv::convexityDefects

当我尝试获取图像最大轮廓的凸性缺陷时。 这是我正在使用的代码:

import cv2
import numpy as np

img=cv2.imread('blk_hand.jpg')
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

ret,thresh=cv2.threshold(gray,100,255,cv2.THRESH_BINARY)

_,contours,h=cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)
sorted_cnts=sorted(contours,key=cv2.contourArea,reverse=True)
hull=cv2.convexHull(sorted_cnts[0])
hull_defects=cv2.convexityDefects(sorted_cnts[0],hull)
cv2.drawContours(img,[hull],-1,(0,0,255),3)

cv2.drawContours(img,sorted_cnts[0],-1,(0,255,0),3)

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

This is the original image

This is threshed image

This is convex hulled image on largest contour

1 个答案:

答案 0 :(得分:1)

cv2.convexHull默认情况下将凸包作为一组点返回( returnPoints 参数对此负责,默认为 True docs here) 。但是根据docscv2.convexityDefects函数期望第二个参数是构成船体的轮廓点的指数

所以只需更改

hull=cv2.convexHull(sorted_cnts[0])

hull=cv2.convexHull(sorted_cnts[0], returnPoints=False)

因此hull将包含构成凸包的原始sorted_cnts[0]轮廓索引。

顺便说一句,在这种情况下,您仍然可以通过执行sorted_cnts[0][hull]来获得船体作为一组点。