【问题标题】:How do I randomly select multiple images from folders and then layer them as a single image in Python?如何从文件夹中随机选择多个图像,然后在 Python 中将它们分层为单个图像?
【发布时间】:2021-09-17 11:10:01
【问题描述】:

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

例如使用不同颜色的减小尺寸的圆圈:一个名为“layer1”的最大圆圈的文件夹包含 3 个大小和位置相同的不同颜色的圆圈在透明背景上,“layer2”文件夹包含 3 个较小的不同颜色的圆圈相同的大小和位置等。我想先从“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))
])

【问题讨论】:

  • 你得到的错误是什么?

标签: python image random png


【解决方案1】:

可能是这样的?这会发现两个目录中 PNG 图像的所有路径,然后从每个目录/层中随机选择一个。然后它遍历选定的路径,并将它们粘贴到单个图像中。我没有对此进行测试,但它应该可以工作:

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

【讨论】:

  • 很高兴它的工作!如果您有任何问题,请告诉我。
  • 事实上,我愿意。我不确定礼仪,所以没有在这些 cmets 中发布后续内容,而是提出了一个新问题(尽我所能给予您的信任):stackoverflow.com/questions/68292339/…
  • 不用担心,谢谢!我已经在那里发布了答案 - 看看。
猜你喜欢
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 2012-06-13
  • 2012-06-10
  • 1970-01-01
相关资源
最近更新 更多