同一张图像在本地显示是正确的但是上传到网页或其他系统打开是旋转后的图像
原图如下:
在网页端或其他机器打开的图像如下:
出现以上现象的原因:
某些相机生成的图像编码中会自带旋转信息,所以会出现以上现象
解决方案如下:
from glob import glob
import PIL
from PIL import Image
from PIL import ExifTags
from PIL import ImageOps
def apply_exif_orientation(image):
try:
exif = image._getexif()
except AttributeError:
exif = None
if exif is None:
return image
exif = {PIL.ExifTags.TAGS[k]: v for k, v in exif.items() if k in PIL.ExifTags.TAGS}
orientation = exif.get('Orientation', None)
print(orientation)
if orientation == 1:
# do nothing
return image
elif orientation == 2:
# left-to-right mirror
return PIL.ImageOps.mirror(image)
elif orientation == 3:
# rotate 180
return image.transpose(PIL.Image.ROTATE_180)
elif orientation == 4:
# top-to-bottom mirror
return PIL.ImageOps.flip(image)
elif orientation == 5:
# top-to-left mirror
return PIL.ImageOps.mirror(image.transpose(PIL.Image.ROTATE_270))
elif orientation == 6:
return image.transpose(PIL.Image.ROTATE_270)
elif orientation == 7:
return PIL.ImageOps.mirror(image.transpose(PIL.Image.ROTATE_90))
elif orientation == 8:
return image.transpose(PIL.Image.ROTATE_90)
else:
return image
if __name__=="__main__":
floder="D:/DataSet/wuzuo/v1.0/Detection_AIBEE_beijing_office_20200610_productairport/*.jpg"
dst_path="D:/DataSet/wuzuo/v1.0/result/"
for i in glob(floder):
jpg_name=i.split("\\")[-1]
image = Image.open(i)
img=apply_exif_orientation(image)
img.save(dst_path+jpg_name)
参考文章