如何从目录中选择随机图像?python

2024-05-13 22:13:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序的目标是获取一个随机png图像,并将其放置在另一个随机图像上。到目前为止,我有它,所以它得到的图像,粘贴到另一个,并保存它,并希望它是随机的

from PIL import Image
from PIL import ImageFilter

France = Image.open(r"C:\Users\Epicd\Desktop\Fortnite\France.png")
FranceRGB = France.convert('RGB')
Crimson_Scout = Image.open(r"C:\Users\Epicd\Desktop\Fortnite\Crimson_Scout.png")

FranceRGB.paste(Crimson_Scout, box=(1,1), mask=Crimson_Scout)
FranceRGB.save(r"C:\Users\Epicd\Desktop\Fortnite\Pain1.png")
 

Tags: from图像imageimportpilpngopenusers
3条回答

最简单的方法是列出目录中的文件,然后从给定路径中随机选择。大概是这样的:

import os
import random

random.choice(os.listdir("/path/to/dir"))

添加一些逻辑以确保筛选出目录,并且只接受具有特定扩展名(pbg、jpg等)的文件可能是明智的做法

您可以从工作目录中随机选取2个*.png文件,如下所示:

import glob
import random

all_pngs =  glob.glob("./*.png")
randPng1 = random.choice(all_pngs)
randPng2 = random.choice(all_pngs)
print randPng1
print randPng2

然后您可以使用这两个变量(randPng1randPng2),而不是图像的硬编码路径

如果随机选取相同的png两次不是您想要的,那么您需要从all_pngs数组中移除randPng1元素,然后再从数组中获取第二个随机元素

可以使用os.listdir获取目录中所有项的路径列表。然后使用random class从该列表中选择项目

相关问题 更多 >