What is the simplest and fastest way to convert an RGBA image in RGB using PIL? I just need to remove the A channel from some images.
I can't find a simple method to do this, I don't need to take background into consideration.
Converts an image from RGB to RGBA format. This function can operate with ROI (see Image Regions of Interest). This function performs conversion from RGB image to RGBA image leaving pixel values unchanged, only changing number of channels from 3 channels to 4 channels.
You probably want to use an image's convert method:
import PIL.Image
rgba_image = PIL.Image.open(path_to_image)
rgb_image = rgba_image.convert('RGB')
In case of numpy
array, I use this solution:
def rgba2rgb( rgba, background=(255,255,255) ):
row, col, ch = rgba.shape
if ch == 3:
return rgba
assert ch == 4, 'RGBA image has 4 channels.'
rgb = np.zeros( (row, col, 3), dtype='float32' )
r, g, b, a = rgba[:,:,0], rgba[:,:,1], rgba[:,:,2], rgba[:,:,3]
a = np.asarray( a, dtype='float32' ) / 255.0
R, G, B = background
rgb[:,:,0] = r * a + (1.0 - a) * R
rgb[:,:,1] = g * a + (1.0 - a) * G
rgb[:,:,2] = b * a + (1.0 - a) * B
return np.asarray( rgb, dtype='uint8' )
in which the argument rgba
is a numpy
array of type uint8
with 4 channels. The output is a numpy
array with 3 channels of type uint8
.
This array is easy to do I/O with library imageio
using imread
and imsave
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With