Ask Your Question
0

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

asked Apr 20 '16

Solace gravatar image

updated Jun 27 '16

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<>();
        contourList.add(contours.get(0));
        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?

Preview: (hide)

1 answer

Sort by » oldest newest most voted
1

answered Apr 20 '16

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.

Preview: (hide)

Comments

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 (Apr 20 '16)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 (Apr 20 '16)edit

Question Tools

1 follower

Stats

Asked: Apr 20 '16

Seen: 445 times

Last updated: Jun 27 '16