# 画像セグメンテーション

Image segmentationモデルは、画像内の異なる関心領域に対応する領域を分離します。これらのモデルは、各ピクセルにラベルを割り当てることで動作します。セグメンテーションには、semantic segmentation、instance segmentation、panoptic segmentationのいくつかの種類があります。

このガイドでは、以下を行います：

1. [セグメンテーションのさまざまなタイプを確認](#types-of-segmentation)。
2. [セマンティックセグメンテーションのエンドツーエンドのファインチューニングの例](#fine-tuning-a-model-for-segmentation)

開始前に、必要なライブラリがすべてインストールされていることを確認してください。

```py
# uncomment to install the necessary libraries
!pip install -q datasets transformers evaluate accelerate trackio
```

モデルをコミュニティにアップロードして共有できるよう、Hugging Face アカウントへのログインをお勧めします。プロンプトが表示されたら、ログイン用のトークンを入力してください:

```py
>>> from huggingface_hub import notebook_login

>>> notebook_login()
```

## セグメンテーションの種類

セマンティックセグメンテーションは、画像内のすべてのピクセルにラベルまたはクラスを割り当てます。セマンティックセグメンテーションモデルの出力を見てみましょう。このモデルは、画像内で遭遇するオブジェクトのすべてのインスタンスに同じクラスを割り当てます。例えば、すべての猫は「cat-1」や「cat-2」ではなく「cat」とラベル付けされます。transformersの画像セグメンテーションパイプラインを使用して、セマンティックセグメンテーションモデルをすばやく推論できます。例の画像を見てみましょう。

```python
from transformers import pipeline
from PIL import Image
import requests

url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/segmentation_input.jpg"
image = Image.open(requests.get(url, stream=True).raw)
image
```

     

[nvidia/segformer-b1-finetuned-cityscapes-1024-1024](https://huggingface.co/nvidia/segformer-b1-finetuned-cityscapes-1024-1024)を使用します。

```python
semantic_segmentation = pipeline("image-segmentation", "nvidia/segformer-b1-finetuned-cityscapes-1024-1024")
results = semantic_segmentation(image)
results
```

セグメンテーションパイプラインの出力には、予測された各クラスのマスクが含まれます。

```bash
[{'score': None,
  'label': 'road',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': None,
  'label': 'sidewalk',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': None,
  'label': 'building',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': None,
  'label': 'wall',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': None,
  'label': 'pole',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': None,
  'label': 'traffic sign',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': None,
  'label': 'vegetation',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': None,
  'label': 'terrain',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': None,
  'label': 'sky',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': None,
  'label': 'car',
  'mask': <PIL.Image.Image image mode=L size=612x415>}]
```

carクラスのマスクを確認すると、すべての車に同じマスクが割り当てられていることがわかります。

```python
results[-1]["mask"]
```

     

インスタンスセグメンテーションでは、すべてのピクセルを分類することではなく、与えられた画像内の**オブジェクトのすべてのインスタンス**に対してマスクを予測することが目的です。これはオブジェクト検出と非常に似ており、各インスタンスにバウンディングボックスがある代わりに、セグメンテーションマスクが存在します。ここでは[facebook/mask2former-swin-large-cityscapes-instance](https://huggingface.co/facebook/mask2former-swin-large-cityscapes-instance)を使用します。

```python
instance_segmentation = pipeline("image-segmentation", "facebook/mask2former-swin-large-cityscapes-instance")
results = instance_segmentation(image)
results
```

以下に示すように、複数の車が分類されており、車と人のインスタンスに属するピクセル以外のピクセルには分類が適用されていません。

```bash
[{'score': 0.999944,
  'label': 'car',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': 0.999945,
  'label': 'car',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': 0.999652,
  'label': 'car',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': 0.903529,
  'label': 'person',
  'mask': <PIL.Image.Image image mode=L size=612x415>}]
```

…

```python
results[2]["mask"]
```

     

パンノプティックセグメンテーションは、セマンティックセグメンテーションとインスタンスセグメンテーションを組み合わせる手法です。この手法では、すべてのピクセルがクラスとそのクラスのインスタンスに分類され、各クラスのインスタンスごとに複数のマスクが生成されます。これには、[facebook/mask2former-swin-large-cityscapes-panoptic](https://huggingface.co/facebook/mask2former-swin-large-cityscapes-panoptic)を使用できます。

```python
panoptic_segmentation = pipeline("image-segmentation", "facebook/mask2former-swin-large-cityscapes-panoptic")
results = panoptic_segmentation(image)
results
```

下に示すように、クラスがより多く存在します。後ほど、各ピクセルがこれらのクラスのいずれかに分類されることを図示します。

```bash
[{'score': 0.999981,
  'label': 'car',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': 0.999958,
  'label': 'car',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': 0.99997,
  'label': 'vegetation',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': 0.999575,
  'label': 'pole',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': 0.999958,
  'label': 'building',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': 0.999634,
  'label': 'road',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': 0.996092,
  'label': 'sidewalk',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': 0.999221,
  'label': 'car',
  'mask': <PIL.Image.Image image mode=L size=612x415>},
 {'score': 0.99987,
  'label': 'sky',
  'mask': <PIL.Image.Image image mode=L size=612x415>}]
```

セグメンテーションのすべてのタイプについて、並べて比較してみましょう。

     

セグメンテーションのすべての種類を見てきましたが、ここではセマンティックセグメンテーション用のモデルのファインチューニングについて詳しく見ていきましょう。

セマンティックセグメンテーションの一般的な実世界での応用には、自動運転車において歩行者や重要な交通情報を識別するための学習、医療画像における細胞や異常の特定、衛星画像からの環境変化の監視などが含まれます。

## セグメンテーション用のモデルのファインチューニング

次に、次のことを行います。

1. [SceneParse150](https://huggingface.co/datasets/merve/scene_parse_150) データセットで [SegFormer](../model_doc/segformer#segformer) をファインチューニングします。
2. ファインチューニングしたモデルを推論に使用します。

このタスクと互換性のあるすべてのアーキテクチャとチェックポイントを確認するには、[タスクページ](https://huggingface.co/tasks/image-segmentation)を参照することをお勧めします。

### SceneParse150 データセットを読み込む

🤗 Datasets ライブラリから SceneParse150 データセットのより小さなサブセットを読み込むことから始めます。これにより、フルデータセットでの学習により多くの時間を費やす前に、実験を行い、すべてが正常に動作することを確認できます。

```py
>>> from datasets import load_dataset

>>> ds = load_dataset("merve/scene_parse_150", split="train[:50]")
```

[train_test_split](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.Dataset.train_test_split) メソッドを使用して、データセットの`train` スプリットを学習セットとテストセットに分割します:

```py
>>> ds = ds.train_test_split(test_size=0.2)
>>> train_ds = ds["train"]
>>> test_ds = ds["test"]
```

次に、例を見てみましょう。

```py
>>> train_ds[0]
{'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=512x683 at 0x7F9B0C201F90>,
 'annotation': <PIL.PngImagePlugin.PngImageFile image mode=L size=512x683 at 0x7F9B0C201DD0>,
 'scene_category': 368}

# view the image
>>> train_ds[0]["image"]
```

- `image`: シーンのPIL画像。
- `annotation`: セグメンテーションマップのPIL画像であり、モデルのターゲットでもあります。
- `scene_category`: 「kitchen」や「office」のように、画像のシーンを説明するカテゴリ ID です。このガイドでは、`image` と `annotation` の 2 つのみが必要ですが、どちらも PIL 画像です。

後でモデルを設定する際に役立つ、ラベル ID からラベルクラスへのマッピングを行う辞書も作成する必要があります。Hub からマッピングをダウンロードし、`id2label` と `label2id` の辞書を作成します。

```py
>>> import json
>>> from pathlib import Path
>>> from huggingface_hub import hf_hub_download

>>> repo_id = "huggingface/label-files"
>>> filename = "ade20k-id2label.json"
>>> id2label = json.loads(Path(hf_hub_download(repo_id, filename, repo_type="dataset")).read_text())
>>> id2label = {int(k): v for k, v in id2label.items()}
>>> label2id = {v: k for k, v in id2label.items()}
>>> num_labels = len(id2label)
```

### 前処理

次のステップは、SegFormerの画像プロセッサを読み込み、モデル用の画像とアノテーションを準備することです。このデータセットのように、背景クラスとしてゼロインデックスを使用するデータセットもあります。ただし、背景クラスは実際には150クラスに含まれていないため、すべてのラベルから1を引くために`do_reduce_labels=True`を設定する必要があります。ゼロインデックスは`255`に置き換えられ、SegFormerの損失関数によって無視されます。

```py
>>> from transformers import AutoImageProcessor

>>> checkpoint = "nvidia/mit-b0"
>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint, do_reduce_labels=True)
```

モデルの過学習に対する頑健性を高めるために、画像データセットにいくつかのデータ拡張を適用することは一般的です。このガイドでは、[torchvision](https://pytorch.org/vision/stable/index.html)の[`ColorJitter`](https://pytorch.org/vision/stable/generated/torchvision.transforms.ColorJitter.html)関数を使用して画像の色特性をランダムに変更しますが、お好みの画像ライブラリを使用することもできます。

```py
>>> from torchvision.transforms import ColorJitter

>>> jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
```

次に、画像とアノテーションをモデル用に準備するための2つの前処理関数を作成します。これらの関数は、画像を`pixel_values`に、アノテーションを`labels`に変換します。トレーニングセットでは、画像を画像プロセッサに渡す前に`jitter`が適用されます。テストセットでは、画像プロセッサが`images`をクロップして正規化し、`labels`はクロップのみを行います。これは、テスト時にはデータ拡張が適用されないためです。

```py
>>> def train_transforms(example_batch):
...     images = [jitter(x) for x in example_batch["image"]]
...     labels = [x for x in example_batch["annotation"]]
...     inputs = image_processor(images, labels)
...     return inputs

>>> def val_transforms(example_batch):
...     images = [x for x in example_batch["image"]]
...     labels = [x for x in example_batch["annotation"]]
...     inputs = image_processor(images, labels)
...     return inputs
```

`jitter`をデータセット全体に適用するには、🤗 Datasetsの[set_transform](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.Dataset.set_transform)関数を使用します。この変換はオンザフライで適用されるため、より高速であり、ディスク容量の消費も少なくなります。

```py
>>> train_ds.set_transform(train_transforms)
>>> test_ds.set_transform(val_transforms)
```

### 評価

学習中にメトリクスを含めることは、モデルの性能を評価する上でしばしば役立ちます。🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) ライブラリを使用すると、評価手法をすばやく読み込むことができます。このタスクでは、[mean Intersection over Union](https://huggingface.co/spaces/evaluate-metric/accuracy)（IoU）メトリクスを読み込みます（メトリクスの読み込みと計算方法の詳細については、🤗 Evaluate の [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) を参照してください）：

```py
>>> import evaluate

>>> metric = evaluate.load("mean_iou")
```

次に、メトリクスを[計算](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute)する関数を作成します。予測値はまずlogitsに変換し、ラベルのサイズに合わせてリシェイプしてから、[compute](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute)を呼び出す必要があります:

```py
>>> import numpy as np
>>> import torch
>>> from torch import nn

>>> def compute_metrics(eval_pred):
...     with torch.no_grad():
...         logits, labels = eval_pred
...         logits_tensor = torch.from_numpy(logits)
...         logits_tensor = nn.functional.interpolate(
...             logits_tensor,
...             size=labels.shape[-2:],
...             mode="bilinear",
...             align_corners=False,
...         ).argmax(dim=1)

...         pred_labels = logits_tensor.detach().cpu().numpy()
...         metrics = metric.compute(
...             predictions=pred_labels,
...             references=labels,
...             num_labels=num_labels,
...             ignore_index=255,
...             reduce_labels=False,
...         )
...         for key, value in metrics.items():
...             if isinstance(value, np.ndarray):
...                 metrics[key] = value.tolist()
...         return metrics
```

`compute_metrics`関数はこれで準備が整いました。学習を設定する際に、この関数に戻ります。

### 学習

[Trainer](/docs/transformers/v5.23.0/ja/main_classes/trainer#transformers.Trainer)によるモデルのファインチューニングに慣れていない場合は、[こちら](../training)の基本的なチュートリアルをご覧ください!

いよいよモデルの学習を開始できます![AutoModelForSemanticSegmentation](/docs/transformers/v5.23.0/ja/model_doc/auto#transformers.AutoModelForSemanticSegmentation)でSegFormerを読み込み、ラベルIDとラベルクラスの対応関係をモデルに渡します:

```py
>>> from transformers import AutoModelForSemanticSegmentation, TrainingArguments, Trainer

>>> model = AutoModelForSemanticSegmentation.from_pretrained(checkpoint, id2label=id2label, label2id=label2id)
```

この時点で、残りのステップは3つだけです:

1. [TrainingArguments](/docs/transformers/v5.23.0/ja/main_classes/trainer#transformers.TrainingArguments) で学習ハイパーパラメータを定義します。未使用の列を削除しないことが重要です。そうしないと、`image` 列が削除されてしまいます。`image` 列がなければ、`pixel_values` を作成できません。この動作を防ぐために、`remove_unused_columns=False` を設定してください。もう一つの必須パラメータは、モデルの保存先を指定する `output_dir` です。`push_to_hub=True` を設定することで、このモデルを Hub にプッシュできます（モデルをアップロードするには、Hugging Face にサインインしている必要があります）。各エポックの終了時、[Trainer](/docs/transformers/v5.23.0/ja/main_classes/trainer#transformers.Trainer) は IoU メトリクスを評価し、学習チェックポイントを保存します。
2. モデル、データセット、トークナイザー、データコラテーター、`compute_metrics` 関数とともに、学習引数を [Trainer](/docs/transformers/v5.23.0/ja/main_classes/trainer#transformers.Trainer) に渡します。
3. [train()](/docs/transformers/v5.23.0/ja/main_classes/trainer#transformers.Trainer.train)を呼び出して、モデルをファインチューニングします。

```py
>>> training_args = TrainingArguments(
...     output_dir="segformer-b0-scene-parse-150",
...     learning_rate=6e-5,
...     num_train_epochs=50,
...     per_device_train_batch_size=2,
...     per_device_eval_batch_size=2,
...     save_total_limit=3,
...     eval_strategy="steps",
...     save_strategy="steps",
...     save_steps=20,
...     eval_steps=20,
...     logging_steps=1,
...     report_to="trackio",
...     run_name="scene-parse-150",
...     eval_accumulation_steps=5,
...     remove_unused_columns=False,
...     push_to_hub=True,
... )

>>> trainer = Trainer(
...     model=model,
...     args=training_args,
...     train_dataset=train_ds,
...     eval_dataset=test_ds,
...     compute_metrics=compute_metrics,
... )

>>> trainer.train()
```

トレーニングが完了したら、[push_to_hub()](/docs/transformers/v5.23.0/ja/main_classes/trainer#transformers.Trainer.push_to_hub) メソッドでモデルを Hub に共有し、誰でもそのモデルを利用できるようにしてください。

```py
>>> trainer.push_to_hub()
```

### 推論

素晴らしい、モデルのファインチューニングが完了したので、推論に使用できます！

データセットを再読み込みし、推論用の画像を読み込みます。

```py
>>> from datasets import load_dataset

>>> ds = load_dataset("merve/scene_parse_150", split="train[:50]")
>>> ds = ds.train_test_split(test_size=0.2)
>>> test_ds = ds["test"]
>>> image = ds["test"][0]["image"]
>>> image
```

    

ここでは、パイプラインを使わずに推論を行う方法を確認します。画像プロセッサで画像を処理し、`pixel_values`をGPUに配置します。

```py
>>> from accelerate import Accelerator
>>> device = Accelerator().device
>>> encoding = image_processor(image, return_tensors="pt")
>>> pixel_values = encoding.pixel_values.to(device)
```

入力をモデルに渡し、`logits`を返します:

```py
>>> outputs = model(pixel_values=pixel_values)
>>> logits = outputs.logits.cpu()
```

次に、logits を元の画像サイズに再スケーリングします:

```py
>>> upsampled_logits = nn.functional.interpolate(
...     logits,
...     size=image.size[::-1],
...     mode="bilinear",
...     align_corners=False,
... )

>>> pred_seg = upsampled_logits.argmax(dim=1)[0]
```

結果を可視化するには、[データセットカラーパレット](https://github.com/tensorflow/models/blob/3f1ca33afe3c1631b733ea7e40c294273b9e406d/research/deeplab/utils/get_dataset_colormap.py#L51)を`ade_palette()`として読み込み、各クラスをそのRGB値にマッピングします。

```py
def ade_palette():
  return np.asarray([
      [0, 0, 0],
      [120, 120, 120],
      [180, 120, 120],
      [6, 230, 230],
      [80, 50, 50],
      [4, 200, 3],
      [120, 120, 80],
      [140, 140, 140],
      [204, 5, 255],
      [230, 230, 230],
      [4, 250, 7],
      [224, 5, 255],
      [235, 255, 7],
      [150, 5, 61],
      [120, 120, 70],
      [8, 255, 51],
      [255, 6, 82],
      [143, 255, 140],
      [204, 255, 4],
      [255, 51, 7],
      [204, 70, 3],
      [0, 102, 200],
      [61, 230, 250],
      [255, 6, 51],
      [11, 102, 255],
      [255, 7, 71],
      [255, 9, 224],
      [9, 7, 230],
      [220, 220, 220],
      [255, 9, 92],
      [112, 9, 255],
      [8, 255, 214],
      [7, 255, 224],
      [255, 184, 6],
      [10, 255, 71],
      [255, 41, 10],
      [7, 255, 255],
      [224, 255, 8],
      [102, 8, 255],
      [255, 61, 6],
      [255, 194, 7],
      [255, 122, 8],
      [0, 255, 20],
      [255, 8, 41],
      [255, 5, 153],
      [6, 51, 255],
      [235, 12, 255],
      [160, 150, 20],
      [0, 163, 255],
      [140, 140, 140],
      [250, 10, 15],
      [20, 255, 0],
      [31, 255, 0],
      [255, 31, 0],
      [255, 224, 0],
      [153, 255, 0],
      [0, 0, 255],
      [255, 71, 0],
      [0, 235, 255],
      [0, 173, 255],
      [31, 0, 255],
      [11, 200, 200],
      [255, 82, 0],
      [0, 255, 245],
      [0, 61, 255],
      [0, 255, 112],
      [0, 255, 133],
      [255, 0, 0],
      [255, 163, 0],
      [255, 102, 0],
      [194, 255, 0],
      [0, 143, 255],
      [51, 255, 0],
      [0, 82, 255],
      [0, 255, 41],
      [0, 255, 173],
      [10, 0, 255],
      [173, 255, 0],
      [0, 255, 153],
      [255, 92, 0],
      [255, 0, 255],
      [255, 0, 245],
      [255, 0, 102],
      [255, 173, 0],
      [255, 0, 20],
      [255, 184, 184],
      [0, 31, 255],
      [0, 255, 61],
      [0, 71, 255],
      [255, 0, 204],
      [0, 255, 194],
      [0, 255, 82],
      [0, 10, 255],
      [0, 112, 255],
      [51, 0, 255],
      [0, 194, 255],
      [0, 122, 255],
      [0, 255, 163],
      [255, 153, 0],
      [0, 255, 10],
      [255, 112, 0],
      [143, 255, 0],
      [82, 0, 255],
      [163, 255, 0],
      [255, 235, 0],
      [8, 184, 170],
      [133, 0, 255],
      [0, 255, 92],
      [184, 0, 255],
      [255, 0, 31],
      [0, 184, 255],
      [0, 214, 255],
      [255, 0, 112],
      [92, 255, 0],
      [0, 224, 255],
      [112, 224, 255],
      [70, 184, 160],
      [163, 0, 255],
      [153, 0, 255],
      [71, 255, 0],
      [255, 0, 163],
      [255, 204, 0],
      [255, 0, 143],
      [0, 255, 235],
      [133, 255, 0],
      [255, 0, 235],
      [245, 0, 255],
      [255, 0, 122],
      [255, 245, 0],
      [10, 190, 212],
      [214, 255, 0],
      [0, 204, 255],
      [20, 0, 255],
      [255, 255, 0],
      [0, 153, 255],
      [0, 41, 255],
      [0, 255, 204],
      [41, 0, 255],
      [41, 255, 0],
      [173, 0, 255],
      [0, 245, 255],
      [71, 0, 255],
      [122, 0, 255],
      [0, 255, 184],
      [0, 92, 255],
      [184, 255, 0],
      [0, 133, 255],
      [255, 214, 0],
      [25, 194, 194],
      [102, 255, 0],
      [92, 0, 255],
  ])
```

その後、画像と予測セグメンテーションマップを合成してプロットできます。

```py
>>> import matplotlib.pyplot as plt
>>> import numpy as np

>>> color_seg = np.zeros((pred_seg.shape[0], pred_seg.shape[1], 3), dtype=np.uint8)
>>> palette = np.array(ade_palette())
>>> for label, color in enumerate(palette):
...     color_seg[pred_seg == label, :] = color
>>> color_seg = color_seg[..., ::-1]  # convert to BGR

>>> img = np.array(image) * 0.5 + color_seg * 0.5  # plot the image with the segmentation map
>>> img = img.astype(np.uint8)

>>> plt.figure(figsize=(15, 10))
>>> plt.imshow(img)
>>> plt.show()
```

    

