-
MMDetection | Faster RCNNDeep Learning/vision 2021. 8. 15. 06:51728x90
MMDetection
https://github.com/chulminkw/DLCV_New/blob/main/faster_rcnn/mm_faster_rcnn_inference.ipynb
위 github 코드를 기반으로 작성함.
MMDetection은 pytorch 기반의 Object Detection / Segmentation 패키지이다. 최신의 다양한 Object Detection, Segmentation 알고리즘을 패키지로 구현하여 제공한다. 뛰어난 구현 성능, 효율적인 모듈 설꼐, config 기반으로 데이터부터 모델 학습, 평가 까지 이어지는 간편한 파이프라인을 적용했다.
다양한 Prebuilt 모델을 지원한다.
Back bone
Object Detection / Segmentation
MMDetection 모델 아키텍쳐
MMDetection Faster RCNN 적용
MMDetection 설치
1. mmcv-full 을 설치한다.
https://github.com/open-mmlab/mmcv
MMDetection을 설치하기 위해 mmcv가 필요하다. 위의 깃헙에 자세하게 설명이 나와있다.
$ pip install mmcv-full
2. mmdetection을 설치한다.
https://github.com/open-mmlab/mmdetection/blob/master/docs/get_started.md
$ pip install mmdet $ git clone https://github.com/open-mmlab/mmdetection.git $ cd mmdetection $ pip install -r requirements/build.txt $ pip install -v -e . # or "python setup.py develop"
github의 installation guide를 따라 설치 한것 뿐이다.
설치하는데 약 10분정도 걸린다. colab에서 하면 매번 설치해야한다... ㅠㅜㅜ
local환경에서 하려고 환경 구성을 해봤는데.. Winodws OS는 지원을 제대로 되지 않는다. WSL 환경에서는 GPU 인식이 잘안된다... 그냥 colab에서 하자.
WSL 환경에서 CUDA와 CUDNN을 설치하려면 NVIDIA-driver를 설치 해야하는데 설치할려면 Windows insider Program Dev Channel이 필요하다. Dev Channel을 구독하려면 Windows11 이 호환되는 사양이 필요한데 내 CPU는 호환되지 않는다.......
FasterRCNN inference
먼저 pretrained weight 모델을 다운로드 받기위해 mmdetection 디렉토리 밑에 checkpoints 디렉토리를 만든다.
mkdir checkpoints
pretrained weight 모델을 다운로드 받는다.
wget -O ./mmdetection/checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth http://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco _20200130-047c8118.pth
이제 본격적으로 pretrained FasterRCNN model을 사용하여 inference를 수행해보자.
from mmdet.apis import init_detector, inference_detector, show_result_pyplot
config_file = './mmdetection/configs/fast_rcnn/faster_rcnn_r50_fpn_1x_coco.py' checkpoint_file = './mmdetection/checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth'
config_file, checkpoint_file 의 경로를 설정해준다.
faster_rcnn(모델)_r50(CNN 층의 수)_fpn(Neck)_1x(학습 epoch 수)_coco(학습 데이터 셋)
model생성
model = init_detector(config_file, checkpoint_file, device='cuda:0')
init_detector 함수는 config_file과 checkpoint_file을 기반으로 model을 만들어준다.
detection을 수행할 image를 시각화 해보자.
import cv2 import matplotlib.pyplot as plt img = '/content/mmdetection/demo/demo.jpg' img_arr = cv2.cvtColor(cv2.imread(img), cv2.COLOR_BGR2RGB) plt.figure(figsize=(12, 12)) plt.imshow(img_arr)
demo.jpg detection 수행
results = inference_detector(model, img)
inference_detector의 인자로 모델과 string(file의 경로)을 입력 해준다. file은 단일, 또는 list형태로 입력될 수 있다.
results에는 80개의 array가 list형태로 저장된다. results[0] 은 ID를 0으로 판별한 object의 정보, results[1] 은 ID를 0으로 판별한 object의 정보 이런식으로 정보를 담고 있다. 80개중 하나의 array를 보자.
result[0]
array([
[3.75348572e+02, 1.19171005e+02, 3.81950867e+02, 1.34460617e+02, 1.35454863e-01],
[5.32362000e+02, 1.09554726e+02, 5.40526550e+02, 1.25222633e+02, 8.88786465e-02],
[3.61124298e+02, 1.09049202e+02, 3.68625610e+02, 1.22483063e+02, 7.20717609e-02]], dtype=float32),
result[0]은 3개의 array를 가지고있다. 즉 ID가 0인 object를 3개 판별했다는 뜻이다.앞 4개는 좌표값, 마지막 값은 confidence score를 의미한다.
시각화
show_result_pyplot(model, img, results)
inference 된 결과를 원본 이미지에 적용하여 새로운 이미지를 생성한다. score threshold는 default 값으로 0.3이 적용되어 있다. show_result_pyplot은 model.show_result()를 호출한다.
전체 코드
#pip install mmcv-full #git clone https://github.com/open-mmlab/mmdetection.git #cd mmdetection; python setup.py install #cd mmdetection; mkdir checkpoints #wget -O /content/mmdetection/checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth http://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth from mmdet.apis import init_detector, inference_detector, show_result_pyplot import cv2 import matplotlib.pyplot as plt # file path config_file = '/content/mmdetection/configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py' checkpoint_file = '/content/mmdetection/checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth' # image img = '/content/mmdetection/demo/demo.jpg' img_arr = cv2.cvtColor(cv2.imread(img), cv2.COLOR_BGR2RGB) # plt.figure(figsize=(12, 12)) # plt.imshow(img_arr) # detect results = inference_detector(model, img) show_result_pyplot(model, img, results)
video inference
from mmdet.apis import init_detector, inference_detector import mmcv import cv2 config_file = '/content/mmdetection/configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py' checkpoint_file = '/content/mmdetection/checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth' model = init_detector(config_file, checkpoint_file, device='cuda:0') video_reader = mmcv.VideoReader('/content/data/John_Wick_small.mp4') video_writer = None fourcc = cv2.VideoWriter_fourcc(*'mp4v') video_writer = cv2.VideoWriter('/content/data/John_Wick_small_out1.mp4', fourcc, video_reader.fps,(video_reader.width, video_reader.height)) for frame in mmcv.track_iter_progress(video_reader): result = inference_detector(model, frame) frame = model.show_result(frame, result, score_thr=0.4) video_writer.write(frame) if video_writer: video_writer.release()
model.show_result는 느리다. matplotlib으로 처리를 하는데 시간이 오래걸린다. openCV를 이용하면 더 빠르게 수행할 수 있다.
728x90'Deep Learning > vision' 카테고리의 다른 글
OpenCV | FasterRCNN (0) 2021.08.19 OpenCV 영상 처리 (2) 2021.08.07 Object Detection / Segmentation 주요 데이터셋 (0) 2021.08.07 Object Detection (0) 2021.08.04