Python使用Pillow库按指定顺序合并多图层实现生成式艺术拼贴
实现思路
- 首先建立素材类型标识到选中图片完整路径的映射字典,方便遍历顺序数组时直接取值
- 初始化合成结果为顺序数组第一个元素对应的图像,然后按顺序遍历后续图层依次叠加
- 注意你原代码仅获取了素材文件名,打开图片时需要拼接对应素材目录的路径,否则会报文件找不到错误
完整实现代码
import os import random from PIL import Image # 1. 加载各类型素材的完整路径 skin = [os.path.join('skin', file) for file in os.listdir('skin') if file.endswith('.png')] hair = [os.path.join('hair', file) for file in os.listdir('hair') if file.endswith('.png')] head = [os.path.join('head', file) for file in os.listdir('head') if file.endswith('.png')] mouth = [os.path.join('mouth', file) for file in os.listdir('mouth') if file.endswith('.png')] nose = [os.path.join('nose', file) for file in os.listdir('nose') if file.endswith('.png')] eyes = [os.path.join('eyes', file) for file in os.listdir('eyes') if file.endswith('.png')] # 2. 随机选择各类型素材,存入字典方便按标识取值 selected = { 'skin': random.choice(skin), 'hair': random.choice(hair), 'head': random.choice(head), 'mouth': random.choice(mouth), 'nose': random.choice(nose), 'eyes': random.choice(eyes) } # 3. 指定叠加顺序 order = ['head','skin','mouth','eyes','nose','hair'] # 4. 按顺序合并图层 # 初始化底图为第一个图层 composite_img = Image.open(selected[order[0]]).convert('RGBA') # 遍历后续图层依次叠加 for layer_name in order[1:]: current_layer = Image.open(selected[layer_name]).convert('RGBA') composite_img = Image.alpha_composite(composite_img, current_layer) # 最终结果可直接保存或显示 composite_img.save('final_collage.png') composite_img.show()
补充说明
alpha_composite要求两张图像都是RGBA模式,代码中加了convert('RGBA')做兼容,避免部分素材模式不匹配报错- 你之前用的
random.choices(xxx)[0]可以直接简化为random.choice(xxx),效果完全一致,写法更简洁
内容的提问来源于stack exchange,提问作者DobotJr
相关产品推荐
相关产品推荐

