관리 메뉴

중요한건 꺾이지 않는 맥북

python pil image rotation 문제 본문

COMPUTER VISION

python pil image rotation 문제

개발허재 2022. 5. 25. 15:23

Pillow 라이브러리로 이미지를 읽어올때 이미지가 회전되는 경우가 있다.

 

from PIL import Image, ImageOps
image_path = ''
image = Image.open(image_path)
image = ImageOps.exif_transpose(image)

pillow 라이브러리로 이미지를 읽은 뒤, ImageOps의 exif_transpose 내장 모듈로 다시 변환시켜주면 된다.

 

exif_transpose 의 소스코드를 보면,

def exif_transpose(image):
    """
    If an image has an EXIF Orientation tag, return a new image that is
    transposed accordingly. Otherwise, return a copy of the image.

    :param image: The image to transpose.
    :return: An image.
    """
    exif = image.getexif()
    orientation = exif.get(0x0112)
    method = {
        2: Image.Transpose.FLIP_LEFT_RIGHT,
        3: Image.Transpose.ROTATE_180,
        4: Image.Transpose.FLIP_TOP_BOTTOM,
        5: Image.Transpose.TRANSPOSE,
        6: Image.Transpose.ROTATE_270,
        7: Image.Transpose.TRANSVERSE,
        8: Image.Transpose.ROTATE_90,
    }.get(orientation)
    if method is not None:
        transposed_image = image.transpose(method)
        transposed_exif = transposed_image.getexif()
        if 0x0112 in transposed_exif:
            del transposed_exif[0x0112]
            if "exif" in transposed_image.info:
                transposed_image.info["exif"] = transposed_exif.tobytes()
            elif "Raw profile type exif" in transposed_image.info:
                transposed_image.info[
                    "Raw profile type exif"
                ] = transposed_exif.tobytes().hex()
            elif "XML:com.adobe.xmp" in transposed_image.info:
                transposed_image.info["XML:com.adobe.xmp"] = re.sub(
                    r'tiff:Orientation="([0-9])"',
                    "",
                    transposed_image.info["XML:com.adobe.xmp"],
                )
        return transposed_image
    return image.copy()

이미지에 EXIF 태그가 있으면, transpose 시켜준다는 의미로 해석된다.

'COMPUTER VISION' 카테고리의 다른 글

VIT(Vision Transformer)  (0) 2022.03.23