我如何从文件夹中随机 select 多个图像,然后将它们作为单个图像在 Python 中分层?

How do I randomly select multiple images from folders and then layer them as a single image in Python?

我正在尝试使用 python 创建一个 composite .png 随机选择和分层的 png 全部具有透明背景,因此所有图层在成品中都是可见的。

例如,使用大小递减的不同颜色的圆圈:名为 'layer1' 的最大圆圈的文件夹包含 3 个相同大小的不同颜色的圆圈和透明背景上的 position,'layer2' 文件夹包含 3 个较小的相同大小的不同颜色的圆圈和 position 等等。我想先从 'layer1' 中随机选择,然后从 'layer2' 中随机选择,然后保存到输出文件。

我已经让代码在没有随机选择图像的情况下工作,而是使用特定的图像文件。当我尝试使用 os 随机选择文件时,我收到消息:

'PIL.UnidentifiedImageError: cannot identify image file '.DS_Store''

随机选择代码和图像粘贴代码之间似乎有冲突。根据我的工作代码,我尝试在 random.choice 前加上 Image.open 前缀,但这显然不是那么简单。

重要的是我可以将所选图像保持为透明背景,因为堆叠的图像超过两张并且它们被放置在彩色背景上。

这是我的原始(工作)代码:

from PIL import Image
import random, os
import numpy as np

layer1 = Image.open('bigcircle/Circle 1.png', 'r')
layer2 = Image.open('mediumcircle/Circle 2.png', 'r')

img = Image.new('RGB', (4961, 4961), color = (0, 220, 15))
img.paste(layer1, (0, 0), layer1)
img.paste(layer2, (0, 0), layer2)

img.save("output.png")

我尝试随机选择,这会引发错误,我已将“layer1 = Image.open('layer1/Circle 1.png', 'r')”更改为以下内容 (如果我没有遇到错误,会对 layer2 做同样的事情)。

path = r"bigcircle"
layer1 = random.choice([
    x for x in os.listdir(path)
    if os.path.isfile(os.path.join(path, x))
])

也许是这样的?这会在您的两个目录中发现 PNG 图像的所有路径,然后从每个 directory/layer 中随机选择一个。然后它遍历选定的路径,并将它们粘贴到单个图像中。我还没有测试过这个,但它应该可以工作:

from pathlib import Path
from random import choice

layers = [list(Path(directory).glob("*.png")) for directory in ("bigcircle/", "mediumcircle/")]

selected_paths = [choice(paths) for paths in layers]

img = Image.new("RGB", (4961, 4961), color=(0, 220, 15))
for path in selected_paths:
    layer = Image.open(str(path), "r")
    img.paste(layer, (0, 0), layer)


img.save("output.png")