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?
4 Answers
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)) ) )
4 Comments
np.dstack makes sense.dtype in np.zeros. its default value is float64. numpy.org/doc/stable/reference/generated/numpy.zeros.htmlIf 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.
Comments
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.
(205, 54, 4, 0)? Please post an example of how the output should be.x.shape = (205,54,3)andx[0][0] = [255, 255, 255]and I wantx[0][0] = [255, 255, 255, 0].