50

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?

cwj
  • 2,473
  • 5
  • 28
  • 38
  • 11
    Assuming, you are using `Image.open()` you can discard the alpha value by doing `Image.open().convert('RGB')`. Hope this helps someone in the future. – Pramesh Bajracharya Feb 11 '19 at 11:08

4 Answers4

124

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

image_without_alpha = image[:,:,:3]
Carsten
  • 17,991
  • 4
  • 48
  • 53
  • I think this will reduce the quality of the image? – Aleksandar Jovanovic Sep 19 '17 at 11:33
  • 21
    @AleksandarJovanovic do you precisely know what you mean by "quality of the image"? Dropping alpha removes information about transparency of pixels but does not influence other information (e.g., color). – dolphin Nov 25 '17 at 20:42
4

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

Kailo
  • 41
  • 3
2

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)
Udesh
  • 2,415
  • 2
  • 22
  • 32
2

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.

phnghue
  • 1,578
  • 2
  • 10
  • 9