【问题标题】:Python: Combining images using paste with overlapping pixels and areas with alpha channel=0Python:使用粘贴与重叠像素和 alpha 通道 = 0 的区域组合图像
【发布时间】:2023-03-24 11:48:02
【问题描述】:

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

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')

【问题讨论】:

    标签: python image python-imaging-library paste


    【解决方案1】:

    我认为您对图像有误解 - 边框图像到处都有像素。它不可能是“丢失”的像素。可以有一个带有 Alpha 通道的图像,该通道类似于 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.
    

    【讨论】:

    • 感谢您的回复。我相信我在 topimage.png 上有一个透明通道(当我在 gimp 中查看它时它就在那里)但是当我用 python 粘贴它时它消失了。有没有我可以设置的标志或其他东西,以便在粘贴时记住我的 Alpha 通道。
    • 非常感谢这解决了所有问题!
    猜你喜欢
    • 2021-01-13
    • 2013-03-19
    • 2015-12-20
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多