Python循环拼接双面相机阵列图像时V1仅保留最后一张问题求解
Python双面相机阵列图像逐对拼接逻辑修复方案
问题根源
原逻辑遍历所有文件时,每次遇到0_开头的V1图像就全局覆盖V1变量,没有存储所有V1的编号对应关系,导致后续处理每个V2时,调用的都是遍历到的最后一个V1,无法实现编号一一对应拼接。同时路径直接字符串拼接的写法也存在跨系统兼容性问题。
修复思路
- 先遍历一次目录,将所有V1图像按编号存入字典,键为两个视角匹配用的公共编号,值可以是V1图像对象或文件路径
- 再遍历所有V2图像,按编号从字典中取出对应的V1执行拼接
- 增加匹配不到的异常跳过逻辑,避免运行时报错
完整修改代码
import os from PIL import Image # 先确保输出目录存在 os.makedirs(newpath2, exist_ok=True) # 第一步:构建V1图像的编号映射字典 v1_map = {} for filename in os.listdir(newpath): file_path = os.path.join(newpath, filename) # 跳过非文件项 if not os.path.isfile(file_path): continue if filename.startswith('0_000'): # 提取匹配键:去掉0_000前缀,剩余部分为公共编号(可根据实际文件名规则调整) # 示例:0_000023.jpg → 匹配键为023.jpg,对应V2文件名为1_023.jpg match_key = filename[len('0_000'):] # 若图像数量多,可改为存路径减少内存占用:v1_map[match_key] = file_path v1_map[match_key] = Image.open(file_path) # 第二步:遍历V2图像逐对拼接 for filename in os.listdir(newpath): file_path = os.path.join(newpath, filename) if not os.path.isfile(file_path): continue if filename.startswith('1_'): # 提取V2对应的匹配键:去掉1_前缀 match_key = filename[len('1_'):] # 无对应V1则跳过 if match_key not in v1_map: print(f"跳过无匹配V1的文件:{filename}") continue # 若v1_map存的是路径,改为V1 = Image.open(v1_map[match_key]) V1 = v1_map[match_key] V2 = Image.open(file_path) # 原有拼接逻辑,可根据实际需求调整画布尺寸、粘贴坐标 v2_width, v2_height = V2.size new_image = Image.new('RGB', (2 * v2_width, v2_height), (250, 250, 250)) new_image.paste(V2, (0, 100)) new_image.paste(V1, (v2_width, 0)) EXIF = V2.getexif() output_path = os.path.join(newpath2, filename) new_image.save(output_path, format=new_image.format, optimize=True, exif=EXIF) # 释放内存,可选 V2.close() V1.close()
规则适配说明
如果你的文件名编号规则和示例的提取逻辑不同,只需调整match_key的提取规则即可:
- 若两个文件名的纯数字编号完全对应,可使用正则提取公共数字部分:
import re; match_key = re.search(r'(\d+)\.\w+$', filename).group(1) - 若前缀长度不同,调整
len('xxx')里的前缀字符串即可
内容的提问来源于stack exchange,提问作者alaskamoe
相关产品推荐
相关产品推荐

