E_learner
E_learner

Reputation: 3582

OpenCV convexhull doesn't give correct output

This is my input binary image:

enter image description here

Now I want to get its convex hull using OpenCV. For that, I wrote the following code:

cv::Mat input = cv::imread("input.jpg", CV_LOAD_IMAGE_GRAYSCALE);
cv::vector<cv::vector<cv::Point>> contours;
cv::vector<cv::Vec4i> hierarchy;

// Find contours
cv::findContours(input, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);

// Find the convex hull
cv::vector<cv::vector<cv::Point>> hull(contours.size());
for(int i = 0; i < contours.size(); i++)
{
    cv::convexHull(cv::Mat(contours[i]), hull[i], false);
}

cv::Mat drawing = cv::Mat::zeros(input.size(), CV_8UC3);
cv::Scalar color = cv::Scalar(0, 0, 255);
for (int j  = 0; j < hull.size(); j++)
{
    cv::drawContours(drawing, hull, j, color, 1, 8, cv::vector<cv::Vec4i>(), 0, cv::Point());
}

cv::imshow("Convex hull", drawing);
cv::waitKey();

And this is the output:

enter image description here

In Matlab however, when I write the following code:

input = imread('input.jpg');
[x, y] = find(input);
k = convhull(x, y);
plot(y(k), x(k), 'r-', y, x, 'b.');

This gives me exactly what I want (the red line represents the convex hull that I want):

enter image description here

So, how can I obtain the same result in OpenCV? What should I've done incorrectly here? Thank you.

Upvotes: 0

Views: 1265

Answers (1)

Andriy Koretskyy
Andriy Koretskyy

Reputation: 575

May be this answer is late, but for those who is still in search here it is.

You don't need to take contours. Just take all non-zero point from binary image using findNonZero() method and then apply convexHull to that set of points. It will work perfectly.

Upvotes: 2

Related Questions