python pillow resize, thumbnail 사용 시 이미지 rotate되는 문제 해결

yo·2021년 6월 8일
3

1. 문제 정의

  • python pillow라이브러리를 통해 thumbnail을 만들었는데,

    몇몇 결과 사진이 아래 예시처럼 rotate되는 현상이 발생함.

    (모든 사진이 그런건 아니고 특정 사진에서만 rotate됨)

2. 원인

  • 스택오버플로우 글에서 원인을 찾았다.

    When a picture is taller than it is wide, it means the camera was rotated. Some cameras can detect this and write that info in the picture's EXIF metadata. Some viewers take note of this metadata and display the image appropriately. PIL can read the picture's metadata

해석하자면,

  • 사진 찍을 때 세로 길이 > 가로 길이 일 경우,
    어떤 카메라들은 이를 감지하여 사진이 rotate됐다는 정보를 EXIF 메타데이터에 적어놓는다.
  • 이 정보를 PIL이 읽을 수 있고, 결국 resize할 때 이를 반영해서 사진을 뒤집어 놓는다는 뜻같다.
    (이 부분은 뇌피셜)

* 여기서 잠깐, EXIF에 대해 알고 넘어가자.

정의: exchangeable image file format

디지털 카메라의 이미지 파일 안에 저장되어 있는 파일 형식을 말합니다.
데이터와 함께 카메라 제조사(Marker), 카메라모델(Model), 에디터(Soft ware)
사진을 보정한 날짜(Date time), EXIF버전(EXIF Version), 촬영한 날짜(Shoot Date time)
,웹에 올려진 사진의 실제크기(Image Size), 노출시간(Exposure Time),
촬영프로그램(Exposure Program), 렌즈초점 길이(Focal Length), 조리개수치(F-Number)
셔터스피드(Shutter Speed), 플래시 사용여부 등 세부적인 부가 정보를 기록할 수 있수 있습니다
출처: 소니 사이트

맥북의 경우 사진 우클릭 -> '정보 가져오기'를 눌러 EXIF를 볼 수 있다.

출처: 제로스의 IT 매뉴얼

3. 해결 시도

1 Pillow의 ImageOps사용

  • 스택오버플로우의 여러 해결책 중 이 방법을 먼저 시도해보기로 했다. 이유는,
      1. 지금 쓰고있는 PIL 라이브러리를 사용하여 해결 가능
      1. 라이브러리 공식문서를 읽어보니 딱 필요로 하는 기능이다.
      1. 코드 줄이 압도적으로 간결
      1. 댓글을 보니 평이 좋음

아래는 ImageOps와 exif_transpose에 대한 대한 공식문서의 설명이다.

The ImageOps module contains a number of ‘ready-made’ image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images.

import io
from PIL import Image, ImageOps

original_image = Image.open(s3_response["Body"])
fixed_image = ImageOps.exif_transpose(original_image)
fixed_image.thumbnail(size, Image.LANCZOS)
bytes_io = io.BytesIO()
fixed_image.save("new_01.jpg", format=original_image.format, optimize=True, quality=90)

바로 아래 사진은 ImageOps.exif_transpose를 적용하지 않은, 원본 사진이 뒤집힌 썸네일이다.

이 아래 사진은 ImageOps.exif_transpose적용하여 원본 사진이 뒤집히지 않은 썸네일이다.

운좋게 첫 시도만에 해결책을 찾을 수 있었다.

profile
Never stop asking why

0개의 댓글