Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

This solves your problem:

// 1) Your contour needs to be of type std::vector<cv::point>

std::vector<cv::Point> contour;

// 2) If you've got contour using findcontours, you've got a std::vector<std::vector<cv::point>> contour_set; that you can pass like this: contour_set[i] instead of contour in the convexHull-method (see below)

// 3) Determine the convex Hull based on int-indeces for contour point localization // ATTENTION: <int> gives you the 'contour element indeces' (= convex hull's key points)!!!!

cv::vector<int> convexHull_IntIdx;          
cv::convexHull(contour, convexHull_IntIdx, true);

// 4) Use the convexityDefects method to determine the convexity defects

std::vector<cv::Vec4i> convexityDefectsSet;     // Here will be start, end point and "most deep" point (the convexity defect, see the documentation-picture) as well as its distance (depth) to the start-end-line determined... as a vector: for each convexity defect one vector-element
cv::convexityDefects(contour, convexHull_IntIdx, convexityDefectsSet);

// 5) You can then access the 4 parameters that this function calculates (start, end, depth/defect-point and depth) like this:

for (int cDefIt = 0; cDefIt < convexityDefectsSet.size(); cDefIt++)
{
int startIdx = convexityDefectsSet[cDefIt].val[0];
int endIdx = convexityDefectsSet[cDefIt].val[1];
int defectPtIdx = convexityDefectsSet[cDefIt].val[2];
double depth = (double)convexityDefectsSet[cDefIt].val[3]/256.0f;  // see documentation link below why this

// do something with *contour[defectPtIdx]*.. This is e.g. the defect point.

}

See for more infos the documentation: http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#void convexityDefects(InputArray contour, InputArray convexhull, OutputArray convexityDefects)