Home > Enterprise >  Convert an image to black and white mask using opencv python
Convert an image to black and white mask using opencv python

Time:06-27

I have a transparent background image and i want to color all transparent region as black and rest of region as white.

imgage = cv2.imread("imgage.png", cv2.IMREAD_UNCHANGED)
trans_mask = image[:,:,3] == 255
image[trans_mask] = [255, 255, 255, 255]

The output i got it. I got inside area to fill white and outside area to fill black. Any suggestion

enter image description here Original input enter image description here

CodePudding user response:

The simplest way to do this is starting out with a fully-black image and filling in just the area with positive alpha:

res = np.zeros(image.shape[:2], np.uint8) # black by default
colored_areas = image[...,3] > 0
res[colored_areas] = 255

CodePudding user response:

You say:

i want to color all transparent region as black and rest of region as white.

So this should satisfy your request:

the alpha channel

and you get that from this simple code:

image[:,:,3]

Just apply imwrite or imshow waitKey (or matplotlib) to see the data.

  • Related