使用 PIL 将 RGBA 图像转换为 RGB 最简单、最快的方法是什么? 我只需要从一些图像中删除 A 通道。
我找不到简单的方法来做到这一点,我不需要考虑背景。
您可能想使用图像的转换方法:
import PIL.Image
rgba_image = PIL.Image.open(path_to_image)
rgb_image = rgba_image.convert('RGB')
对于
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 个通道的 numpy
类型的 uint8
数组。输出是一个 numpy
数组,具有 3 个类型为 uint8
的通道。
imageio
使用 imread
和 imsave
进行 I/O。
@王峰感谢您的回答。如果您的图像批量具有附加的第一维度,则可以使用以下内容。您仍然可以将其用于单个图像。无论 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