Reputation: 2583
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?
Upvotes: 51
Views: 49299
Reputation: 1686
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.
Upvotes: 2
Reputation:
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)
Upvotes: 2
Reputation: 41
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
Upvotes: 4
Reputation: 18446
Just slice the array to get the first three entries of the last dimension:
image_without_alpha = image[:,:,:3]
Upvotes: 128