首页 > 编程 > Python > 正文

Python PIL读取的图像发生自动旋转的实现方法

2019-11-25 12:30:28
字体:
来源:转载
供稿:网友

对于手机、相机等设备拍摄的照片,由于手持方向的不同,拍出来的照片可能是旋转0°、90°、180°和270°。即使在电脑上利用软件将其转正,他们的exif信息中还是会保留方位信息。

在用PIL读取这些图像时,读取的是原始数据,也就是说,即使电脑屏幕上显示是正常的照片,用PIL读进来后,也可能是旋转的图像,并且图片的size也可能与屏幕上的不一样。

对于这种情况,可以利用PIL读取exif中的orientation信息,然后根据这个信息将图片转正后,再进行后续操作,具体如下。

from PIL import Image, ExifTagsimg = Image.open(file)try:  for orientation in ExifTags.TAGS.keys() :     if ExifTags.TAGS[orientation]=='Orientation' : break   exif=dict(img._getexif().items())  if  exif[orientation] == 3 :     img=img.rotate(180, expand = True)  elif exif[orientation] == 6 :     img=img.rotate(270, expand = True)  elif exif[orientation] == 8 :     img=img.rotate(90, expand = True)except:  pass

顺便提一句,这里rotate中的“expand = True”是将图片尺寸也进行相应的变换。如果不加这句,则size不变。

详情参见:https://stackoverflow.com/questions/4228530/pil-thumbnail-is-rotating-my-image

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表