-
-
Save ageitgey/842500419feef08294cd228ace471181 to your computer and use it in GitHub Desktop.
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
import PIL.Image | |
import PIL.ImageOps | |
import numpy as np | |
def exif_transpose(img): | |
if not img: | |
return img | |
exif_orientation_tag = 274 | |
# Check for EXIF data (only present on some files) | |
if hasattr(img, "_getexif") and isinstance(img._getexif(), dict) and exif_orientation_tag in img._getexif(): | |
exif_data = img._getexif() | |
orientation = exif_data[exif_orientation_tag] | |
# Handle EXIF Orientation | |
if orientation == 1: | |
# Normal image - nothing to do! | |
pass | |
elif orientation == 2: | |
# Mirrored left to right | |
img = img.transpose(PIL.Image.FLIP_LEFT_RIGHT) | |
elif orientation == 3: | |
# Rotated 180 degrees | |
img = img.rotate(180) | |
elif orientation == 4: | |
# Mirrored top to bottom | |
img = img.rotate(180).transpose(PIL.Image.FLIP_LEFT_RIGHT) | |
elif orientation == 5: | |
# Mirrored along top-left diagonal | |
img = img.rotate(-90, expand=True).transpose(PIL.Image.FLIP_LEFT_RIGHT) | |
elif orientation == 6: | |
# Rotated 90 degrees | |
img = img.rotate(-90, expand=True) | |
elif orientation == 7: | |
# Mirrored along top-right diagonal | |
img = img.rotate(90, expand=True).transpose(PIL.Image.FLIP_LEFT_RIGHT) | |
elif orientation == 8: | |
# Rotated 270 degrees | |
img = img.rotate(90, expand=True) | |
return img | |
def load_image_file(file, mode='RGB'): | |
# Load the image with PIL | |
img = PIL.Image.open(file) | |
if hasattr(PIL.ImageOps, 'exif_transpose'): | |
# Very recent versions of PIL can do exit transpose internally | |
img = PIL.ImageOps.exif_transpose(img) | |
else: | |
# Otherwise, do the exif transpose ourselves | |
img = exif_transpose(img) | |
img = img.convert(mode) | |
return np.array(img) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment