상세 컨텐츠

본문 제목

Detectron2 활용법 (2) - Dataloader & Data Augmentation

Machine Learning

by 땅콩또복 2022. 10. 14. 00:00

본문

Pytorch와 마찬가지로 Detectron2도 dataloader를 통해서 데이터를 보낼 수 있다

 

1. Dataloader 구조

Detectron2에서 제공하고 있는 기본적인 loader는

더보기

build_detection_{train,test}_loader

이다.

Loader는 mapper를 input으로 받아 수행이 되도록 되어 있는데 default mapperDatasetMapper 라는 곳에 담겨 있다

 

예를들어 만약 data augmentation (e.g. resizing)을 수행하고 싶을 경우, 다음과 같이 진행한다.

import detectron2.data.transforms as T
from detectron2.data import DatasetMapper   # the default mapper

mapper = DatasetMapper(cfg, is_train = True, augmentations = [T.Resize((800, 800))])
dataloader = build_detection_train_loader(cfg, mapper = mapper)

# use this dataloader instead of the default

만약 기본적인 DatasetMapper가 마음에 들지 않는다면 하단처럼 별도의 생성이 필요하다

from detectron2.data import detection_utils as utils
 # Show how to implement a minimal mapper, similar to the default DatasetMapper
def mapper(dataset_dict):
    dataset_dict = copy.deepcopy(dataset_dict)  # it will be modified by code below
    # can use other ways to read image
    image = utils.read_image(dataset_dict["file_name"], format="BGR")
    # See "Data Augmentation" tutorial for details usage
    auginput = T.AugInput(image)
    transform = T.Resize((800, 800))(auginput)
    image = torch.from_numpy(auginput.image.transpose(2, 0, 1))
    annos = [
        utils.transform_instance_annotations(annotation, [transform], image.shape[1:])
        for annotation in dataset_dict.pop("annotations")
    ]
    return {
       # create the format that the model expects
       "image": image,
       "instances": utils.annotations_to_instances(annos, image.shape[1:])
    }
dataloader = build_detection_train_loader(cfg, mapper=mapper)

 

2. Custom dataloader를 만들고 싶을 경우

Detectron2에서 제공하는 DefaultTrainerbuild_{train,test}_loaderoverwrite해서 사용하면 된다. 

참고할만한 예시 링크: https://github.com/facebookresearch/detectron2/blob/main/projects/DeepLab/train_net.py

 

Trainer 사용법은 다음과 같다

trainer = DefaultTrainer(cfg)
trainer.resume_or_load()  # load last checkpoint or MODEL.WEIGHTS
trainer.train()

 

3. Data augmentation

일반적은 data augmentation은 image에도 적용이 되지만 (이해한 바에 따르면) 동시에 bounding boxes, video clip 등에 영향을 미치기 때문에 별도로 detectron2에서 제공하는 transform을 써야한다. (이 외에 albumentation 같은 것들이 있다)

Detectron2에서 제공하는 augmentation은 크게 3가지 특징이 있다.

  1. T.Augmentation: Augmentation policy를 정하는 단계 (e.g. crop, resize, 등)
  2. T.Transform: data transformation을 위하여 실제 operation을 실행하는 단계 
  3. T.AugInput: augmentation에 사용하기 위한 input 불러옴

4. 심화: Custom Data augmentation + 기타

buitin data augmentation을 사용하지 않고, 나만의 data augmentation도 물론 가능하다.

하지만 여기서는 다루지 말자.. 이것까지 하기에는 너무 많다...

 

5. Reference

https://detectron2.readthedocs.io/en/latest/tutorials/augmentation.html

관련글 더보기

댓글 영역