Computer Vision 관련하여다양한 크기의 이미지 자료를 학습 및 검증을 수행하던 도중 image의 ratio에 따라 예측 성능이 변화 되는 것을 느꼈다. 이에 따라서 image를 Crop하는 것도 방법과 Ratio를 유지한 채 Padding을 주는 것도 방법 일 것 같았다. 그래서 Ratio를 유지한 채로 Padding을 주는 방법을 구현하여 보았다.

물론 해당 내용은 검색을 잠깐 해보아도 잘 나오긴 하나 크기와 비율에 무관하게 만들고 싶어 구현을 한번 해보았다.

Add padding to images to get them into the same shape
l have a set of images of different sizes (45,50,3), (69,34,3), (34,98,3). l want to add padding to these images as follows: Take the max width and length of the whole images then put the image in...
Resize image with padding using CV2
Resize image with padding using CV2. GitHub Gist: instantly share code, notes, and snippets.

아래는 구현한 코드이다. 기본적으로 원하는 이미지의 크기를 H, W, C라고하고, 가지고 있는 이미지의 크기를 f_H, f_W, f_C라할 때 내 이미지의 비율은 유지하고 싶기 때문에 H/W = f_H/f_W일 것이다. 이미지는 W가 H보다 크다 가정하자.

그러면 W를 기준으로 줄이게 되면 새로이 계산될 new_H는 H보다 적게 나타날 것이다.  new_H는 양 변에 W를 곱해주면 new_H=f_H/f_W*W로 나타날 것이다.

def ratio_padding(frame,H,W):
    out=np.zeros((H,W,3))
    f_H=frame.shape[0];f_W=frame.shape[1]
    f_r=f_H/f_W

    if f_r<1:
        new_H=int(f_r*W)
        frame=cv2.resize(frame,(W,new_H))
        st=(H-new_H)//2
        out[st:new_H+st,:,:]=frame
    else:
        new_W=int(H/f_r)
        frame=cv2.resize(frame,(new_W, H))
        st=(W-new_W)//2
        out[:,st:new_W+st,:]=frame
    return out.astype('u1')