如何使用PIL保存多于3个通道的图像?

问题描述 投票:1回答:2

我需要保存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)。

请参见下图,以直观地了解我要做什么:

“

python python-imaging-library alpha channels
2个回答
1
投票

更新后的答案

好吧,我想你是这个意思:

#!/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

enter image description here

alpha.png

enter image description here

进入result.tif

enter image description here

原始答案

这是创建和保存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')

enter image description here


1
投票

我想出了使用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)
© www.soinside.com 2019 - 2024. All rights reserved.