如何利用Pillow将左右朝向图像转为垂直方向?
用Pillow校正图像朝向至垂直方向
问题说明
手里的图像只有两种异常朝向:
- 右向:相对于垂直方向顺时针转了90度
- 左向:相对于垂直方向顺时针转了270度(也就是逆时针90度)
要把这些图像统一转成垂直方向,之前试了Pillow没成功,需要先识别图像是哪种朝向,再对应旋转:右向图顺时针转270度,左向图顺时针转90度,最终所有图像都垂直对齐。
实现代码
下面是可直接运行的Pillow处理代码,优先用图像的EXIF旋转信息判断,没有EXIF的话用OCR识别文字方向辅助判断:
from PIL import Image import os def fix_image_orientation(input_path, output_path): with Image.open(input_path) as img: # 先读取EXIF里的旋转标记,大部分拍摄的图都会有这个信息 exif_data = img.getexif() orientation = exif_data.get(0x0112) corrected_img = img if orientation == 6: # EXIF标记6对应顺时针90度(右向),转270度校正 corrected_img = img.rotate(270, expand=True) elif orientation == 8: # EXIF标记8对应逆时针90度(左向),转90度校正 corrected_img = img.rotate(90, expand=True) else: # 没有EXIF信息,先看宽高比,横向图才需要处理 width, height = img.size if width > height: # 尝试用OCR识别文字方向,判断旋转角度 try: import pytesseract from pytesseract import Output osd_info = pytesseract.image_to_osd(img, output_type=Output.DICT) rotate_angle = osd_info['rotate'] if rotate_angle == 90: corrected_img = img.rotate(270, expand=True) elif rotate_angle == 270: corrected_img = img.rotate(90, expand=True) except ImportError: # 没装pytesseract的话,默认按右向处理(可根据自己的图调整) print("未安装pytesseract,默认按右向图像处理") corrected_img = img.rotate(270, expand=True) # 保存校正后的图 corrected_img.save(output_path) # 单张图处理示例 fix_image_orientation("你的输入图.jpg", "校正后的图.jpg") # 批量处理文件夹示例 input_dir = "待处理图片文件夹" output_dir = "处理完成文件夹" os.makedirs(output_dir, exist_ok=True) for file_name in os.listdir(input_dir): if file_name.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp')): in_path = os.path.join(input_dir, file_name) out_path = os.path.join(output_dir, file_name) fix_image_orientation(in_path, out_path) print(f"已处理:{file_name}")
代码说明
- EXIF优先处理:手机、相机拍的图一般会自带EXIF旋转信息,代码先读这个标记,直接对应旋转,准确率最高。
- 无EXIF时的 fallback:如果图像没有EXIF信息,先判断是否为横向图(宽>高),再用OCR识别文字的旋转角度,确定是右向还是左向。如果没装OCR工具,会默认按右向处理,你可以根据自己的图像情况修改默认逻辑。
- 批量处理:代码支持单张和批量处理整个文件夹的图像,自动保存到指定目录。
依赖安装
需要先装Pillow和pytesseract:
pip install pillow pytesseract
另外pytesseract需要搭配Tesseract OCR引擎使用,根据你的操作系统到官方渠道下载安装即可。
内容的提问来源于stack exchange,提问作者Raghav Kavimandan
相关产品推荐
相关产品推荐

