Create 2 channel image - grayscale and alpha

asked 2020-02-24 21:58:55 -0600

charlie gravatar image

updated 2020-10-24 02:14:18 -0600

I wish to create a 2-channel png image - 1 channel would be grayscale and 1 channel would be alpha (the bit depth doesn't concern me). I have developed a workaround to achieve this, but this is non-ideal because (a) it makes the image unnecessarily 2x as large as it needs to be, and (b), its an 'obtuse' way to solve the problem:

import cv2
import numpy as np
img = cv2.imread("test_image_with_transparency.png", cv2.IMREAD_UNCHANGED)
alpha = img[:,:,3]
rgb = img[:,:,:-1]
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
rgb_gray = cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB)
alpha = np.reshape(alpha, (*alpha.shape,1))
gray_alpha = np.concatenate([rgb_gray, alpha], axis=2)
cv2.imwrite("test_image_out.png", gray_alpha)

Ideally, the solution would simplify lines 4-9 to:

gray_with_alpha = cv2.cvtColor(rgb, cv2.COLOR_RGBA2GRAYALPHA)

With the added bonus that there would just be 2 channels written to file, as opposed to 4. However, I can't find such a function to achieve this, though I'm fairly confident 2-channel png files do legitimately exist.

I've seen this answer here, but this does not accomplish what I'm after, because it applies transparency as a binary mask to the image (I don't want to lose the alpha information).

I want to do this because I think this is the best way I think to resolve NaNs in image data received from a sensor. Selecting a value at the extremes (either black or white) creates the possibility for the user to be easily mislead.

edit retag flag offensive close merge delete

Comments

1

imo, opencv, being a computer-vision library is the wrong tool for you

(alpha does not play any role here, and is usually harmful/discarded)

berak gravatar imageberak ( 2020-02-25 02:43:50 -0600 )edit

It strikes me as really strange to argue that encoding an image to make it easier for a computer to interpret isn't the role of a computer-vision library...

charlie gravatar imagecharlie ( 2020-02-28 03:45:02 -0600 )edit