在Python中将RGBA转换为RGB

时间:2018-05-14 13:25:22

标签: python-3.x image type-conversion python-imaging-library rgb

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

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

2 个答案:

答案 0 :(得分:4)

您可能想要使用图像的转换方法:

import PIL.Image


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

答案 1 :(得分:0)

对于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是类型为numpy的{​​{1}}数组,具有4个通道。输出是一个uint8数组,其中包含3个类型为numpy的通道。

使用uint8imread,可以很容易地通过库imageio进行此数组的I / O操作。

相关问题