Search code examples
c++matlabopencvconvex-hull

Replicating Matlab's bwconvhull in OpenCV


I am currently in the process of rewriting a Matlab program into OpenCV and I cannot find an equivalent to the bwconvhull function.

The Matlab code does the following:

H = bwconvhull(W>0.5);

Where W is a matrix with floating point values (which got calculated from several distance maps in the previous part of the algorithm).

I have successfully found a way to calculate W itself in OpenCV - resulting cv::Mat with type 32FC1.

My first attempt used the straightforward translation:

cv::convexHull(w>0.5, h);

This crashes with the following exception:

OpenCV(3.4.1) \opencv\modules\imgproc\src\convhull.cpp:137: 
error: (-215) total >= 0 && (depth == 5 || depth == 4) 
in function cv::convexHull

I have checked out the source code and found out the problem is the Mat type - (> operator produces 8U mat, while algorithm seems to support only 32F and 32S). So I tried conversion:

cv::Mat w2;
w = (w > 0.5);
w.convertTo(w2, CV_32F);
cv::convexHull(w2, h);

But now the problem moves to the total >= 0 condition, where total is w.checkVector(2). I am unable to understand how to achieve this condition to hold true.

I have also tried the following approach with the same result:

cv::Mat w2 = w * ( w > 0.5 );
cv::convexHull(w2, h);

My other tries involved cv::threshold and cv::findContours but those failed in a similar fashion.

I am really inexperienced in OpenCV and will be grateful for any pointer in the right direction.


Solution

  • @CrisLuengo and @AlexanderReynolds have pointed me in the right direction, thank you both very much.

    What I was missing was the findContours step to first retrieve the contours of the image and only then run it through the convexHull function. I have tried the findContours call before asking the question, but I must have chosen the arguments incorrectly. To get it working I have basically replicated the sample code here.