퐈니썬's LIfe - 잘 실패하자 RSS 태그 관리 글쓰기 방명록
구현 (1)
2022-01-20 00:05:31
728x90
반응형

<Introduction>

입력 이미지를 특정 사이즈에 맞게 Scale 하는 과정을 python으로 직접 구현하고자 합니다. 

opencv 라이브러리를 통해 간단하게 진행이 가능하지만, 전반적인 이미지 처리에 대한 이해를 다지고자 작성하였습니다. 

 

<Scale(Scaling)>

이미지 스케일링(Scaling)은 입력 이미지를 특정 사이즈에 맞게 줄였다가, 늘렸다가 하여 이미지를 구성하는 이미지 처리방법입니다. 즉, 이미지를 확대, 축소하는 과정입니다. 

 

그렇다면, 입력 이미지 대비 출력 이미지(특정 사이즈)의 비율이 중요하게 되고 그 비율만큼 입력 이미지는 확대 및 축소를 하게 될 것입니다. 

 

잠깐 상상을 해봅시다. 입력 이미지가 100x100의 사이즈를 가지고 해당 이미지를 200x200으로 만들고자 합니다. 즉 확대한 이미지를 만들고자 합니다.

 

이때, 픽셀의 갯수는 4배가 증가할 것입니다. 그러면 1개인 픽셀이 4개가 되는데 그 나머지 3개의 픽셀은 어떻게 할 것인가?

 

opencv에서는 다양한 보간법 제공하여 처리합니다. 구현에서는 인접한 픽셀을 그대로 취하도록 하였습니다. 

 

앞서 예시에서 3개의 픽셀은 1개의 픽셀과 동일한 값을 가지고 옵니다. 

출처 https://www.geeksforgeeks.org/image-processing-without-opencv-python/

 

 

<구현>

import cv2
import numpy as np
from math import floor

#Load image
img = cv2.imread('./../Image01.png')
print(img.shape, img.dtype)
height = img.shape[0]
width = img.shape[1]

#Scale
target_size = (300, 300)  # target size
output = np.zeros((target_size[0], target_size[1], 3), np.uint8)

x_scale = height/output.shape[0]   #input image / output image
y_scale = width/output.shape[1]   #input image / output image

for y in range(output.shape[1]):
    for x in range(output.shape[0]):
        # the pixel at coordinate (x, y) in the new image is equal to the pixel that is located at coordinate (floor(x * x_ratio), floor(y * y_ratio)).
        # floor는 인접한 픽셀을 가져오기 위해서 사용
        xp, yp = floor(x* x_scale), floor(y * y_scale)
        print(xp, yp)
        print(x, y)
        output[x,y] = img[xp,yp]
cv2.imwrite('./scale.png', output)

 

 

<opencv>

# cv2.reize()로 이미지 확대 및 축소 (scale_resize.py)

import cv2
import numpy as np

img = cv2.imread('../Image01.png')
height, width = img.shape[:2]

target_size = (300,300)
scale_img = cv2.resize(img, (target_size[0], target_size[1]), \
                         interpolation=cv2.INTER_AREA)

cv2.imwrite('./scale_cv.png', scale_img)

resize 함수를 통하여 간단하게 구현이 가능하며, 보간법은 영상 축소 시 효과적인 INTER_AREA(Nearest Neigbour 계열)을 사용하였습니다. 

 

 

 

728x90
반응형