gpt4 book ai didi

Python PIL - 将多层图像合并为一个

转载 作者:行者123 更新时间:2023-12-05 01:16:05 27 4
gpt4 key购买 nike

我有多个白色背景的 PNG 图像,并且图像的某些部分充满了图案(可能是不同的颜色,黑色、蓝色、红色、黄色等)。

如何使用 Python PIL 库将所有​​这些图像合并为一张图像,以便所有非白色部分出现在一张图像上?

举个例子,

我有以下 3 张 PNG 图片:

Image #1 Image #2 Image #3

现在,我想将所有这些图像合并为一张图像,这样背景仍然是白色的,但所有图案都出现在一张图像上。

例如,我选择了 2 张图片并尝试了以下操作:

#! /usr/bin/python

from PIL import Image

background = Image.open("check00001.png")
foreground = Image.open("check00002.png")

background.paste(foreground, (0, 0), foreground)
background.show()

但它以这样一种方式合并图像,使得只有其中一个图像的内容可见。

我需要为一大组图像执行此操作,其中每个图像都有最终图像的一小部分。

最佳答案

据我所知,您可以使用 Pillow 轻松地将图像的白色像素转换为透明像素,然后一层又一层地遮盖它们。

要将白色像素转换为透明,您需要先将图像数据转换为缓冲区,然后从缓冲区重新创建它,示例代码如下:

from PIL import Image 
# your loop here
img = Image.open('img.png')
img = img.convert("RGBA")
datas = img.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)

img.putdata(newData)
img.save("mod_img1.png", "PNG")

然后像在代码中一样进行常规粘贴。

background = Image.open("mod_img1.png") 
foreground = Image.open("mod_img2.png")

background.paste(foreground, (0, 0), foreground)
background.show()

关于Python PIL - 将多层图像合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54499763/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com