Created
December 14, 2023 01:55
-
-
Save NormXU/5faf24cd5483c21c3acec499dd5c1538 to your computer and use it in GitHub Desktop.
Correct the image orientation mismatch between viewing and loading with PIL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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