Rego의 블로그

Backward Mapping 본문

영상처리

Backward Mapping

RegularPark 2021. 9. 29. 16:22

forward mapping을 하면 input_image를 rotate하는 과정에서 좌표를 int 처리하는 동안 이미지의 특정 픽셀들이 누락되는 현상이 생긴다.

 

곳곳에 보이는 구멍들

 

이를 해결하기 위해 backward mapping을 하는데, 이는 옮기고자 하는 input_image의 좌표를, 역으로(backward) output_image의 좌표에서 얻어와 input_image의 자리에 넣는 형태이다.

import cv2
import numpy as np

def rotation(img, angle):
    height, width = img.shape
    result = np.zeros((height, width), dtype = np.uint8)    # 모든 원소가 0인 height * width 행렬
    
    angle = np.radians(angle)

    rotation_matrix = np.array([
        [np.cos(angle), -np.sin(angle), 0],
        [np.sin(angle), np.cos(angle), 0],
        [0, 0, 1]
    ])
    
    for x in range(width):
        for y in range(height):
            (x_a, y_a, _) = rotation_matrix.dot(np.array([x, y, 1]))
            
            x_a = int(x_a)
            y_a = int(y_a)  # 할당한 value 값이 정수 값이라 공백이 생김

            if 0 <= x_a < width and 0 <= y_a < height:
                result[x, y] = img[x_a, y_a]   # 이 코드의 좌표들이 포인트.     
                # backward mapping이므로 forward mapping과 반대로 기존의 이미지에서 좌표를 거꾸로 가져옴.
             
    return result
      
if __name__ == '__main__':
    img = cv2.imread('2.jpg', flags= 0)

    rotation_img = rotation(img, 20)

    cv2.imshow('Input image', img)
    cv2.imshow('Rotation image', rotation_img)
    cv2.waitKey()

 

output_image

깔끔하게 rotation이 되었다.