Datasets documentation
객체 감지
객체 감지
Object detection 모델은 이미지 내의 객체를 식별하며, object detection 데이터셋은 자율 주행이나 산불과 같은 자연 재해 탐지와 같은 애플리케이션에 사용됩니다. 이 가이드에서는 Albumentations의 tutorial에 따라 object detection 데이터셋에 변환을 적용하는 방법을 보여줍니다.
이 예제를 실행하려면 albumentations와 cv2의 최신 버전이 설치되어 있는지 확인하세요:
pip install -U albumentations opencv-python
이 예제에서는 COVID-19 팬데믹 맥락에서 의료용 개인 보호 장비(PPE)를 식별하기 위해 cppe-5 데이터셋을 사용합니다.
데이터셋을 로드하고 예시를 확인해 보세요:
>>> from datasets import load_dataset
>>> ds = load_dataset("rishitdagli/cppe-5")
>>> example = ds['train'][0]
>>> example
{'height': 663,
'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=943x663 at 0x7FC3DC756250>,
'image_id': 15,
'objects': {'area': [3796, 1596, 152768, 81002],
'bbox': [[302.0, 109.0, 73.0, 52.0],
[810.0, 100.0, 57.0, 28.0],
[160.0, 31.0, 248.0, 616.0],
[741.0, 68.0, 202.0, 401.0]],
'category': [4, 4, 0, 0],
'id': [114, 115, 116, 117]},
'width': 943}데이터셋에는 다음 필드가 있습니다:
image: 이미지를 포함하는 PIL.Image.Image 객체.image_id: 이미지 ID입니다.height: 이미지의 높이.width: 이미지의 너비.objects: 이미지의 객체에 대한 바운딩 박스 메타데이터를 포함하는 사전:id: 어노테이션 ID.area: 바운딩 박스의 면적.bbox: 객체의 바운딩 박스(coco 형식).category: 객체의 카테고리이며, 가능한 값에는Coverall (0),Face_Shield (1),Gloves (2),Goggles (3),Mask (4)등이 있습니다.
일부 내부 torch 유틸리티를 사용하여 이미지 위에 bboxes를 시각화할 수 있습니다. 이를 위해 카테고리 ID와 연관된 ClassLabel 기능을 참조하여 문자열 라벨을 조회해야 합니다:
>>> import torch
>>> from torchvision.ops import box_convert
>>> from torchvision.utils import draw_bounding_boxes
>>> from torchvision.transforms.functional import pil_to_tensor, to_pil_image
>>> categories = ds['train'].features['objects'].feature['category']
>>> boxes_xywh = torch.tensor(example['objects']['bbox'])
>>> boxes_xyxy = box_convert(boxes_xywh, 'xywh', 'xyxy')
>>> labels = [categories.int2str(x) for x in example['objects']['category']]
>>> to_pil_image(
... draw_bounding_boxes(
... pil_to_tensor(example['image']),
... boxes_xyxy,
... colors="red",
... labels=labels,
... )
... )
albumentations를 사용하면 이미지를 변환하는 동시에 bboxes도 그에 맞게 업데이트할 수 있습니다. 이 경우 이미지는 (480, 480)으로 리사이즈되고, 수평으로 뒤집히며, 밝기가 증가합니다.
>>> import albumentations
>>> import numpy as np
>>> transform = albumentations.Compose([
... albumentations.Resize(480, 480),
... albumentations.HorizontalFlip(p=1.0),
... albumentations.RandomBrightnessContrast(p=1.0),
... ], bbox_params=albumentations.BboxParams(format='coco', label_fields=['category']))
>>> image = np.array(example['image'])
>>> out = transform(
... image=image,
... bboxes=example['objects']['bbox'],
... category=example['objects']['category'],
... )이제 결과를 시각화하면 이미지는 뒤집혀 있어야 하지만, bboxes는 여전히 올바른 위치에 있어야 합니다.
>>> image = torch.tensor(out['image']).permute(2, 0, 1)
>>> boxes_xywh = torch.stack([torch.tensor(x) for x in out['bboxes']])
>>> boxes_xyxy = box_convert(boxes_xywh, 'xywh', 'xyxy')
>>> labels = [categories.int2str(x) for x in out['category']]
>>> to_pil_image(
... draw_bounding_boxes(
... image,
... boxes_xyxy,
... colors='red',
... labels=labels
... )
... )
예시(batch)에 변환을 적용하는 함수를 생성합니다:
>>> def transforms(examples):
... images, bboxes, categories = [], [], []
... for image, objects in zip(examples['image'], examples['objects']):
... image = np.array(image.convert("RGB"))
... out = transform(
... image=image,
... bboxes=objects['bbox'],
... category=objects['category']
... )
... images.append(torch.tensor(out['image']).permute(2, 0, 1))
... bboxes.append(torch.tensor(out['bboxes']))
... categories.append(out['category'])
... return {'image': images, 'bbox': bboxes, 'category': categories}set_transform() 함수를 사용하면 변환을 온더플라이(on-the-fly)로 적용하여 디스크 공간을 덜 차지할 수 있습니다. 데이터 증강의 무작위성으로 인해 동일한 예시를 두 번 접근하면 서로 다른 이미지가 반환될 수 있습니다. 이는 여러 에포크에 걸쳐 모델을 학습시킬 때 특히 유용합니다.
>>> ds['train'].set_transform(transforms)10번째 예시를 시각화하여 변환이 제대로 작동하는지 확인할 수 있습니다:
>>> example = ds['train'][10]
>>> to_pil_image(
... draw_bounding_boxes(
... example['image'],
... box_convert(example['bbox'], 'xywh', 'xyxy'),
... colors='red',
... labels=[categories.int2str(x) for x in example['category']]
... )
... )
Update on GitHub객체 감지를 위한 데이터셋 처리 방법을 알게 되셨으니, 객체 감지 모델을 학습하는 방법과 추론 시 사용법을 배워보세요.