seif elberkawy
seif elberkawy

Reputation: 3

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?

Upvotes: 0

Views: 1657

Answers (2)

Rahul Kedia
Rahul Kedia

Reputation: 1430

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)

Upvotes: 1

balu
balu

Reputation: 1143

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 

Upvotes: 1

Related Questions