'Python how to make the outside of all contours black?
I am using mask-RCNN to detect objects in an image then I draw contours on the image using the objects masks like this contours in an image
Then I want to make every pixel outside those contours to be black something like this: contours with black background so is there an easy way to do so?
Solution 1:[1]
Get a mask by using cv2.FILLED while drawing contours and apply to the original image.
ex:
black_canvas = np.zeros_like(img_gray)
cv2.drawContours(black_canvas, contours, -1, 255, cv2.FILLED) # this gives a binary mask
Solution 2:[2]
Assuming that you have the contours, you can obtain your result by first creating a mask image of the contours and then performing a bitwise_and operation using that mask.
maskImage = np.zeros(img.shape, dtype=np.uint8)
cv2.drawContours(maskImage, Contours, -1, (255, 255, 255), -1)
newImage = cv2.bitwise_and(img, maskImage)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | balu |
| Solution 2 | Rahul Kedia |
