如何使用 PIL 保存超过 3 个通道的图像?

Sha*_* P. 5 python alpha python-imaging-library channels

我需要用 4 个通道保存 tiff 图像,特别是 R、G、B 和 A 通道。

当我尝试使用Image.save()4 个通道保存 tiff 时,生成的图像是 RGBA 图像,但是在 Photoshop 中检查 tiff 时,唯一的通道是 RGB,没有 Alpha。有没有办法将 4 个通道合并到一个 RGBA 图像中,并带有第 4 个通道(一个单独的 alpha 通道)?

以下是我尝试过的示例

from PIL import Image

# import image A
inputImageA = Image.open(input_imageA_path)

# import image B
inputImageB = Image.open(input_imageB_path)

# split channels
R, G, B, A = inputImageA.split()
alpha_channel = inputImageA.split()[-1]

# merge 4 channels back into a single image
outputImage = Image.merge("RGBA", [R,G,B,alpha_channel])

# save the new image
outputImage.save(ouput_image_path)
Run Code Online (Sandbox Code Playgroud)

在此示例中,生成的输出图像只有 3 个通道 (RGB)。

请参阅下图以直观说明我正在尝试做的事情:

例子

Mar*_*ell 2

更新答案

好吧,我想你现在的意思是:

#!/usr/bin/env python3

from PIL import Image

# Open background image, ensuring RGB
im = Image.open('start.png').convert('RGB')

# Open alpha channel, ensuring single channel
alpha = Image.open('alpha.png').convert('L')

# Add that alpha channel to background image
im.putalpha(alpha)

# Save as TIFF
im.save('result.tif')
Run Code Online (Sandbox Code Playgroud)

这使得start.png

在此输入图像描述

alpha.png

在此输入图像描述

进入result.tif

在此输入图像描述

原答案

下面是创建和保存 4 通道 RGBA TIFF 的简单示例:

#!/usr/bin/env python3

from PIL import Image, ImageDraw

# Create RGB image full of yellow
w, h = 640, 480
im =Image.new('RGB',(w,h),color=(255,255,0))

# Create alpha channel of white i.e. opaque
alpha =Image.new('L',(w,h),color=255)

# Get drawing context to draw into alpha channel and draw black (i.e. transparent) rectangle
d = ImageDraw.Draw(alpha)
d.rectangle([10,40,200,250],fill=0)

# Add that alpha channel to yellow image
im.putalpha(alpha)

# Save as TIFF
im.save('result.tif')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述