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

Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
Interpreter67
  • 57
  • 2
  • 6
  • 1
    https://stackoverflow.com/questions/68646920/set-particular-channel-of-image-to-certain-value-according-to-other-image – Jeru Luke May 30 '22 at 17:19
  • Your question isn't very clear about what should happen to the alpha channel where pixels are not white... should they be set to zero, or 255 or unaffected? – Mark Setchell May 30 '22 at 18:52

2 Answers2

3

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

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

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432