| import os |
| from pathlib import Path |
| from datetime import datetime |
| from PIL import Image |
|
|
|
|
| def process_images_from_dir(input_dir, output_base_dir=None): |
| """ |
| 从输入目录读取所有jpg和png图像,转换为RGB格式后保存到输出目录 |
| |
| Args: |
| input_dir: 输入图像目录路径 |
| output_base_dir: 输出基础目录,如果为None则使用输入目录的父目录 |
| """ |
| input_path = Path(input_dir) |
| if not input_path.exists(): |
| raise ValueError(f"输入目录不存在: {input_dir}") |
| |
| |
| if output_base_dir is None: |
| output_base_dir = input_path.parent |
| else: |
| output_base_dir = Path(output_base_dir) |
| |
| output_dir = output_base_dir / f"processed_jpg" |
| output_dir.mkdir(parents=True, exist_ok=True) |
| print(f"输出目录: {output_dir}") |
| |
| |
| image_extensions = {'.jpg', '.jpeg', '.png', '.JPG', '.JPEG', '.PNG'} |
| |
| |
| image_files = [] |
| for ext in image_extensions: |
| image_files.extend(input_path.glob(f"*{ext}")) |
| |
| if not image_files: |
| print(f"在 {input_dir} 中未找到图像文件") |
| return |
| |
| print(f"找到 {len(image_files)} 个图像文件") |
| |
| |
| save_kwargs = dict(format="JPEG", quality=96, subsampling=0, optimize=True) |
| |
| |
| success_count = 0 |
| for img_path in image_files: |
| try: |
| |
| img = Image.open(img_path) |
| |
| |
| if img.mode != "RGB": |
| img = img.convert("RGB") |
|
|
| img = img.resize((512, 512), resample=Image.LANCZOS) |
| |
| |
| output_filename = img_path.stem + ".jpg" |
| out_path = output_dir / output_filename |
| |
| |
| img.save(out_path, **save_kwargs) |
| success_count += 1 |
| print(f"已处理: {img_path.name} -> {output_filename}") |
| |
| except Exception as e: |
| print(f"处理 {img_path.name} 时出错: {str(e)}") |
| |
| print(f"\n处理完成!成功处理 {success_count}/{len(image_files)} 个文件") |
| print(f"输出目录: {output_dir}") |
|
|
|
|
| if __name__ == "__main__": |
| |
| input_directory = "./final_result/blended" |
| output_base_directory = "./" |
| |
| process_images_from_dir(input_directory, output_base_directory) |
|
|