Adding alpha channel to RGB array using numpy

I have an array of images in RGB space and you want to add the alpha channel to zero. In particular, I have a numpy array with the shape (205, 54, 3), and I want to change the shape to (205, 54, 4), and the extra spot in the third dimension is all 0.0. What operation with numpy would achieve this?

+8
source share
4 answers

You can use one of the stack functions ( stack / hstack / vstack / dstack / concatenate ) to combine multiple arrays.

 numpy.dstack( ( your_input_array, numpy.zeros((25, 54)) ) ) 
+13
source

If you have the current image as an rgb variable, just use:

 rgba = numpy.concatenate((rgb, numpy.zeros((205, 54, 1))), axis=2) 

A function union combines an array of rgb and zeros. The Zeros function creates an array of zeros. We set the axis to 2, which means we are merging in the dimensions of the tirade. Note: axis is counted from 0.

+5
source

Np array style, depth measurement stack (channel measurement, 3rd dimension):

 rgba = np.dstack((rgb, np.zeros(rgb.shape[:-1]))) 

but you should use the OpenCV function:

 rgba = cv2.cvtColor(rgb, cv2.COLOR_RGB2RGBA) 
0
source

not sure if you are still looking for an answer.

Recently, I am trying to achieve what you want to do with numpy, because I needed to make png with a 24-bit depth of 32. I agree that it makes sense to use dstack, but I could not get it to work. Instead, I used the insert, and it seems to have 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.

0
source

All Articles