Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert RGBA to RGB in Python

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.

like image 799
Jimbo Avatar asked May 14 '18 13:05

Jimbo


People also ask

Can you convert RGB to RGBA?

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.


2 Answers

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')
like image 169
Noctis Skytower Avatar answered Oct 16 '22 11:10

Noctis Skytower


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.

like image 37
Feng Wang Avatar answered Oct 16 '22 09:10

Feng Wang