Discarding alpha channel from images stored as Numpy arrays

Question:

I load images with numpy/scikit. I know that all images are 200×200 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?

Asked By: cwj

||

Answers:

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

image_without_alpha = image[:,:,:3]
Answered By: Carsten
Answered By: Kailo

Use PIL.Image to remove the alpha channel

from PIL import Image
import numpy as np

img = Image.open("c:>path_to_image")
img = img.convert("RGB") # remove alpha
image_array = np.asarray(img) # converting image to numpy array
print(image_array.shape)
img.show()

If images are in numpy array to convert the array to Image use Image.fromarray to convert array to Image

pilImage = Image.fromarray(numpy_array)
Answered By: Udesh

If you need higher speed, you can use cvtColor in cv2 (openCV):

img_RGB = cv2.cvtColor(img_RGBA, cv2.COLOR_RGBA2RGB);

It took 1/4 time of numpy slice method.

Answered By: phnghue
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.