9

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

neon29
  • 179
  • 1
  • 3
  • 13
  • mask is single channel. you try to set channel 2... try cv.drawContours(mask, contours, -1, (255),1) – Micka Sep 04 '15 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 – tonyslowdown Jul 07 '16 at 05:29
  • use the constant of cv.FILLED instead of -1 (they are the same number, but for clarity and kosher coding) – Joel Teply Jul 14 '22 at 20:05

1 Answers1

8

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

try

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

or

 cv.drawContours(mask, contours, -1, (255,255,255),1)
Micka
  • 19,585
  • 4
  • 56
  • 74
  • 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 May 15 '22 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 May 16 '22 at 06:58
  • 3
    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. – Andrew Parmar Sep 17 '22 at 22:14