Transformers documentation

이미지 분할

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

이미지 분할

Image segmentation 모델은 이미지에서 서로 다른 관심 영역에 해당하는 영역을 분리합니다. 이러한 모델은 각 픽셀에 라벨을 할당하는 방식으로 작동합니다. 분할에는 semantic segmentation, instance segmentation, panoptic segmentation 등 여러 유형이 있습니다.

이 가이드에서는 다음을 수행합니다:

  1. 다양한 분할 유형을 살펴보세요.
  2. 의미론적 분할을 위한 끝에서 끝으로(fine-tuning) 예제를 제공합니다.

시작하기 전에 필요한 라이브러리가 모두 설치되어 있는지 확인하세요:

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

모델을 업로드하여 커뮤니티와 공유할 수 있도록 Hugging Face 계정에 로그인하는 것을 권장합니다. 프롬프트가 표시되면 토큰을 입력하여 로그인하세요:

>>> from huggingface_hub import notebook_login

>>> notebook_login()

분할의 유형

시맨틱 세그멘테이션은 이미지 내 모든 픽셀에 라벨 또는 클래스를 할당합니다. 시맨틱 세그멘테이션 모델의 출력을 살펴보겠습니다. 이 모델은 이미지에서 발견하는 모든 객체 인스턴스에 동일한 클래스를 할당합니다. 예를 들어, 모든 고양이는 “cat-1”, “cat-2”가 아닌 “cat”으로 라벨링됩니다. transformers의 이미지 세그멘테이션 파이프라인을 사용하면 시맨틱 세그멘테이션 모델을 빠르게 추론할 수 있습니다. 예시 이미지를 살펴보겠습니다.

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

nvidia/segformer-b1-finetuned-cityscapes-1024-1024를 사용하겠습니다.

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

Segmentation 파이프라인의 출력에는 예측된 각 클래스에 대한 마스크가 포함됩니다.

[{'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>}]

자동차 클래스의 마스크를 살펴보면, 모든 자동차가 동일한 마스크로 분류되는 것을 확인할 수 있습니다.

results[-1]["mask"]
Semantic Segmentation Output

인스턴스 세그멘테이션에서는 모든 픽셀을 분류하는 것이 목표가 아니라, 주어진 이미지에서 모든 객체 인스턴스에 대한 마스크를 예측하는 것입니다. 이는 객체 감지와 매우 유사하게 작동하며, 각 인스턴스에 대해 바운딩 박스가 있는 대신 세그멘테이션 마스크가 있습니다. 이를 위해 facebook/mask2former-swin-large-cityscapes-instance를 사용합니다.

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

아래에서 볼 수 있듯이 여러 자동차가 분류되어 있으며, 자동차와 사람 인스턴스에 속하는 픽셀을 제외한 다른 픽셀에 대한 분류는 없습니다.

[{'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>}]

아래의 자동차 마스크 중 하나를 확인해 보세요.

results[2]["mask"]
Semantic Segmentation Output

Panoptic segmentation은 semantic segmentation과 instance segmentation을 결합하여, 모든 픽셀을 해당 클래스와 그 클래스의 인스턴스로 분류하며, 각 클래스의 인스턴스마다 여러 개의 마스크가 존재합니다. 이를 위해 facebook/mask2former-swin-large-cityscapes-panoptic를 사용할 수 있습니다.

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

아래에서 볼 수 있듯이 클래스가 더 많습니다. 이후 모든 픽셀이 클래스 중 하나로 분류되는 것을 보여드리겠습니다.

[{'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>}]

모든 유형의 분할에 대해 나란히 비교해 보겠습니다.

Segmentation Maps Compared

모든 종류의 세그멘테이션을 살펴본 후, 이제 의미론적 세그멘테이션을 위한 모델 파인튜닝을 자세히 살펴보겠습니다.

의미 분할의 일반적인 실생활 응용 사례로는 보행자 및 중요한 교통 정보를 식별하도록 자율주행차를 학습시키는 것, 의료 영상에서 세포와 이상을 식별하는 것, 위성 영상에서 환경 변화를 모니터링하는 것 등이 있습니다.

분할을 위한 모델 미세 조정

이제 다음을 수행합니다:

  1. SceneParse150 데이터셋에서 SegFormer를 fine-tune합니다.
  2. 파인튜닝된 모델을 추론에 사용하세요.

이 작업과 호환되는 모든 아키텍처와 체크포인트를 확인하려면 task-page를 확인하는 것을 권장합니다.

SceneParse150 데이터셋 로드

🤗 Datasets 라이브러리에서 SceneParse150 데이터셋의 더 작은 부분 집합을 로드하는 것부터 시작해 보세요. 이렇게 하면 전체 데이터셋으로 더 많은 시간을 들여 학습하기 전에 실험을 해보고 모든 것이 정상적으로 작동하는지 확인할 수 있습니다.

>>> from datasets import load_dataset

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

데이터셋의 train 스플릿을 train_test_split 메서드를 사용하여 학습 세트와 테스트 세트로 분리합니다:

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

다음은 예시입니다:

>>> 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 이미지로, 모델의 학습 대상(target)이기도 합니다.
  • scene_category: “kitchen”이나 “office”와 같이 이미지 장면을 설명하는 카테고리 ID입니다. 이 가이드에서는 image와 annotation만 필요하며, 둘 다 PIL 이미지입니다.

나중에 모델을 설정할 때 유용한, 라벨 ID를 라벨 클래스로 매핑하는 사전도 만들어야 합니다. Hub에서 매핑을 다운로드하고 id2label 및 label2id 사전을 생성하세요:

>>> 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 이미지 프로세서를 로드하여 모델에 사용할 이미지와 주석을 준비하는 것입니다. 이 데이터셋과 같은 일부 데이터셋은 배경 클래스로 0 인덱스를 사용합니다. 그러나 배경 클래스는 실제로 150개 클래스에 포함되지 않으므로, 모든 라벨에서 1을 빼기 위해 do_reduce_labels=True를 설정해야 합니다. 0 인덱스는 255로 대체되어 SegFormer의 손실 함수에서 무시됩니다:

>>> from transformers import AutoImageProcessor

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

이미지 데이터셋에 데이터 증강을 적용하여 모델이 과적합에 대해 더 강건하도록 만드는 것이 일반적입니다. 이 가이드에서는 torchvision의 ColorJitter 함수를 사용하여 이미지의 색상 특성을 무작위로 변경하지만, 원하는 이미지 라이브러리를 자유롭게 사용할 수도 있습니다.

>>> from torchvision.transforms import ColorJitter

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

이제 이미지를 모델에 맞게 준비하기 위한 두 가지 전처리 함수를 생성합니다. 이 함수들은 이미지를 pixel_values로, 주석을 labels로 변환합니다. 학습 세트의 경우, 이미지 프로세서에 이미지를 전달하기 전에 jitter가 적용됩니다. 테스트 세트의 경우, 이미지 프로세서가 images를 자르고 정규화하며, 테스트 시 데이터 증강이 적용되지 않으므로 labels만 자릅니다.

>>> 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 함수를 사용하세요. 변환은 실시간으로 적용되어 더 빠르고 디스크 공간을 덜 차지합니다:

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

평가

학습 중에 메트릭을 포함하는 것은 모델 성능을 평가하는 데 도움이 되는 경우가 많습니다. 🤗 Evaluate 라이브러리를 사용하면 평가 방법을 빠르게 로드할 수 있습니다. 이 작업에서는 mean Intersection over Union(IoU) 메트릭을 로드합니다(메트릭을 로드하고 계산하는 방법에 대해 자세히 알아보려면 🤗 Evaluate quick tour를 참고하세요):

>>> import evaluate

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

이후 compute 메트릭을 계산하는 함수를 만듭니다. 예측값은 먼저 logits로 변환한 뒤, labels의 크기에 맞게 reshape해야 compute를 호출할 수 있습니다:

>>> 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를 사용하여 모델을 fine-tuning하는 방법에 대해 잘 모르신다면, 여기의 기본 튜토리얼을 참고하세요!

이제 모델을 학습시킬 준비가 되었습니다! AutoModelForSemanticSegmentation로 SegFormer를 로드하고, 모델에 label id와 label class 간의 매핑을 전달하세요:

>>> from transformers import AutoModelForSemanticSegmentation, TrainingArguments, Trainer

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

이 시점에서 남은 단계는 단 세 가지입니다:

  1. TrainingArguments에서 학습 하이퍼파라미터를 정의합니다. 사용하지 않는 컬럼을 제거하지 않는 것이 중요합니다. 제거하면 image 컬럼이 삭제되기 때문입니다. image 컬럼이 없으면 pixel_values를 생성할 수 없습니다. 이 동작을 방지하려면 remove_unused_columns=False를 설정하세요! 나머지 필수 파라미터는 모델 저장 위치를 지정하는 output_dir입니다. push_to_hub=True를 설정하여 이 모델을 Hub에 업로드할 수 있습니다(모델 업로드를 위해 Hugging Face에 로그인되어 있어야 합니다). 각 에포크가 끝나면 Trainer가 IoU 메트릭을 평가하고 학습 체크포인트를 저장합니다.
  2. 모델, 데이터셋, 토크나이저, 데이터 콜레이터, compute_metrics 함수와 함께 학습 인수를 Trainer에 전달합니다.
  3. 모델을 파인튜닝하려면 train()을 호출하세요.
>>> 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() 메서드를 사용하여 모델을 Hub에 공유하여 누구나 모델을 사용할 수 있도록 하세요:

>>> trainer.push_to_hub()

추론

좋습니다. 이제 모델을 fine-tuning 했으므로 추론에 사용할 수 있습니다!

데이터셋을 다시 로드하고 추론을 위한 이미지를 불러옵니다.

>>> 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
Image of bedroom

이제 파이프라인 없이 추론을 수행하는 방법을 살펴보겠습니다. 이미지 프로세서로 이미지를 처리하고 pixel_values를 GPU에 배치합니다:

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

입력을 모델에 전달하고 logits를 반환합니다:

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

다음으로, logits를 원래 이미지 크기로 다시 스케일링합니다:

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

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

결과를 시각화하려면, 각 클래스를 해당 RGB 값으로 매핑하는 dataset color palette를 ade_palette()로 로드합니다.

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],
  ])

그런 다음 이미지와 예측된 분할 맵을 결합하고 플롯할 수 있습니다:

>>> 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()
Image of bedroom overlaid with segmentation map
Update on GitHub