Datasets 文件
目標檢測
加入 Hugging Face 社群
並獲得增強的文件體驗
開始使用
目標檢測
目標檢測模型用於識別影像中的物體,而目標檢測資料集則用於自動駕駛和檢測自然災害(如野火)等應用。本指南將向您展示如何根據 Albumentations 的教程對目標檢測資料集應用變換。
要執行這些示例,請確保您已安裝最新版本的 albumentations 和 cv2。
pip install -U albumentations opencv-python
在本例中,您將使用 cppe-5
資料集,該資料集用於在 COVID-19 大流行的背景下識別醫療個人防護裝置 (PPE)。
載入資料集並檢視一個示例
>>> from datasets import load_dataset
>>> ds = load_dataset("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
... )
... )

建立一個函式,將變換應用於一批示例
>>> 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() 函式可以動態應用變換,這會消耗更少的磁碟空間。資料增強的隨機性可能會導致您兩次訪問同一示例時返回不同的影像。這在對模型進行多輪訓練時尤其有用。
>>> 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']]
... )
... )

現在您已經知道如何為目標檢測處理資料集了,接下來學習如何訓練一個目標檢測模型並用它進行推理。