Two/영상처리

mmdetection - tutorial (3)

DH Father 2024. 1. 17. 16:22

mmdetection

tutorial (3)



mmdetection - tutorial (3)

mmdetection 설치, config 파일, inference, dataset 준비 하는 부분까지 스터디했다.

오늘은 testing, traing 하는 방법에 대해 알아보자.

 

 

Test Existing Models on Standard Datasets

 

Test existing models

test script 를 사용하여 존재하는 모델의 평가를 제공한다.

single GPU, CPU, Single node multiple GPUs, Multiple nodes 환경 지원한다.

# Single-gpu testing
python tools/test.py \
    ${CONFIG_FILE} \
    ${CHECKPOINT_FILE} \
    [--out ${RESULT_FILE}] \
    [--show]

# CPU: disable GPUs and run single-gpu testing script
export CUDA_VISIBLE_DEVICES=-1
python tools/test.py \
    ${CONFIG_FILE} \
    ${CHECKPOINT_FILE} \
    [--out ${RESULT_FILE}] \
    [--show]

# Multi-gpu testing
bash tools/dist_test.sh \
    ${CONFIG_FILE} \
    ${CHECKPOINT_FILE} \
    ${GPU_NUM} \
    [--out ${RESULT_FILE}]

 

Optional arguments 

자세한건 문서 참조

  • RESULT_FILE
  • --show
  • --show-dir
  • --work-dir
  • --cfg-options

 

Examples

config, checkpoint 파일을 먼저 다운로드 받는다.

# 1. Test RTMDet and visualize the results. Press any key for the next image
python tools/test.py \
    configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \
    checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \
    --show
    
    

# 2. Test RTMDet and save the painted images for future visualization
python tools/test.py \
    configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \
    checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \
    --show-dir faster_rcnn_r50_fpn_1x_results
    
    
# 3.Test Faster R-CNN on PASCAL VOC (without saving the test results)
python tools/test.py \
    configs/pascal_voc/faster-rcnn_r50_fpn_1x_voc0712.py \
    checkpoints/faster_rcnn_r50_fpn_1x_voc0712_20200624-c9895d40.pth
    
    
# 4. Test Mask R-CNN with 8 GPUs, and evaluate
./tools/dist_test.sh \
    configs/mask-rcnn_r50_fpn_1x_coco.py \
    checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \
    8 \
    --out results.pkl
    
    
# 5.Test Mask R-CNN with 8 GPUs, and evaluate the metric class-wise.
./tools/dist_test.sh \
    configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \
    checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \
    8 \
    --out results.pkl \
    --cfg-options test_evaluator.classwise=True
    
    
# 6. est Mask R-CNN on COCO test-dev with 8 GPUs, and generate JSON files for submitting to the official evaluation server
#replace the original test_evaluator and test_dataloader with test_evaluator and test_dataloader in the comment in and run:
./tools/dist_test.sh \
    configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \
    checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \
    8


# 7.Test Mask R-CNN on Cityscapes test with 8 GPUs, and generate txt and png files for submitting to the official evaluation server
# Replace the original test_evaluator and test_dataloader with test_evaluator and test_dataloader in the comment in and run:
./tools/dist_test.sh \
    configs/cityscapes/mask-rcnn_r50_fpn_1x_cityscapes.py \
    checkpoints/mask_rcnn_r50_fpn_1x_cityscapes_20200227-afe51d5a.pth \
    8

 

Test without Ground Truth Annotations

아래의 명령어를 통해 COCO 데이터셋이 아닌것을 COCO 형태로 변환가능하다. 

자세한 내용은 문서를 참조하자.

python tools/dataset_converters/images2coco.py \
    ${IMG_PATH} \
    ${CLASSES} \
    ${OUT} \
    [--exclude-extensions]

 

Batch Inference -->> To Do..

Test Time Augmentation -->> To Do..

 

 

Train Predefined Models on Standard Datsets

 

Prepare datasets

 

Learning rate auto scaling

default learning rate은 8GPU, 2 sample per GPU 로 batch size = 8 * 2 = 16 이다.

auto scaling은 config/_base_/schedules/schedule_1x.py 에서 auto_scale_lr.base_batch_size에 있으며,

auto_sacel_lr.eable 은 default 로 False로 되어있다. 

commad line에서는 아래와 같이 사용할 수 있다.

python tools/train.py \
    ${CONFIG_FILE} \
    --auto-scale-lr \
    [optional arguments]

 

Training on a single GPU

tools/train.py 를  사용하여 single GPU로 학습이 가능하며, work_dir 에 chekcpoint와 log 파일이 저장된다.

python tools/train.py \
    ${CONFIG_FILE} \
    [optional arguments]

 

Training on CPU

training 전에 아래의 명령어를 실행한 후, training 하면 cpu로 실행된다.

export CUDA_VISIBLE_DEVICES=-1

 

Training on multiple GPUs

tools/dist_train.sh 를 사용하면 multiple GPU 사용 가능하며, GPU를 지정해서 사용할 수도 있다.

bash ./tools/dist_train.sh \
    ${CONFIG_FILE} \
    ${GPU_NUM} \
    [optional arguments]
CUDA_VISIBLE_DEVICES=0,1,2,3 PORT=29500 ./tools/dist_train.sh ${CONFIG_FILE} 4
CUDA_VISIBLE_DEVICES=4,5,6,7 PORT=29501 ./tools/dist_train.sh ${CONFIG_FILE} 4

 

Train with multiple machines

이더넷을 연결하여 사용할 수 있음

Manage jobs with slurm

 

 

Train With Customized Datasets

 

전체 프로세스는 아래와 같다.

1. customized dataset 준비

2. config 파일 수정

3. train, test, inference 수행

 

Prepare the customized dataset

MMDetection에서는 아래 3종류로 customized 데이터셋을 인식할 수 있다.

1, 2번을 사용하는 것이 편하다고 하니 2가지 중에서 사용하는게 좋을 것 같다.

1. COCO format

2. middle format

3. Implement a new dataset

 

COCO annotation format

COCO 데이터셋 포맷은 링크에 들어가면 더 자세히 볼 수 있다. https://cocodataset.org/#format-data

{
    "images": [image],
    "annotations": [annotation],
    "categories": [category]
}

image = {
    "id": int,
    "width": int,
    "height": int,
    "file_name": str,
}

annotation = {
    "id": int,
    "image_id": int,
    "category_id": int,
    "segmentation": RLE or [polygon],
    "area": float,
    "bbox": [x,y,width,height], # (x, y) are the coordinates of the upper left corner of the bbox
    "iscrowd": 0 or 1,
}

categories = [{
    "id": int,
    "name": str,
    "supercategory": str,
}]

documentation에서 제시하는 ballon dataset의 aanotation 파일은 아래와 같다. 

이것을 COCO format 형태로 변경하여, config 파일의 CocoDataset 으로 학습을 할 수 있다. 

{'base64_img_data': '',
 'file_attributes': {},
 'filename': '34020010494_e5cb88e1c4_k.jpg',
 'fileref': '',
 'regions': {'0': {'region_attributes': {},
   'shape_attributes': {'all_points_x': [1020,
     1000,
     994,
     1003,
     1023,
     1050,
     1089,
     1134,
     1190,
     1265,
     1321,
     1361,
     1403,
     1428,
     1442,
     1445,
     1441,
     1427,
     1400,
     1361,
     1316,
     1269,
     1228,
     1198,
     1207,
     1210,
     1190,
     1177,
     1172,
     1174,
     1170,
     1153,
     1127,
     1104,
     1061,
     1032,
     1020],
    'all_points_y': [963,
     899,
     841,
     787,
     738,
     700,
     663,
     638,
     621,
     619,
     643,
     672,
     720,
     765,
     800,
     860,
     896,
     942,
     990,
     1035,
     1079,
     1112,
     1129,
     1134,
     1144,
     1153,
     1166,
     1166,
     1150,
     1136,
     1129,
     1122,
     1112,
     1084,
     1037,
     989,
     963],
    'name': 'polygon'}}},
 'size': 1115004}

아래의 코드는 balloon 데이터셋을 COCO 포맷으로 변경하는 코드이다. 

import os.path as osp

import mmcv

from mmengine.fileio import dump, load
from mmengine.utils import track_iter_progress


def convert_balloon_to_coco(ann_file, out_file, image_prefix):
    data_infos = load(ann_file)

    annotations = []
    images = []
    obj_count = 0
    for idx, v in enumerate(track_iter_progress(data_infos.values())):
        filename = v['filename']
        img_path = osp.join(image_prefix, filename)
        height, width = mmcv.imread(img_path).shape[:2]

        images.append(
            dict(id=idx, file_name=filename, height=height, width=width))

        for _, obj in v['regions'].items():
            assert not obj['region_attributes']
            obj = obj['shape_attributes']
            px = obj['all_points_x']
            py = obj['all_points_y']
            poly = [(x + 0.5, y + 0.5) for x, y in zip(px, py)]
            poly = [p for x in poly for p in x]

            x_min, y_min, x_max, y_max = (min(px), min(py), max(px), max(py))

            data_anno = dict(
                image_id=idx,
                id=obj_count,
                category_id=0,
                bbox=[x_min, y_min, x_max - x_min, y_max - y_min],
                area=(x_max - x_min) * (y_max - y_min),
                segmentation=[poly],
                iscrowd=0)
            annotations.append(data_anno)
            obj_count += 1

    coco_format_json = dict(
        images=images,
        annotations=annotations,
        categories=[{
            'id': 0,
            'name': 'balloon'
        }])
    dump(coco_format_json, out_file)


if __name__ == '__main__':
    convert_balloon_to_coco(ann_file='data/balloon/train/via_region_data.json',
                            out_file='data/balloon/train/annotation_coco.json',
                            image_prefix='data/balloon/train')
    convert_balloon_to_coco(ann_file='data/balloon/val/via_region_data.json',
                            out_file='data/balloon/val/annotation_coco.json',
                            image_prefix='data/balloon/val')

 

Prepare a config

아래의 코드와 같이 config 파일을 수정해준다. 

classses 수, data_root, ann_file, data_prefix, load_from 부분 등을 필요에 맞게 수정하면 되는것 같다. 

# The new config inherits a base config to highlight the necessary modification
_base_ = '../mask_rcnn/mask-rcnn_r50-caffe_fpn_ms-poly-1x_coco.py'

# We also need to change the num_classes in head to match the dataset's annotation
model = dict(
    roi_head=dict(
        bbox_head=dict(num_classes=1), mask_head=dict(num_classes=1)))

# Modify dataset related settings
data_root = 'data/balloon/'
metainfo = {
    'classes': ('balloon', ),
    'palette': [
        (220, 20, 60),
    ]
}
train_dataloader = dict(
    batch_size=1,
    dataset=dict(
        data_root=data_root,
        metainfo=metainfo,
        ann_file='train/annotation_coco.json',
        data_prefix=dict(img='train/')))
val_dataloader = dict(
    dataset=dict(
        data_root=data_root,
        metainfo=metainfo,
        ann_file='val/annotation_coco.json',
        data_prefix=dict(img='val/')))
test_dataloader = val_dataloader

# Modify metric related settings
val_evaluator = dict(ann_file=data_root + 'val/annotation_coco.json')
test_evaluator = val_evaluator

# We can use the pre-trained Mask RCNN model to obtain higher performance
load_from = 'https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth'

 

Train a new model

아래의 명령어를 사용하여 학습을 할 수 있다. 

python tools/train.py configs/balloon/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon.py

 

Test and inference

아래의 명령어를 사용하여 test, inference 를 수행할 수 있다. 

python tools/test.py configs/balloon/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon.py work_dirs/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon/epoch_12.pth

 

Reference

https://mmdetection.readthedocs.io/en/latest/user_guides/test.html