Detectron에서 제공 하는 documnet와 tutorial을 바탕으로 해당 내용들을 번역하며 다른 blog들을 참고하여 작성하였습니다. 스스로 내용을 정리하려고 만든 글이므로 틀린점이나 잘못된점은 지적해주시면 감사하겠습니다.
Detectron2 란?
Facebook(현 Meta) 인공지능 연구자들이 만든 pytorch 기반 object detection와 sementic segemanation을 위한 training inferecne 플랫폼입니다.
Detectron의 특징
Detectron2는 학습 루프를 pytorch로 짜인 engine을 통해 학습합니다. 기존 pytorch style이 아닌 caffe2 학습 스타일을 pytorch로 구현한 것입니다. 또한 python 최적화를 위해 연산량이 많이 드는 부분을 python이 아닌 Cuda와 C로 구현하였습니다.
Detectron의 파일 구조
Detectron에서 주로 많이 쓰이는 directroy는 model에 대한 정보가 있는 detectron2 와 훈련을 시킬 tools를 주로 사용합니다. 이때 detectron2 directory안에는 아래 이미지와 같은 다양한 라이브러리가 존재합니다.
config 폴더는 detectron2 사용시 필요한 하이퍼 파라미터들이 정의되어있습니다.
model_zoo 폴더는 특정 model에 대한 정보에 맞는 project의 특정한 config를 추가합니다. 즉, 학습한 모델들이 관리되는 폴더입니다.
ex) TensorMask
utils 폴더는 utility function들을 포함하고 있습니다.
engine 폴더에서는 data_loader로부터 온 data의 loss계산, 경사하강, optimizer와 함께 Update등 이를 통해 학습과정을 추상화 합니다.
Detectron2 실행해보기
- Python version >= 3.7
- PyTorch >= 1.8 이에 일치하는 torchvision
해당 버전을 준수하여 진행해주시면 감사하겠습니다.
python -m pip install 'git+https://github.com/facebookresearch/detectron2.git'
# (add --user if you don't have permission)
# Or, to install it from a local clone:
git clone https://github.com/facebookresearch/detectron2.git
python -m pip install -e detectron2
# On macOS, you may need to prepend the above commands with a few environment variables:
CC=clang CXX=clang++ ARCHFLAGS="-arch x86_64" python -m pip install ...
해당 git을 클론하고 실행합니다.
이후 사전 훈련된 모델을 골라야 합니다. 해당 file은 configs내에 훈련된 yaml file을 demo폴더에 있는 demo.py 로 실행합니다.
모델경로: detectron2/configs/~
demo.py 경로: detectron2/demo/demo.py
cd demo/
python demo.py --config-file ../configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml \
위 명령어는 cocodataset을 바탕으로 instance Segmentation을 진행 할 때 쓰이는 model경로입니다.
추가적으로 다른 기능을 사용하려면 다음과 같이 진행합니다.
웹캠에서 실행: --input files--webcam
비디오에서 실행: --input files--video-input video.mp4
cpu에서 실행: MODEL.DEVICE cpu--opts
Pre-trained된 detectron2 model 실행하기
아래코드는 Detectron2 tutorial의 코드를 바탕으로 진행하였습니다.
먼저 test image를 불러옵니다.
!wget http://images.cocodataset.org/val2017/000000439715.jpg -q -O input.jpg
im = cv2.imread("./input.jpg")
cv2_imshow(im)
이후 detectron2 config를 만들고, 해당 이미지에대한 inference를 Detectron2의 DefaultPredictor로 실행시킵니다.
해당 DefaultPredictor는 detectron2/detectron2/engine/defaults.py에 있습니다.
cfg = get_cfg()
# add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library
cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model
# Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
predictor = DefaultPredictor(cfg)
outputs = predictor(im)
DefaultPredictor의 역할은 단일 입력 이미지에 대해 단일 장치에서 실행되는 지정된 구성으로 간단한 예측자를 만듭니다.
이후 해당 config에 대해 Predict을 하면 해당 이미지 데이터에 대한 예측 class와 예측 boxes가 만들어지게 됩니다.
이후 해당 정보를 바탕으로 object detection을 진행합니다.
# We can use `Visualizer` to draw the predictions on the image.
v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
cv2_imshow(out.get_image()[:, :, ::-1])
진행방식은 MetadatCatlog를 통해 해당 dataset의 train정보(class)를 저장합니다,이후 이를 바탕으로 utils에 있는 Visualizer를 통해,
numpy 배열(H, W, C)와 MetadataCatalog를 통해 나온 global dictionary를 인자값으로 넣어 이미지에 대한 detection/segmentation에 대한 데이터를 그립니다.
여기서 H 및 W는 각각 이미지의 높이와 너비. C는 색상 채널의 수입니다. Matplotlib 라이브러리의 요구 사항이므로 이미지는 RGB 형식이어야 합니다.
마지막으로 img[:,:,::-1]에 대한 의미는 open cv channel은 BGR로 되어있어서 이를 RGB로 convert하는 과정입니다.
Custom dataset에 대한 내용은 추후 작성하도록 하겠습니다.
지적할 부분이나 정정할 부분 있으면 말해주시면 감사하겠습니다.
'AI > Computer vision' 카테고리의 다른 글
Yolov5 Deep learning (2) (0) | 2022.07.07 |
---|---|
Detectron 2 with custom dataset (0) | 2022.07.06 |
YOLOv5 Deep learning (1) (0) | 2022.07.01 |
COCO dataset (0) | 2022.06.27 |