Python/OpenCV

[OpenCV] Image Cropping

언킴 2023. 7. 6. 09:22
반응형

데이터 증강(Data Augmentation)을 위해 이미지를 자를 수도 있고, 특정 영역에 대한 바운딩 박스(Bounding Box)를 가지고 오기 위해 이미지를 자를 수 있다. 이때 가장 간단한 방법은 Height과 Width를 지정해서 해당 범위에 대한 영역만 잘라오는 것이다.

def cropping(img, x, y, h=16, w=16):
    H, W, C = img.shape
    w_start = np.min([x, 0])
    w_end = np.min([x+w, W])
    
    h_start = np.min([y, 0])
    h_end = np.min([y+h, H])
    
    cropped_img = img[h_start:h_end, w_start:w_end].copy()
    return cropped_img

def load_image(path):
    img = cv2.imread(path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB).astype('uint8')
    return img 

def plot_imshow(img1, img2):
    fig, axes = plt.subplots(figsize=(6, 9), ncols=2, nrows=1)
    axes[0].imshow(img1)
    axes[1].imshow(img2)
    plt.show()

query = load_image(query_path)
cropped_query = cropping(query)


plot_imshow(query, cropped_query)

x와 y는 원본 이미지의 시작 지점을 나타낸다. 시작 지점에서 높이를 얼마만큼, 넓이를 얼마만큼 지정하냐에 따라 절단되는 이미지의 크기를 조정할 수 있다. 넘파이에서 인덱스가 원래의 길이보다 긴 경우에 최대 길이만큼 슬라이싱 해주기 때문에 굳이 np.min 과같은 함수를 사용하지 않더라도, 매우 간단하게 아래와 같은 코드로도 이미지를 자를 수 있다. 

def cropping(img, x, y, h, w):
    return img[y:y+h, x:x+w].copy()

'Python > OpenCV' 카테고리의 다른 글

[OpenCV] Image Registration Processing  (0) 2023.07.05