I have an RGBA image and I want to set the alpha channel of all white pixels to 0. How can I do that?
Thank you for your help
CodePudding user response:
I guess, you're referring to a numpy array.
img_rgb = img[:,:,:3]
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
alpha_mask = img[:,:,-1]
alpha_mask = np.expand_dims(np.where(img_gray ==255, 0, alpha_mask), axis = 2)
img = np.concatenate((img_rgb, alpha_mask), axis = 2)
CodePudding user response:
If you start with this image, wherein the square is transparent and the circle is white:
You can do this:
import cv2
import numpy as np
# Load image, including alpha channel
im = cv2.imread('a.png', cv2.IMREAD_UNCHANGED)
# Make a Boolean mask of white pixels, setting it to True wherever all the first three components of a pixel are [255,255,255], and False elsewhere
whitePixels = np.all(im[...,:3] == (255, 255, 255), axis=-1)
# Now set the A channel anywhere the mask is True to zero
im[whitePixels,3] = 0
If you want to see the mask of white pixels, do this:
cv2.imwrite('result.png', whitePixels*255)
That works because multiplying a False pixel in the Boolean mask by 255 gives zero (i.e. black) and multiplying a True pixel in the mask by 255 gives 255 (i.e. white).