2018年2月13日火曜日

JPG画像のexif形式対応

画像を処理する前に、iPhoneなどで撮影した画像はExifというデータを元に上下左右のオリエンテーションを直しておかないと、PILとかで処理するときに勝手にひっくり返ったりしてしまう。
学習中に間違ったデータを与えかねないので、一括で直しておく。

from PIL import Image
import os

img_path = 'img/'

def rota(i):
    image = Image.open(i)
    if hasattr(image, '_getexif'):
        orientation = 0x0112
        exif = image._getexif()
        if exif is not None:
            orientation = exif[orientation]
            rotations = {
                3: Image.ROTATE_180,
                6: Image.ROTATE_270,
                8: Image.ROTATE_90
            }
            if orientation in rotations:
                image = image.transpose(rotations[orientation])
    image.save(i)

for i in os.listdir(img_path):
    rota(img_path+i)

4万枚画像があるので結構時間がかかる