I have an image array in RGB space and want to add the alpha channel to be all zeros. Specifically, I have a numpy
array with shape (205, 54, 3) and I want to change the shape to (205, 54, 4) with the additional spot in the third dimension being all 0.0's. Which numpy operation would achieve this?
You could use one of the stack functions (stack/hstack/vstack/dstack/concatenate) to join multiple arrays together.
numpy.dstack( ( your_input_array, numpy.zeros((205, 54)) ) )
If you have your current image as rgb variable then just use:
rgba = numpy.concatenate((rgb, numpy.zeros((205, 54, 1))), axis=2)
Concatenate function merge rgb and zeros array together. Zeros function creates array of zeros. We set axis to 2 what means we merge in the thirde dimensions. Note: axis are counted from 0.
np array style, stack on depth dimension(channel dimension, 3rd dimension):
rgba = np.dstack((rgb, np.zeros(rgb.shape[:-1])))
but you should use OpenCV function:
rgba = cv2.cvtColor(rgb, cv2.COLOR_RGB2RGBA)
not sure if your still looking for an answer.
recently i am looking to achieve the exact same thing you are looking to do with numpy because i needed to force a 24 bit depth png into a 32. I agree that it makes sense to use dstack, but i couldnt get it to work. i used insert instead and it seems to achieved my goal.
# for your code it would look like the following:
rgba = numpy.insert(
rgb,
3, #position in the pixel value [ r, g, b, a <-index [3] ]
255, # or 1 if you're going for a float data type as you want the alpha to be fully white otherwise the entire image will be transparent.
axis=2, #this is the depth where you are inserting this alpha channel into
)
hope this helps, good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With