Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding alpha channel to RGB array using numpy

Tags:

python

numpy

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?

like image 617
Melanie Avatar asked Sep 22 '16 15:09

Melanie


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)) ) )
like image 131
kennytm Avatar answered Nov 17 '22 18:11

kennytm


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.

like image 42
Primoz Avatar answered Nov 17 '22 18:11

Primoz


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)
like image 8
lbsweek Avatar answered Nov 17 '22 20:11

lbsweek


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.

like image 5
TAITONIUM Avatar answered Nov 17 '22 19:11

TAITONIUM