Temp

[Pillow] 이미지를 읽었더니 회전될 때

ju_young 2021. 12. 13. 11:23
728x90

EXIF orientation values

The 8 EXIF orientation values are numbered 1 to 8.

  1. 1 = 0 degrees: the correct orientation, no adjustment is required.
  2. 2 = 0 degrees, mirrored: image has been flipped back-to-front.
  3. 3 = 180 degrees: image is upside down.
  4. 4 = 180 degrees, mirrored: image has been flipped back-to-front and is upside down.
  5. 5 = 90 degrees: image has been flipped back-to-front and is on its side.
  6. 6 = 90 degrees, mirrored: image is on its side.
  7. 7 = 270 degrees: image has been flipped back-to-front and is on its far side.
  8. 8 = 270 degrees, mirrored: image is on its far side.

https://sirv.com/help/articles/rotate-photos-to-be-upright/

Code

import cv2
from PIL import Image
from PIL.ExifTags import TAGS
import numpy as np

image = Image.open(img_path)
img = np.array(image)

# -- exifdata에 있는 orientation 정보 get
exifdata = image.getexif()
orientation = 0
for tag_id in exifdata:
	tag = TAGS.get(tag_id, tag_id)
    data = exifdata.get(tag_id)
    if isinstance(data, bytes):
    	try:
        	data = data.decode()
        except:
        	data = data.decode('iso8859-1') # utf8으로 안되면 iso8849-1로 변경하여 decoding
    # orientation 정보 저장
    if tag == 'Orientation':
    	orientation = data
    
# -- orientation 정보에 따라 이미지 조작
if orientation == 2:
    img = cv2.flip(img, 1)
elif orientation == 3:
    img = cv2.flip(img, 0)
    img = cv2.flip(img, 1)
elif orientation == 4:
    img = cv2.flip(img, 0)
elif orientation == 5:
    img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
    img = cv2.flip(img, 1)
elif orientation == 6:
    img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
elif orientation == 7:
    img = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)
    img = cv2.flip(img, 1)

pillow의 Image.open으로 이미지를 read해야만 exifdata를 읽어올 수 있다. cv2로 read하면 exifdata를 얻을 수 없다. 그리고 이미지를 조작하기위해서는 이미지는 numpy.array로 변환하여 cv2로 flip 또는 rotate한다.

728x90