使用PIL转换图片为灰度图时图片自动旋转,如何禁用该功能?
解决PIL转换灰度图时自动旋转图片的问题
问题出在图片的EXIF方向元数据上——很多手机或相机拍摄的照片会在EXIF里记录Orientation(方向)标签,PIL的Image.open默认会自动根据这个标签旋转图片以保证显示正确,但这会导致保存后的图片和原始像素布局不一致,看起来像是“自动旋转”了。
下面分两种场景给出解决方案:
场景1:使用PIL 9.1.0及以上版本
这个版本的PIL新增了autorient参数,直接设置为False就能禁用自动旋转:
修改你代码里的图片打开逻辑:
img = Image.open(f'spanish_pages_photos/{i}', autorient=False).convert('L')
这样打开的图片会完全保留原始像素的布局,忽略EXIF的方向信息,转换灰度图后保存就不会出现自动旋转的情况。
场景2:使用低于9.1.0的PIL版本
需要手动读取EXIF的Orientation标签,把PIL自动旋转的操作反转回去:
替换你的循环逻辑为以下代码(顺便修正了变量名,避免覆盖内置的list类型):
from PIL import Image, ImageOps import os path = 'spanish_pages_photos/' pathContents = os.listdir(path) file_list = sorted(pathContents) for filename in file_list[2:]: img_path = os.path.join(path, filename) img = Image.open(img_path) # 获取图片的EXIF元数据 exif = img.getexif() # 读取Orientation标签(标签码为0x0112) orientation = exif.get(0x0112) # 反转PIL自动应用的旋转操作 if orientation == 2: img = ImageOps.mirror(img) elif orientation == 3: img = img.rotate(180, expand=True) elif orientation == 4: img = ImageOps.mirror(img.rotate(180, expand=True)) elif orientation == 5: img = ImageOps.mirror(img.rotate(270, expand=True)) elif orientation == 6: img = img.rotate(270, expand=True) elif orientation == 7: img = ImageOps.mirror(img.rotate(90, expand=True)) elif orientation == 8: img = img.rotate(90, expand=True) # 转换为灰度图并保存(可选保留原始EXIF) img_gray = img.convert('L') img_gray.save(img_path, exif=exif) print('finished')
内容的提问来源于stack exchange,提问作者bananatoast
相关产品推荐
相关产品推荐

