Custom Detectron2 Inference!! (Person Detection)-챕터 3 학습된모델로 새로운 이미지 예측하기(구글 Colab)
본문 바로가기
Coding Project

Custom Detectron2 Inference!! (Person Detection)-챕터 3 학습된모델로 새로운 이미지 예측하기(구글 Colab)

by Migos 2020. 10. 14.
반응형

목차

EP1. 데이터셋 만들기

EP2. 모델 훈련시키기

EP3. 정확도 확인하기

 

 

새로운 이미지를 보여주고 Segmentation한 결과를 확인하는 방법이다.

 

1) 빌드를 위한 기본 코드 (패키지 임포트 등) 을 실행해주고,

2) 예측할 폴더를 생성한다음(images_test) 새로운 이미지를 폴더에 넣어주고(구글클라우드 업로드)

3) 이미지를 불러와서 학습된 모델을 통해 예측하는 순서로 결과를 확인해보자.

 

 

1) 빌드를 위한 기본 코드 및 패키지 임포트(코랩은 런타임이 초기화되기때문에 다시 활성화하는 단계부터 실행해줌)

 1-1) detectron2 폴더로 경로이동시켜준다.

 %cd /content/drive/My Drive/Coding/detectron2 (본인껄로..)

 

 1-2) 패키지 임포트(다시 해줘야함)

# torchvision 설치
!pip install -U torch torchvision
!pip install git+https://github.com/facebookresearch/fvcore.git
import torch, torchvision
torch.__version__
# detectron2 original repo clone
%cd /content/drive/My Drive/Coding/detectron2 # 경로이동
# !git clone https://github.com/facebookresearch/detectron2 detectron2_repo # 아까했죠?ㅎㅎ
!pip install -e detectron2_repo

 1-3) 런타임 다시시작 (상단메뉴-런타임 다시 시작 Ctrl+M) 클릭

 1-4) 경로가 초기화 되었으니 다시 루트폴더로 이동해줍니다.

 %cd /content/drive/My Drive/Coding/detectron2 (본인껄로..)

 

 1-5) 다시 패키지 임포트해줍니다.

# You may need to restart your runtime prior to this, to let your installation take effect
# Some basic setup
# Setup detectron2 logger
import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()

# import some common libraries
import matplotlib.pyplot as plt
import numpy as np
import cv2
from google.colab.patches import cv2_imshow

# import some common detectron2 utilities
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
from detectron2.data import MetadataCatalog, DatasetCatalog

 1-6 모두 스킵하고 아래 코드 실행해줍니다.

from detectron2.engine import DefaultTrainer
from detectron2.config import get_cfg
import os

cfg = get_cfg()
cfg.merge_from_file("/content/drive/My Drive/Coding/detectron2_tmp//detectron2_repo/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
cfg.DATASETS.TRAIN = ("person",)
cfg.DATASETS.TEST = ()   # no metrics implemented for this dataset
cfg.DATALOADER.NUM_WORKERS = 2
cfg.MODEL.WEIGHTS = "detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl"  # initialize from model zoo
cfg.SOLVER.IMS_PER_BATCH = 2
cfg.SOLVER.BASE_LR = 0.02
cfg.SOLVER.MAX_ITER = 300    # 300 iterations seems good enough, but you can certainly train longer
cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 128   # faster, and good enough for this toy dataset
cfg.MODEL.ROI_HEADS.NUM_CLASSES = 1  # 1 classes (person)

os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)
# trainer = DefaultTrainer(cfg)
# trainer.resume_or_load(resume=False)
# trainer.train()
cfg.MODEL.WEIGHTS = "/content/drive/My Drive/Coding/detectron2/output/model_final.pth" # 여기부분은 본인의 model이저장된 경로로 수정해줍니다.
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5   # set the testing threshold for this model
cfg.DATASETS.TEST = ("person", )
predictor = DefaultPredictor(cfg)

 

 1-7 새로운 이미지를 불러와서 예측해봅시다. 저는 detectron2 폴더 안에 data 폴더를 생성하고 그 안에 images_test폴더를 만든 후 제가 예측하고싶은 사진들을 업로드했습니다.

path = "/content/drive/My Drive/Coding/detectron2/data/images_test/00122.jpg"

im = cv2.imread(path)
outputs = predictor(im)
v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
v = v.draw_instance_predictions(outputs["instances"].to("cpu"))
cv2_imshow(v.get_image()[:, :, ::-1])

 

우선 학습을 많이 안했기 때문에.. 예측상태가 완벽하진 않네요.. 하지만 실제 현장 이미지에서 저정도 탐지한거면 잘 했다고 생각합니당~

 

이전 포스팅 링크는 아래와 같습니다.

Custom Detectron2 Training!! (Person Detection)-챕터 1 데이터셋 만들기

 

Custom Detectron2 Training!! (Person Detection)-챕터 1 데이터셋 만들기

목차 1. 데이터셋 만들기 2. 훈련시키기 3. 정확도 확인하기 4. 예측하기 1. 데이터셋 만들기 라벨링툴 다운로드 : Labelme << click  새폴더(ex. 바탕화면/data) 만들기 라벨링할 이미지 넣기  라벨링툴 �

hansonminlearning.tistory.com

Custom Detectron2 Training!! (Person Detection)-챕터 2 모델 훈련시키기(구글 colab)

 

Custom Detectron2 Training!! (Person Detection)-챕터 2 모델 훈련시키기(구글 colab)

목차 EP1. 데이터셋 만들기 EP2. 모델 훈련시키기 EP3. 정확도 확인하기 EP4. 예측하기 2. 모델 훈련시키기 구글드라이브 - 새폴더 생성(ex. detectron2) 마우스우클릭 - 더보기 - Google Colaboratory 클릭 런..

hansonminlearning.tistory.com

 

반응형

댓글