Skip to content

Instantly share code, notes, and snippets.

@NormXU
Created December 14, 2023 01:55
Show Gist options
  • Save NormXU/5faf24cd5483c21c3acec499dd5c1538 to your computer and use it in GitHub Desktop.
Save NormXU/5faf24cd5483c21c3acec499dd5c1538 to your computer and use it in GitHub Desktop.
Correct the image orientation mismatch between viewing and loading with PIL
def correct_orientation(image):
try:
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
break
exif = dict(image._getexif().items())
if exif[orientation] == 3:
image = image.rotate(180, expand=True)
elif exif[orientation] == 6:
image = image.rotate(270, expand=True)
elif exif[orientation] == 8:
image = image.rotate(90, expand=True)
return image
except Exception as e:
# cases: image don't have getexif
print("correct_orientation exception ={}".format(e))
return image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment