Datasets 文件

語義分割

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

語義分割

語義分割資料集用於訓練模型對影像中的每個畫素進行分類。這些資料集支援多種應用,例如影像背景移除、影像風格化或自動駕駛的場景理解。本指南將向你展示如何對影像分割資料集應用轉換。

在開始之前,請確保您已安裝最新版本的 albumentationscv2

pip install -U albumentations opencv-python

Albumentations 是一個用於計算機視覺資料增強的 Python 庫。它支援影像分類、目標檢測、分割和關鍵點估計等多種計算機視覺任務。

本指南使用 場景解析 資料集,用於將影像分割並解析為與語義類別(如天空、道路、人物和床)相關的不同影像區域。

載入資料集的 train 分割,並檢視一個示例

>>> from datasets import load_dataset

>>> dataset = load_dataset("scene_parse_150", split="train")
>>> index = 10
>>> dataset[index]
{'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=683x512 at 0x7FB37B0EC810>,
 'annotation': <PIL.PngImagePlugin.PngImageFile image mode=L size=683x512 at 0x7FB37B0EC9D0>,
 'scene_category': 927}

資料集有三個欄位

  • image: 一個 PIL 影像物件。
  • annotation: 影像的分割掩碼。
  • scene_category: 影像的標籤或場景類別(例如“廚房”或“辦公室”)。

接下來,檢視一張圖片

>>> dataset[index]["image"]

類似地,你可以檢視相應的分割掩碼

>>> dataset[index]["annotation"]

我們還可以在分割掩碼上新增一個調色盤,並將其疊加到原始影像上以視覺化資料集

定義調色盤後,您應該就可以視覺化一些疊加效果了。

>>> import matplotlib.pyplot as plt

>>> def visualize_seg_mask(image: np.ndarray, mask: np.ndarray):
...    color_seg = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.uint8)
...    palette = np.array(create_ade20k_label_colormap())
...    for label, color in enumerate(palette):
...        color_seg[mask == 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.axis("off")
...    plt.show()


>>> visualize_seg_mask(
...     np.array(dataset[index]["image"]),
...     np.array(dataset[index]["annotation"])
... )

現在使用 albumentations 應用一些增強。你將首先調整影像大小並調整其亮度。

>>> import albumentations

>>> transform = albumentations.Compose(
...     [
...         albumentations.Resize(256, 256),
...         albumentations.RandomBrightnessContrast(brightness_limit=0.3, contrast_limit=0.3, p=0.5),
...     ]
... )

建立一個函式來對影像應用轉換

>>> def transforms(examples):
...     transformed_images, transformed_masks = [], []
...
...     for image, seg_mask in zip(examples["image"], examples["annotation"]):
...         image, seg_mask = np.array(image), np.array(seg_mask)
...         transformed = transform(image=image, mask=seg_mask)
...         transformed_images.append(transformed["image"])
...         transformed_masks.append(transformed["mask"])
...
...     examples["pixel_values"] = transformed_images
...     examples["label"] = transformed_masks
...     return examples

使用 set_transform() 函式即時將轉換應用於資料集的批次,以減少磁碟空間佔用

>>> dataset.set_transform(transforms)

你可以透過索引示例的 pixel_valueslabel 來驗證轉換是否生效

>>> image = np.array(dataset[index]["pixel_values"])
>>> mask = np.array(dataset[index]["label"])

>>> visualize_seg_mask(image, mask)

在本指南中,你使用了 albumentations 來增強資料集。也可以使用 torchvision 來應用一些類似的轉換。

>>> from torchvision.transforms import Resize, ColorJitter, Compose

>>> transformation_chain = Compose([
...     Resize((256, 256)),
...     ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
... ])
>>> resize = Resize((256, 256))

>>> def train_transforms(example_batch):
...     example_batch["pixel_values"] = [transformation_chain(x) for x in example_batch["image"]]
...     example_batch["label"] = [resize(x) for x in example_batch["annotation"]]
...     return example_batch

>>> dataset.set_transform(train_transforms)

>>> image = np.array(dataset[index]["pixel_values"])
>>> mask = np.array(dataset[index]["label"])

>>> visualize_seg_mask(image, mask)

現在你已經瞭解瞭如何處理用於語義分割的資料集,接下來學習如何訓練語義分割模型並將其用於推理。

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.