Datasets documentation

オブジェクト検出

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.2.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

オブジェクト検出

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) が含まれます。

bboxesを画像上に可視化するには、torchの内部ユーティリティを使用できます。そのためには、カテゴリ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() 関数を使用すると、変換をオンザフライで適用でき、ディスク容量の消費を削減できます。データ拡張のランダム性により、同じサンプルに2回アクセスすると、異なる画像が返される場合があります。これは、モデルを複数エポックにわたって学習させる際に特に有用です。

>>> 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