Create 2 channel image - grayscale and alpha

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
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 close merge delete