网络编程
位置:首页>> 网络编程>> Python编程>> Python PIL读取的图像发生自动旋转的实现方法

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

作者:mzp_1990  发布时间:2022-05-01 20:29:26 

标签:Python,PIL,自动旋转

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

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

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


from PIL import Image, ExifTags
img = 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

来源:https://blog.csdn.net/mizhenpeng/article/details/82794112

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com