You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python从文件夹随机选取多张图像并分层合成为单张PNG图像

多文件夹随机选图分层堆叠合成PNG Python脚本

前置依赖

需先安装Pillow图像处理库,执行以下命令安装:
pip install pillow

完整可运行代码

import os
import random
from PIL import Image

# -------------------------- 配置项 可根据需求修改 --------------------------
# 4个素材文件夹路径,顺序对应堆叠层级:第一个是最底层,第四个是最上层
FOLDER_PATHS = [
    "./layer1",  # 替换为你的第一层文件夹路径
    "./layer2",  # 替换为你的第二层文件夹路径
    "./layer3",  # 替换为你的第三层文件夹路径
    "./layer4"   # 替换为你的第四层文件夹路径
]
# 合成图输出文件夹路径
OUTPUT_DIR = "./output"
# 需要生成的合成图总数量
GENERATE_COUNT = 10
# 支持读取的图片格式
SUPPORTED_IMG_EXTS = (".png", ".jpg", ".jpeg", ".webp")
# ------------------------------------------------------------------------

# 预加载每个文件夹下的所有可用图片路径
layer_img_paths = []
for folder in FOLDER_PATHS:
    if not os.path.exists(folder):
        raise FileNotFoundError(f"文件夹不存在:{folder}")
    imgs = [
        os.path.join(folder, f) 
        for f in os.listdir(folder) 
        if f.lower().endswith(SUPPORTED_IMG_EXTS)
    ]
    if not imgs:
        raise ValueError(f"文件夹 {folder} 中未找到符合格式的图片")
    layer_img_paths.append(imgs)

# 创建输出文件夹
os.makedirs(OUTPUT_DIR, exist_ok=True)

for idx in range(GENERATE_COUNT):
    # 从每个文件夹各随机选1张图
    selected_imgs = []
    base_size = None
    for img_list in layer_img_paths:
        img_path = random.choice(img_list)
        img = Image.open(img_path).convert("RGBA")
        # 统一尺寸:默认和第一张图尺寸保持一致
        if base_size is None:
            base_size = img.size
        else:
            img = img.resize(base_size, Image.Resampling.LANCZOS)
        selected_imgs.append(img)
    
    # 逐层堆叠
    composite = selected_imgs[0]
    for layer in selected_imgs[1:]:
        composite = Image.alpha_composite(composite, layer)
    
    # 保存为PNG
    output_path = os.path.join(OUTPUT_DIR, f"composite_{idx+1}.png")
    composite.save(output_path, format="PNG")
    print(f"已生成:{output_path}")

print(f"所有合成图已生成完毕,共 {GENERATE_COUNT} 张,保存在 {OUTPUT_DIR} 目录下")

使用说明

  • 替换配置项中的FOLDER_PATHS为你自己的4个素材文件夹路径,列表顺序就是堆叠的层级,第一个元素对应最底层,最后一个对应最上层
  • 修改OUTPUT_DIR为你存放合成结果的文件夹路径
  • 修改GENERATE_COUNT为你需要生成的合成图总数量
  • 如果不需要自动统一图层尺寸,可以删除resize相关的代码段,仅保留img = Image.open(img_path).convert("RGBA")即可

内容的提问来源于stack exchange,提问作者Johny Leyer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 22:51:01