如何批量将文件夹图片按顺序两两垂直拼接?运行代码报FileNotFoundError
问题排查与修复方案
核心报错原因
你定义了源图片存储路径directory = "C:/Users/seren/Desktop/ResizeImages",但构建文件名列表、打开图片时没有拼接源路径,程序默认会在脚本的运行工作目录查找图片,而不是你指定的ResizeImages文件夹,因此触发文件不存在报错。
其他潜在问题
- 硬编码的文件名范围
range(1,50)只能覆盖49张图片,无法满足200+图片的处理需求,且硬编码容易出现文件名匹配误差。 - 若总图片数为奇数,遍历到最后一组时取
images_list[j+1]会触发索引越界报错。 - 若输出目录
new_directory未提前创建,保存拼接图片时会触发路径不存在报错。 - 部分版本numpy无法直接识别
np.vstack内的生成器表达式,需转为列表格式。
修正后可运行代码
import os import numpy as np from PIL import Image # 配置参数 directory = "C:/Users/seren/Desktop/ResizeImages" ext = ".jpg" new_file_name = "vBos" new_directory = "C:/Users/seren/Desktop/vcombine" # 自动创建输出目录(不存在的话) os.makedirs(new_directory, exist_ok=True) # 自动读取源文件夹下所有指定后缀的图片,按文件名排序 images_list = sorted([f for f in os.listdir(directory) if f.lower().endswith(ext)]) # 如果文件名是数字序号但默认排序不符合预期,可替换为自定义排序逻辑 count = 1 for j in range(0, len(images_list), 2): # 跳过最后单出来的一张图(如果总张数是奇数) if j + 1 >= len(images_list): break name = f"{new_file_name}{count}{ext}" # 拼接源路径再打开图片 img1_path = os.path.join(directory, images_list[j]) img2_path = os.path.join(directory, images_list[j+1]) imgs = [Image.open(img1_path), Image.open(img2_path)] # 取最小尺寸统一缩放 min_img_shape = sorted([(np.sum(i.size), i.size) for i in imgs])[0][1] # 转列表再拼接避免numpy兼容性问题 imgs_arr = [np.asarray(i.resize(min_img_shape)) for i in imgs] imgs_comb = np.vstack(imgs_arr) imgs_comb = Image.fromarray(imgs_comb) imgs_comb.save(os.path.join(new_directory, name)) count += 1
内容的提问来源于stack exchange,提问作者Serena Taylor
相关产品推荐
相关产品推荐

