用于批量裁剪指定文件夹中的JPEG图像。该脚本可以递归地遍历文件夹及其所有子文件夹,并将裁剪后的图像保存到指定的输出文件夹中,同时保留原有的文件结构。
功能特点
- 批量处理:支持批量处理指定文件夹中的所有JPEG图像。
- 递归遍历:能够递归地遍历文件夹及其所有子文件夹。
- 保留文件结构:输出文件夹中会保留与输入文件夹相同的文件结构。
- 日志记录:通过配置日志记录,方便跟踪处理过程和错误信息。
环境要求
Python 3.x
Pillow 库(用于图像处理)
安装依赖
在运行脚本之前,请确保安装了 Pillow 库。可以使用以下命令进行安装:
import os
import logging
from PIL import Image
# 配置日志
logging.basicConfig(level=logging.INFO)
#input下有二级文件夹,二级文件下有图像视频
input_folder = './input/'
output_folder = './output/' # 输出文件夹
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 遍历文件夹及其所有子文件夹
for root, dirs, files in os.walk(input_folder):
for file in files:
if file.lower().endswith('.jpg'): # 检查文件是否为JPEG格式
file_path = os.path.join(root, file)
logging.info(f'处理文件: {file_path}')
# 打开图像
try:
image = Image.open(file_path)
except Exception as e:
logging.warning(f'无法读取图像 {file_path}: {e}')
continue
# 裁剪图像
cropped = image.crop((200, 185, 1000, 850)) # 裁剪坐标
# 生成输出路径,保留原有文件结构
relative_path = os.path.relpath(root, input_folder)
output_dir = os.path.join(output_folder, relative_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
output_path = os.path.join(output_dir, file)
cropped.save(output_path)
logging.info(f'已保存裁剪图像: {output_path}')