반응형

Image Rotate

이미지를 특정 각도로 회전하는 방법에 대해 알아보겠습니다.  이미지를 회전할 때에는 회전할 지점을 지정해야 합니다. 대부분의 경우는 이미지의 중심을 기준으로 회전을 하지만 임의의 지점을 지정할 수도 있습니다.


Import packages

import cv2
import numpy as np
import imutils
import matplotlib.pyplot as plt

Jupyter Notebook 및 Google Colab에서 이미지를 표시할 수 있도록 Function으로 정의

def img_show(title='image', img=None, figsize=(8 ,5)):
    plt.figure(figsize=figsize)

    if type(img) == list:
        if type(title) == list:
            titles = title
        else:
            titles = []

            for i in range(len(img)):
                titles.append(title)

        for i in range(len(img)):
            if len(img[i].shape) <= 2:
                rgbImg = cv2.cvtColor(img[i], cv2.COLOR_GRAY2RGB)
            else:
                rgbImg = cv2.cvtColor(img[i], cv2.COLOR_BGR2RGB)

            plt.subplot(1, len(img), i + 1), plt.imshow(rgbImg)
            plt.title(titles[i])
            plt.xticks([]), plt.yticks([])

        plt.show()
    else:
        if len(img.shape) < 3:
            rgbImg = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
        else:
            rgbImg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        plt.imshow(rgbImg)
        plt.title(title)
        plt.xticks([]), plt.yticks([])
        plt.show()

Load Image

cv2_image = cv2.imread('asset/images/test_image.jpg', cv2.IMREAD_COLOR)

Rotate

이미지의 크기를 잡고 이미지의 중심을 계산합니다. 이 중심을 기준으로 이미지를 45도 회전 하거나 -90도 회전하는 예시입니다.

# 이미지의 크기를 잡고 이미지의 중심을 계산합니다.
(h, w) = cv2_image.shape[:2]
(cX, cY) = (w // 2, h // 2)

# 이미지의 중심을 중심으로 이미지를 45도 회전합니다.
M = cv2.getRotationMatrix2D((cX, cY), 45, 1.0)
rotated_45 = cv2.warpAffine(cv2_image, M, (w, h))

# 이미지를 중심으로 -90도 회전
M = cv2.getRotationMatrix2D((cX, cY), -90, 1.0)
rotated_90 = cv2.warpAffine(cv2_image, M, (w, h))

img_show(["Rotated by 45 Degrees", "Rotated by -90 Degrees"], [rotated_45, rotated_90])

이미지를 이동 할 때 행렬을 정의했던 것처럼 이미지를 회전 시에도 행렬을 정의하여 이용 할 수 있습니다.  NumPy를 사용하여 수동으로 행렬을 구성하는 대신 cv2.getRotationMatrix2D메서드를 사용합니다.

첫번째 인수는 이미지를 회전하는 지점입니다. (이 경우 이미지의 중심 cX과 위치 cY) 두번째 인수는 각도 입니다. 세번째 인수는 이미지 크기입니다. (예를들어 1.0 이면 원본사이즈, 2.0 이면 이미지 크기가 두배가 됩니다.)

M = cv2.getRotationMatrix2D((10, 10), 45, 1.0)
rotated = cv2.warpAffine(cv2_image, M, (w, h))
img_show("Rotated by Arbitrary Point", rotated)

Rotate images using imutils

imutils 함수를 사용하여 이미지를 180도 회전합니다. 

rotated = imutils.rotate(cv2_image, 180)
img_show("Rotated by 180 Degrees", rotated)

imutils.rotate_bound을 사용하면 회전 시 이미지 전체가 그안에 맞 도록 이미지 배열을 자동으로 확장합니다.

rotated = imutils.rotate_bound(cv2_image, -33)
img_show("Rotated Without Cropping", rotated)

 

반응형