Python:使用具有重叠像素和alpha通道=0的区域的粘贴组合图像



我正在尝试将三个图像组合在一起。我想要的底部图像是一张700x900的全黑像素图像。最重要的是,我想粘贴一个400x400的图像,偏移量为100200。最重要的是,我想粘贴一个700x900的图像边框。图像边框内部的alpha=0,周围的alpha=0,因为它没有直边。当我运行我粘贴在下面的代码时,我遇到了两个问题:

1) 在alpha通道=0的边界图像上的任何地方,alpha通道都已设置为255,并且显示的颜色是白色,而不是黑色背景和我放置边界的图像。

2) 边界图像的质量已经显著降低,看起来与应有的大不相同。

此外:部分边框图像将覆盖我放置边框的图像的一部分。所以我不能只是切换粘贴的顺序。

提前感谢您的帮助。

#!/usr/bin/python -tt
from PIL import ImageTk, Image
old_im2 = Image.open('backgroundImage1.jpg') # size = 400x400
old_im = Image.open('topImage.png') # size = 700x900
new_size = (700,900)
new_im = Image.new("RGBA", new_size) # makes the black image
new_im.paste(old_im2, (100, 200))
new_im.paste(old_im,(0,0))
new_im.show()
new_im.save('final.jpg')

我认为您对图像有一个误解——边界图像确实到处都有像素。它不可能是"缺失"像素。可以具有具有阿尔法通道的图像,阿尔法通道是类似于RGB通道的通道,但是指示透明度。

试试这个:

1.确保topImage.png具有透明度通道,并且要"丢失"的像素是透明的(即具有最大alpha值)。你可以通过这种方式进行双重检查:

print old_im.mode  # This should print "RGBA" if it has an alpha channel.

2.在"RGBA"模式下创建new_im

new_im = Image.new("RGBA", new_size) # makes the black image
# Note the "A" --------^

3.试试这个粘贴语句:

new_im.paste(old_im,(0,0), mask=old_im)  # Using old_im as the mask argument should tell the paste function to use old_im's alpha channel to combine the two images.

最新更新