Processed with PIL considering EXIF Orientation tag

When a JPEG file is opened with PIL (Pillow), even if a value is set in the Orientation tag of EXIF, it is not taken into consideration. Implementation example of how to generate data after performing rotation / flip processing according to the value set in the Orientation tag.

from PIL import Image

file_path = "JPEG image file path"

#Processing according to the Orientation tag value
#The angle of Rotate in PIL is positive counterclockwise
convert_image = {
    1: lambda img: img,
    2: lambda img: img.transpose(Image.FLIP_LEFT_RIGHT),                              #Flip horizontal
    3: lambda img: img.transpose(Image.ROTATE_180),                                   #180 degree rotation
    4: lambda img: img.transpose(Image.FLIP_TOP_BOTTOM),                              #flip upside down
    5: lambda img: img.transpose(Image.FLIP_LEFT_RIGHT).transpose(Pillow.ROTATE_90),  #Left-right reversal & counterclockwise rotation 90 degrees
    6: lambda img: img.transpose(Image.ROTATE_270),                                   #Rotate 270 degrees counterclockwise
    7: lambda img: img.transpose(Image.FLIP_LEFT_RIGHT).transpose(Pillow.ROTATE_270), #Left-right reversal & counterclockwise rotation 270 degrees
    8: lambda img: img.transpose(Image.ROTATE_90),                                    #Rotate 90 degrees counterclockwise
}

img = Image.open(file_path)
exif = img._getexif()
orientation = exif.get(0x112, 1)

new_img = convert_image[orientation](img)

Click here for the definition of the EXIF standard. http://www.cipa.jp/std/documents/j/DC-008-2012_J.pdf

However, the definition of the value of the Orientation tag of EXIF is hard to understand just by looking at the explanation. There are various pages that explain in an easy-to-understand manner by searching. For example, here. http://hackmylife.net/archives/7400448.html

Recommended Posts

Processed with PIL considering EXIF Orientation tag
PIL installation with pip
Extract EXIF with sips
Image Processing with PIL