Convert RGBA to RGB in Python

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.


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')