11

I would like to get an image mask from the contour (it exists only 1 contour) I have computed thanks to cv.findContours.

However, while my contour variable is not empty, I do not manage to retrieve an image mask using cv.drawContours, my destination image being always empty.

Here is my code:

img = mosaicImage[:,:,0].astype('uint8')
contours, _ = cv.findContours(img.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
mask = np.zeros(img.shape, np.uint8)
cv.drawContours(mask, contours, -1, (0,255,0),1)

I hope you could help!

Thanks

3
  • mask is single channel. you try to set channel 2... try cv.drawContours(mask, contours, -1, (255),1)
    – Micka
    Commented Sep 4, 2015 at 18:06
  • 3
    If you're creating a mask, would you want to fill in the contours? You can do that by changing the last parameter to drawContours from 1 to -1 Commented Jul 7, 2016 at 5:29
  • use the constant of cv.FILLED instead of -1 (they are the same number, but for clarity and kosher coding)
    – Joel Teply
    Commented Jul 14, 2022 at 20:05

1 Answer 1

9

You are setting color (0,255,0) to the mask, but the mask is single channel so you can draw the contour in color 0.

try

cv.drawContours(mask, contours, -1, (255),1)

or

cv.drawContours(mask, contours, -1, (255,255,255),1)
3
  • that's not a mask, it only draws the contours. This is also exactly the same code as in the question, which is specifically said to not help. What am I missing?
    – Gulzar
    Commented May 15, 2022 at 21:52
  • 1
    @Gulzar you are missing, that in the question, the contour was drawn in black color (only the first channel of the color (0,255,0) => 0) so the mask was completely black (black contour area drawn on black background). If (as done in my answer) the contour is drawn in (255) or (255,255,255), the contour is drawn in white and the resulting image is a mask for the contour. Choosing thickness = -1 performs drawing a filled conour, which results in a mask of the whole contour area instead of the contour outline.
    – Micka
    Commented May 16, 2022 at 6:58
  • 6
    Adding to Micka's explanation. This would the code for a filled in mask. cv.drawContours(mask, contours, -1, (255,255,255), -1). The last argument is the thickness with -1 being a fill value. Commented Sep 17, 2022 at 22:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.