Interpreter67
Interpreter67

Reputation: 67

How can I set the Alpha Channel to 0?

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

Upvotes: 0

Views: 1665

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207365

If you start with this image, wherein the square is transparent and the circle is white:

enter image description here

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

enter image description here


If you want to see the mask of white pixels, do this:

cv2.imwrite('result.png', whitePixels*255)

enter image description here

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).

Upvotes: 1

Sangam Khanal
Sangam Khanal

Reputation: 133

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)

Upvotes: 3

Related Questions