Python图片缩放脚本优化:避免重复处理_resized后缀图片
解决方案
要实现仅处理原图、跳过已生成的带_resized后缀的缩放图,只需在遍历文件时添加过滤逻辑,同时可额外增加输出文件存在性检查避免重复处理原图。以下是修改后的代码:
import cv2 import glob import os def img_reshape(img_file): image = cv2.imread(str(img_file), 1) # 读取失败时直接返回,避免报错 if image is None: print(f"无法读取文件: {img_file}") return False resized_image = cv2.resize(image, (int(image.shape[1]/2), int(image.shape[0]/2))) file_name = os.path.splitext(os.path.basename(img_file))[0] output_path = f"files\\sample_images\\{file_name}_resized.jpg" # 检查输出文件是否已存在,存在则跳过 if os.path.exists(output_path): print(f"输出文件已存在,跳过: {output_path}") return True return cv2.imwrite(output_path, img=resized_image) def main(): for img_path in glob.glob("files\\sample_images\\*.jpg"): # 获取文件名(不含路径和后缀) file_name = os.path.splitext(os.path.basename(img_path))[0] # 跳过文件名以"_resized"结尾的文件 if file_name.endswith("_resized"): continue img_reshape(img_path) if __name__ == "__main__": main()
修改说明
- 过滤已生成的缩放图:在
main函数中,通过file_name.endswith("_resized")判断当前文件是否是已生成的缩放图,若是则直接跳过。 - 避免重复处理原图:在
img_reshape函数中,添加os.path.exists(output_path)检查,若输出文件已存在则跳过保存操作,避免重复处理同一原图。 - 增加错误处理:添加图片读取失败的判断,避免因文件损坏或路径错误导致程序崩溃。
内容的提问来源于stack exchange,提问作者user23265679
相关产品推荐
相关产品推荐

