Exception with Convexity Defects

611 Views Asked by At

I am trying get Convexity Defects from the following code, but keep getting a unhandled exception. What am I doing wrong?

vector<Vec4i> defects;
ContourPoly = vector<Point>(contour.size());
approxPolyDP( Mat(contour), ContourPoly,20, false );
convexHull(Mat(ContourPoly), HullPoints, false, true);
// The following line wont work
convexityDefects(Mat(ContourPoly),HullPoints,defects);

While HullPoints are of type vector<Point> The exception is as follows

OpenCV Error: Assertion Failed (ptnum >3) is unknown function, file ..\..\..\src\opencv\modules\imgproc\src\contours.cpp, line 1969

But with vector<Point> defects; or vector<Vec4i> defects I get the following exception

 OpenCV Error: Assertion Failed (hull.checkVector(1,CV_32S) is unknown function, file ..\..\..\src\opencv\modules\imgproc\src\contours.cpp, line 1971
2

There are 2 best solutions below

0
On

First of all

vector<vector<Vec4i> > defects;

should be:

vector<vector<Vec4i> > defects( contour.size() );

Also, before calling convexityDefects function, check if the size of the HullPoints is greater than 3.

2
On

defects should be vector<Vec4i>

From the documentation:

each convexity defect is represented as 4-element integer vector (a.k.a. cv::Vec4i): (start_index, end_index, farthest_pt_index, fixpt_depth), where indices are 0-based indices in the original contour of the convexity defect beginning, end and the farthest point, and fixpt_depth is fixed-point approximation (with 8 fractional bits) of the distance between the farthest contour point and the hull. That is, to get the floating-point value of the depth will be fixpt_depth/256.0