Help us understand the problem. What is going on with this article?

PILでEXIF Orientationタグを考慮して処理

More than 5 years have passed since last update.

PIL(Pillow) で JPEG ファイルをオープンしたとき、EXIF の Orientation タグに値が設定されていても特に考慮されない。
Orientation タグに設定されている値に従った回転・フリップ処理を行った後のデータを生成する方法の実装例。

from PIL import Image

file_path = "JPEG 画像ファイルのパス"

# Orientation タグ値にしたがった処理
# PIL における Rotate の角度は反時計回りが正
convert_image = {
    1: lambda img: img,
    2: lambda img: img.transpose(Image.FLIP_LEFT_RIGHT),                              # 左右反転
    3: lambda img: img.transpose(Image.ROTATE_180),                                   # 180度回転
    4: lambda img: img.transpose(Image.FLIP_TOP_BOTTOM),                              # 上下反転
    5: lambda img: img.transpose(Image.FLIP_LEFT_RIGHT).transpose(Pillow.ROTATE_90),  # 左右反転&反時計回りに90度回転
    6: lambda img: img.transpose(Image.ROTATE_270),                                   # 反時計回りに270度回転
    7: lambda img: img.transpose(Image.FLIP_LEFT_RIGHT).transpose(Pillow.ROTATE_270), # 左右反転&反時計回りに270度回転
    8: lambda img: img.transpose(Image.ROTATE_90),                                    # 反時計回りに90度回転
}

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

new_img = convert_image[orientation](img)

EXIF 規格の定義はこちら。
http://www.cipa.jp/std/documents/j/DC-008-2012_J.pdf

ただ EXIF の Orientation タグの値の定義は、その説明だけ見てもパッと分かりづらい。検索すれば分かりやすく解説してくれているページがいろいろある。例えばこちらなど。
http://hackmylife.net/archives/7400448.html

Klein
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした