在Python中将RGBA转换为RGB

16

如何使用PIL最简单且最快地将RGBA图像转换为RGB?我只需要从一些图像中删除A通道。

我找不到一个简单的方法来做到这一点,我不需要考虑背景。

3个回答

37

你可能想使用图像的convert方法:

import PIL.Image


rgba_image = PIL.Image.open(path_to_image)
rgb_image = rgba_image.convert('RGB')

17

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

参数rgba是一个包含4个通道的uint8类型的numpy数组。输出结果是一个包含3个通道的uint8类型的numpy数组。

使用库imageio中的imreadimsave函数可以轻松进行该数组的输入输出操作。


0
@Feng Wang 感谢你的回答。如果你的图像有一个额外的第一维作为批处理,你可以使用以下方法。即使是对于单个图像,你仍然可以使用它。而且它也适用于不同顺序的RGB通道。
def compose_alpha(image_with_alpha):

    image_with_alpha = image_with_alpha.astype(np.float32)

    image, alpha = image_with_alpha[..., :3], image_with_alpha..., 3:] / 255.0

    image = image * alpha + (1.0 - alpha) * 255.0

    image = image.astype(np.uint8)
    
    return image

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接