Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discarding alpha channel from images stored as Numpy arrays

Tags:

python

math

numpy

I load images with numpy/scikit. I know that all images are 200x200 pixels.

When the images are loaded, I notice some have an alpha channel, and therefore have shape (200, 200, 4) instead of (200, 200, 3) which I expect.

Is there a way to delete that last value, discarding the alpha channel and get all images to a nice (200, 200, 3) shape?

like image 449
cwj Avatar asked Mar 09 '16 20:03

cwj


People also ask

How to Remove alpha channel from image in Python?

To remove image alpha channel, we can use ImageMagick application.

Can NumPy array store images?

fromarray() Function to Save a NumPy Array as an Image. The fromarray() function is used to create an image memory from an object which exports the array. We can then save this image memory to our desired location by providing the required path and the file name.

How NumPy is used in image processing?

It is used in the domain of linear algebra, Fourier transforms, matrices, and the data science field. which is used. NumPy arrays are way faster than Python Lists. You must have known about Image processing Libraries such as OpenCV, Python Image Library(PIL), Scikit-Image, and many more.


2 Answers

Just slice the array to get the first three entries of the last dimension:

image_without_alpha = image[:,:,:3] 
like image 161
Carsten Avatar answered Oct 13 '22 23:10

Carsten


scikit-image builtin:

from skimage.color import rgba2rgb from skimage import data img_rgba = data.logo() img_rgb = rgba2rgb(img_rgba) 

https://scikit-image.org/docs/dev/user_guide/transforming_image_data.html#conversion-from-rgba-to-rgb-removing-alpha-channel-through-alpha-blending
https://scikit-image.org/docs/dev/api/skimage.color.html#rgba2rgb

like image 37
Kailo Avatar answered Oct 13 '22 23:10

Kailo