import os from PIL import Image def flip_and_duplicate_image(image_path, output_path): """ Flip an image horizontally and save a copy with a suffix. """ try: with Image.open(image_path) as img: flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT) flipped_img.save(output_path) return True except Exception as e: print(f"无法处理图像 {image_path}: {e}") return False def process_images_in_directory(directory): """ Process all images in a given directory and its subdirectories. """ total_files = 0 processed_files = 0 # 预先计算总文件数以显示进度 for root, dirs, files in os.walk(directory): for file in files: if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')): total_files += 1 for root, dirs, files in os.walk(directory): for file in files: if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')): original_path = os.path.join(root, file) filename, file_extension = os.path.splitext(file) output_path = os.path.join(root, f"{filename}(1){file_extension}") if not os.path.exists(output_path): # 避免覆盖已存在的文件 if flip_and_duplicate_image(original_path, output_path): processed_files += 1 # 打印处理进度 print(f"处理进度: {processed_files}/{total_files} ({(processed_files/total_files)*100:.2f}%)") def main(): directory = input("请输入要处理的文件夹的路径: ") if os.path.exists(directory) and os.path.isdir(directory): process_images_in_directory(directory) print("图片处理完成。") else: print("提供的路径无效或不是一个目录。") # 运行脚本 main()
标签:files,os,image,file,path,directory,镜像,lora,目录 From: https://www.cnblogs.com/zly324/p/17842604.html