我的程序的目标是拍摄一个随机的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")
答案 0 :(得分:3)
最简单的方法是在目录中列出文件,然后从给定的路径中随机选择。像这样:
import os
import random
random.choice(os.listdir("/path/to/dir"))
添加一些逻辑以确保您正在过滤目录,并且仅接受具有特定扩展名(pbg,jpg等)的文件,这可能很聪明
答案 1 :(得分:0)
您可以使用os.listdir获取目录中所有项目的路径列表。然后使用random class从该列表中选择项目。
答案 2 :(得分:0)
您可以从工作目录中随机选择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
然后您可以使用这两个变量(randPng1
和randPng2
),而不是图像的硬编码路径。
如果不想两次随机选择相同的png,则需要从randPng1
数组中删除all_pngs
元素,然后再从数组中获取第二个随机元素。
答案 3 :(得分:0)
您可以将random.choice
和os.walk
用于该任务。
用于选择图像的代码如下:
import os
import random
path = "path/to/your/images.png"
images = []
# This will get each root, dir and file list in the path specified recursively (like the "find" command in linux, but separating files, from directories, from paths).
# root is the full path from your specified path to the the directory it is inspecting
# dirs is a list containing all the directories found in the current inspecting directory
# files is a list containing all the files found in the current inspecting directory
for root, dirs, files in os.walk(path):
# This will filter all the .png files in case there is something else in the directory
# If your directory only has images, you can do this:
# images = files
# instead of filtering the '.png' images with the for loop
for f in files:
if f[-4:] == '.png':
images.append(f)
print(random.choice(images))