Data Mavericks

CV(Deep learning) (2) - Selective Search 실습 본문

Computer Vision/Deep Learning

CV(Deep learning) (2) - Selective Search 실습

권동동 2023. 7. 5. 16:19

Selective Search 실습 및 시각화

실습환경

운영 체제 : Ubuntu 20.04 ( Linux )
실습 환경 : COLAB
NVIDIA GPU Driver Version: 530.41.03
CUDA Version: 12.1

Selective Search를 이용하여 Object Detection을 위한 Region Proposal 영역을 도출

'selectivesearch' 패키지 설치

!pip install selectivesearch

 

디렉토리 생성

!mkdir /content/data

 

이미지 다운로드

!wget -O /content/data/audrey01.jpg https://raw.githubusercontent.com/chulminkw/DLCV/master/data/image/audrey01.jpg

 

matplotlib를 사용하여 이미지를 시각화

import selectivesearch
import cv2
import matplotlib.pyplot as plt
import os
%matplotlib inline

### 오드리헵번 이미지를 cv2로 로드하고 matplotlib으로 시각화
img = cv2.imread('./data/audrey01.jpg')
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
print('img shape:', img.shape)

plt.figure(figsize=(8, 8))
plt.imshow(img_rgb)
plt.show()

 

이미지에 대한 Selective Search를 수행하여 Region Proposal 정보를 반환

import selectivesearch

#selectivesearch.selective_search()는 이미지의 Region Proposal정보를 반환
_, regions = selectivesearch.selective_search(img_rgb, scale=100, min_size=3000)

print(type(regions), len(regions))

selectivesearch.selective_search() 함수는 이미지와 함께 사용자가 설정한 scale과 min_size 값을 인자로 받아 Selective Search를 수행하고, 반환되는 결과 중에서 Region Proposal 정보를 regions 변수에 저장

type(regions)와 len(regions)를 출력하여 regions 변수의 타입과 개수를 확인

 

regions의 출력해보면

첫번째의 regions를 예시로 들자면 0,0은 좌표 107은 width 207은 height를 나태냄


Bounding Box를 시각화 하기

# opencv의 rectangle()을 이용하여 시각화
# rectangle()은 이미지와 좌상단 좌표, 우하단 좌표, box컬러색, 두께등을 인자로 입력하면 원본 이미지에 box를 그려줌.

green_rgb = (125, 255, 51)
img_rgb_copy = img_rgb.copy()
for rect in cand_rects:

    left = rect[0]
    top = rect[1]
    # rect[2], rect[3]은 너비와 높이이므로 우하단 좌표를 구하기 위해 좌상단 좌표에 각각을 더함.
    right = left + rect[2]
    bottom = top + rect[3]

    img_rgb_copy = cv2.rectangle(img_rgb_copy, (left, top), (right, bottom), color=green_rgb, thickness=2)

plt.figure(figsize=(8, 8))
plt.imshow(img_rgb_copy)
plt.show()

 

Bounding Box의 큰 후보만 추출

cand_rects = [cand['rect'] for cand in regions if cand['size'] > 10000]

green_rgb = (125, 255, 51)
img_rgb_copy = img_rgb.copy()
for rect in cand_rects:

    left = rect[0]
    top = rect[1]
    # rect[2], rect[3]은 너비와 높이이므로 우하단 좌표를 구하기 위해 좌상단 좌표에 각각을 더함.
    right = left + rect[2]
    bottom = top + rect[3]

    img_rgb_copy = cv2.rectangle(img_rgb_copy, (left, top), (right, bottom), color=green_rgb, thickness=2)

plt.figure(figsize=(8, 8))
plt.imshow(img_rgb_copy)
plt.show()


📢  이 글은 권철민님의 [개정판] 딥러닝 컴퓨터 비전 완벽 가이드 - 인프런 강의를 바탕으로 정리한 내용입니다.

 

📢  해당 글은 교육적인 목적으로 작성되었으며 영리 목적이 없음을 밝힙니다. 법률적인 문제가 있을 경우 메일을 보내주시면 수정하도록 하겠습니다.

 

📢 이메일 : do5431@naver.com