1

我收到此错误:

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)

这是原图

这是脱粒的图像

这是最大轮廓上的凸包图像

4

1 回答 1

5

cv2.convexHull默认情况下将凸包作为一组点返回(returnPoints参数对此负责,默认为True此处的文档)。但是cv2.convexityDefects,根据docs,该函数期望第二个参数是构成 hull 的轮廓点的索引

所以只要改变

hull=cv2.convexHull(sorted_cnts[0])

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

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

顺便说一句,在这种情况下,您仍然可以通过sorted_cnts[0][hull].

于 2018-12-05T07:01:52.770 回答