Ask Your Question

Why is the drawContour() in OpenCV generating this strange Mask?

asked 2016-04-20 00:36:34 -0500

Solace gravatar image

updated 2016-06-27 14:51:16 -0500

I started by reading in a Mat.

Then I converted it to Greyscale and applied Imgproc.canny() to it, getting the following mask.

Then I used Imgproc.findContours() to find the contours, Imgproc.drawContours(), and Core.putText() to label the contours with numbers

Then I did Rect boundingRect = Imgproc.boundingRect(contours.get(0)); Mat submatrix = new Mat(); submatrix = originalMat.submat(boundingRect); to get following submatrix:

So far so good. The Problem starts hereafter:

NOW I NEEDED A MASK OF THE submatrix. So I decided to use Imgproc.drawContours() to get the mask:

Mat mask = new Mat(submatrix.rows(), submatrix.cols(), CvType.CV_8UC1);
        List<MatOfPoint> contourList = new ArrayList<>();
        Imgproc.drawContours(mask, contourList, 0, new Scalar(255), -1);

I got the following mask:

enter image description here

WHAT I WAS EXPECTING was a filled (in white color) diamond shape on black background.

WHy am I getting this unexpected result?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2016-04-20 03:54:37 -0500

berak gravatar image

your mask is not initialized properly. it has the right size / type, but the pixels contain uninitialized data.

Mat mask = Mat.zeros(submatrix.rows(), submatrix.cols(), CvType.CV_8UC1);

should do , what you want.

edit flag offensive delete link more


This helped get rid of the garbage in the mask, but still not working correctly. Tried a couple of things, which have confused me more. Can you see the edit in the question?

Solace gravatar imageSolace ( 2016-04-20 06:40:12 -0500 )edit

your mask is smaller than the image, and your contours are thus outside the drawing region.

make the mask same size as the image. (or subtract the tl point from boundingbox from the contours)

berak gravatar imageberak ( 2016-04-20 07:13:35 -0500 )edit

Question Tools

1 follower


Asked: 2016-04-20 00:36:34 -0500

Seen: 298 times

Last updated: Jun 27 '16