15

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.

Jimbo
  • 444
  • 2
  • 7
  • 22

2 Answers2

37

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')
ejuhjav
  • 2,660
  • 2
  • 21
  • 32
Noctis Skytower
  • 21,433
  • 16
  • 79
  • 117
17

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.

Feng Wang
  • 1,506
  • 15
  • 17