我希望我用正确的措词,因为我是这一切的新手。我需要保存4个通道的tiff图像,特别是R,G,B和A通道。
当我尝试使用Image.save()保存具有4个通道的tiff时,生成的图像是RGBA图像,但是在photoshop中检查tiff时,仅有的通道是RGB,而没有Alpha。有什么方法可以将第4通道(单独的alpha通道)的4个通道合并为RGBA图像?
下面是我尝试过的例子
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)
在此示例中,生成的输出图像仅具有3个通道(RGB)。
感谢进阶!
编辑: 如果我的问题不清楚,请更改上面提供的示例代码;另外,请参见下面的图片,以直观地了解我要做什么:
答案 0 :(得分:0)
更新后的答案
好的,我想你是这个意思:
#!/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')
哪个使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')
答案 1 :(得分:0)
因此,我想出了使用OpenCV2库而不是PIL解决此问题的方法。看看下面我是怎么做到的:
import cv2
# read original image
original = cv2.imread(original_image_path, cv2.IMREAD_UNCHANGED)
# get dimensions for resizing mask
height, width, channels = original.shape
# read alpha image
alpha = cv2.imread(alpha_path)
# resize alpha image to match original
alpha_resized = cv2.resize(alpha, (height,width))
# split alpha_resized into individual channels
channels = cv2.split(alpha_resized)
# apply to 4th channel of original
original[:,:,3] = channels[0]
# write new image file with alpha channel
cv2.imwrite(output_path,original)