在Python中将RGBA转换为RGB

Jim*_*mbo 1 rgb image type-conversion python-imaging-library python-3.x

使用PIL将RGBA图像转换为RGB的最简单,最快的方法是什么?我只需要从某些图像中删除A通道即可。

我找不到一个简单的方法来执行此操作,我不需要考虑背景。

Fen*_*ang 9

numpy数组的情况下,我使用这个解决方案:

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' )
Run Code Online (Sandbox Code Playgroud)

其中参数rgba是具有 4 个通道numpy的类型数组uint8。输出是一个numpy具有 3 个通道的数组,类型为uint8

这个数组很容易imageio通过使用imread和的库进行I/O imsave


Noc*_*wer 8

您可能要使用图像的convert方法:

import PIL.Image


rgba_image = PIL.Image.open(path_to_image)
rgb_image = rgba_image.convert('RGB')
Run Code Online (Sandbox Code Playgroud)