Reputation: 304
I am getting this error :
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
when I try to get the convexityDefects of the largest contour of the image. This is the code I am using:
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)
Upvotes: 1
Views: 3225
Reputation: 131
cv2.convexHull
returns convex hull as a set of points by default (returnPoints argument is responsible for this, defaulted to True, docs here). But the cv2.convexityDefects
function, according to docs, expects 2nd argument to be indices of the contour points that make the hull.
So just change
hull=cv2.convexHull(sorted_cnts[0])
to
hull=cv2.convexHull(sorted_cnts[0], returnPoints=False)
so hull
will contain indices of original sorted_cnts[0]
contour that make the convex hull.
BTW, in this case you still can obtain the hull as a set of points by doing sorted_cnts[0][hull]
.
Upvotes: 6