语义分割和数据集

:label:sec_semantic_segmentation

在 :numref:sec_bbox— :numref:sec_rcnn中讨论的目标检测问题中,我们一直使用方形边界框来标注和预测图像中的目标。 本节将探讨语义分割(semantic segmentation)问题,它重点关注于如何将图像分割成属于不同语义类别的区域。 与目标检测不同,语义分割可以识别并理解图像中每一个像素的内容:其语义区域的标注和预测是像素级的。 :numref:fig_segmentation展示了语义分割中图像有关狗、猫和背景的标签。 与目标检测相比,语义分割标注的像素级的边框显然更加精细。

语义分割中图像有关狗、猫和背景的标签 :label:fig_segmentation

图像分割和实例分割

计算机视觉领域还有2个与语义分割相似的重要问题,即图像分割(image segmentation)和实例分割(instance segmentation)。 我们在这里将它们同语义分割简单区分一下。

  • 图像分割将图像划分为若干组成区域,这类问题的方法通常利用图像中像素之间的相关性。它在训练时不需要有关图像像素的标签信息,在预测时也无法保证分割出的区域具有我们希望得到的语义。以 :numref:fig_segmentation中的图像作为输入,图像分割可能会将狗分为两个区域:一个覆盖以黑色为主的嘴和眼睛,另一个覆盖以黄色为主的其余部分身体。
  • 实例分割也叫同时检测并分割(simultaneous detection and segmentation),它研究如何识别图像中各个目标实例的像素级区域。与语义分割不同,实例分割不仅需要区分语义,还要区分不同的目标实例。例如,如果图像中有两条狗,则实例分割需要区分像素属于的两条狗中的哪一条。

Pascal VOC2012 语义分割数据集

[最重要的语义分割数据集之一是Pascal VOC2012] 下面我们深入了解一下这个数据集。

```{.python .input} %matplotlib inline from d2l import mxnet as d2l from mxnet import gluon, image, np, npx import os

npx.set_np()

  1. ```{.python .input}
  2. #@tab pytorch
  3. %matplotlib inline
  4. from d2l import torch as d2l
  5. import torch
  6. import torchvision
  7. import os

数据集的tar文件大约为2GB,所以下载可能需要一段时间。 提取出的数据集位于../data/VOCdevkit/VOC2012

```{.python .input}

@tab all

@save

d2l.DATA_HUB[‘voc2012’] = (d2l.DATA_URL + ‘VOCtrainval_11-May-2012.tar’, ‘4e443f8a2eca6b1dac8a6c57641b67dd40621a49’)

voc_dir = d2l.download_extract(‘voc2012’, ‘VOCdevkit/VOC2012’)

  1. 进入路径`../data/VOCdevkit/VOC2012`之后,我们可以看到数据集的不同组件。
  2. `ImageSets/Segmentation`路径包含用于训练和测试样本的文本文件,而`JPEGImages``SegmentationClass`路径分别存储着每个示例的输入图像和标签。
  3. 此处的标签也采用图像格式,其尺寸和它所标注的输入图像的尺寸相同。
  4. 此外,标签中颜色相同的像素属于同一个语义类别。
  5. 下面将`read_voc_images`函数定义为[**将所有输入的图像和标签读入内存**]。
  6. ```{.python .input}
  7. #@save
  8. def read_voc_images(voc_dir, is_train=True):
  9. """读取所有VOC图像并标注"""
  10. txt_fname = os.path.join(voc_dir, 'ImageSets', 'Segmentation',
  11. 'train.txt' if is_train else 'val.txt')
  12. with open(txt_fname, 'r') as f:
  13. images = f.read().split()
  14. features, labels = [], []
  15. for i, fname in enumerate(images):
  16. features.append(image.imread(os.path.join(
  17. voc_dir, 'JPEGImages', f'{fname}.jpg')))
  18. labels.append(image.imread(os.path.join(
  19. voc_dir, 'SegmentationClass', f'{fname}.png')))
  20. return features, labels
  21. train_features, train_labels = read_voc_images(voc_dir, True)

```{.python .input}

@tab pytorch

@save

def read_voc_images(voc_dir, is_train=True): “””读取所有VOC图像并标注””” txt_fname = os.path.join(voc_dir, ‘ImageSets’, ‘Segmentation’, ‘train.txt’ if is_train else ‘val.txt’) mode = torchvision.io.image.ImageReadMode.RGB with open(txt_fname, ‘r’) as f: images = f.read().split() features, labels = [], [] for i, fname in enumerate(images): features.append(torchvision.io.read_image(os.path.join( voc_dir, ‘JPEGImages’, f’{fname}.jpg’))) labels.append(torchvision.io.read_image(os.path.join( voc_dir, ‘SegmentationClass’ ,f’{fname}.png’), mode)) return features, labels

train_features, train_labels = read_voc_images(voc_dir, True)

  1. 下面我们[**绘制前5个输入图像及其标签**]。
  2. 在标签图像中,白色和黑色分别表示边框和背景,而其他颜色则对应不同的类别。
  3. ```{.python .input}
  4. n = 5
  5. imgs = train_features[0:n] + train_labels[0:n]
  6. d2l.show_images(imgs, 2, n);

```{.python .input}

@tab pytorch

n = 5 imgs = train_features[0:n] + train_labels[0:n] imgs = [img.permute(1,2,0) for img in imgs] d2l.show_images(imgs, 2, n);

  1. 接下来,我们[**列举RGB颜色值和类名**]。
  2. ```{.python .input}
  3. #@tab all
  4. #@save
  5. VOC_COLORMAP = [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0],
  6. [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128],
  7. [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0],
  8. [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128],
  9. [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0],
  10. [0, 64, 128]]
  11. #@save
  12. VOC_CLASSES = ['background', 'aeroplane', 'bicycle', 'bird', 'boat',
  13. 'bottle', 'bus', 'car', 'cat', 'chair', 'cow',
  14. 'diningtable', 'dog', 'horse', 'motorbike', 'person',
  15. 'potted plant', 'sheep', 'sofa', 'train', 'tv/monitor']

通过上面定义的两个常量,我们可以方便地[查找标签中每个像素的类索引]。 我们定义了voc_colormap2label函数来构建从上述RGB颜色值到类别索引的映射,而voc_label_indices函数将RGB值映射到在Pascal VOC2012数据集中的类别索引。

```{.python .input}

@save

def voc_colormap2label(): “””构建从RGB到VOC类别索引的映射””” colormap2label = np.zeros(256 * 3) for i, colormap in enumerate(VOC_COLORMAP): colormap2label[ (colormap[0] 256 + colormap[1]) * 256 + colormap[2]] = i return colormap2label

@save

def voc_label_indices(colormap, colormap2label): “””将VOC标签中的RGB值映射到它们的类别索引””” colormap = colormap.astype(np.int32) idx = ((colormap[:, :, 0] 256 + colormap[:, :, 1]) 256

  1. + colormap[:, :, 2])
  2. return colormap2label[idx]
  1. ```{.python .input}
  2. #@tab pytorch
  3. #@save
  4. def voc_colormap2label():
  5. """构建从RGB到VOC类别索引的映射"""
  6. colormap2label = torch.zeros(256 ** 3, dtype=torch.long)
  7. for i, colormap in enumerate(VOC_COLORMAP):
  8. colormap2label[
  9. (colormap[0] * 256 + colormap[1]) * 256 + colormap[2]] = i
  10. return colormap2label
  11. #@save
  12. def voc_label_indices(colormap, colormap2label):
  13. """将VOC标签中的RGB值映射到它们的类别索引"""
  14. colormap = colormap.permute(1, 2, 0).numpy().astype('int32')
  15. idx = ((colormap[:, :, 0] * 256 + colormap[:, :, 1]) * 256
  16. + colormap[:, :, 2])
  17. return colormap2label[idx]

[例如],在第一张样本图像中,飞机头部区域的类别索引为1,而背景索引为0。

```{.python .input}

@tab all

y = voc_label_indices(train_labels[0], voc_colormap2label()) y[105:115, 130:140], VOC_CLASSES[1]

  1. ### 预处理数据
  2. 在之前的实验,例如 :numref:`sec_alexnet` :numref:`sec_googlenet`中,我们通过再缩放图像使其符合模型的输入形状。
  3. 然而在语义分割中,这样做需要将预测的像素类别重新映射回原始尺寸的输入图像。
  4. 这样的映射可能不够精确,尤其在不同语义的分割区域。
  5. 为了避免这个问题,我们将图像裁剪为固定尺寸,而不是再缩放。
  6. 具体来说,我们[**使用图像增广中的随机裁剪,裁剪输入图像和标签的相同区域**]。
  7. ```{.python .input}
  8. #@save
  9. def voc_rand_crop(feature, label, height, width):
  10. """随机裁剪特征和标签图像"""
  11. feature, rect = image.random_crop(feature, (width, height))
  12. label = image.fixed_crop(label, *rect)
  13. return feature, label

```{.python .input}

@tab pytorch

@save

def voc_rand_crop(feature, label, height, width): “””随机裁剪特征和标签图像””” rect = torchvision.transforms.RandomCrop.get_params( feature, (height, width)) feature = torchvision.transforms.functional.crop(feature, rect) label = torchvision.transforms.functional.crop(label, rect) return feature, label

  1. ```{.python .input}
  2. imgs = []
  3. for _ in range(n):
  4. imgs += voc_rand_crop(train_features[0], train_labels[0], 200, 300)
  5. d2l.show_images(imgs[::2] + imgs[1::2], 2, n);

```{.python .input}

@tab pytorch

imgs = [] for _ in range(n): imgs += voc_rand_crop(train_features[0], train_labels[0], 200, 300)

imgs = [img.permute(1, 2, 0) for img in imgs] d2l.show_images(imgs[::2] + imgs[1::2], 2, n);

  1. ### [**自定义语义分割数据集类**]
  2. 我们通过继承高级API提供的`Dataset`类,自定义了一个语义分割数据集类`VOCSegDataset`
  3. 通过实现`__getitem__`函数,我们可以任意访问数据集中索引为`idx`的输入图像及其每个像素的类别索引。
  4. 由于数据集中有些图像的尺寸可能小于随机裁剪所指定的输出尺寸,这些样本可以通过自定义的`filter`函数移除掉。
  5. 此外,我们还定义了`normalize_image`函数,从而对输入图像的RGB三个通道的值分别做标准化。
  6. ```{.python .input}
  7. #@save
  8. class VOCSegDataset(gluon.data.Dataset):
  9. """一个用于加载VOC数据集的自定义数据集"""
  10. def __init__(self, is_train, crop_size, voc_dir):
  11. self.rgb_mean = np.array([0.485, 0.456, 0.406])
  12. self.rgb_std = np.array([0.229, 0.224, 0.225])
  13. self.crop_size = crop_size
  14. features, labels = read_voc_images(voc_dir, is_train=is_train)
  15. self.features = [self.normalize_image(feature)
  16. for feature in self.filter(features)]
  17. self.labels = self.filter(labels)
  18. self.colormap2label = voc_colormap2label()
  19. print('read ' + str(len(self.features)) + ' examples')
  20. def normalize_image(self, img):
  21. return (img.astype('float32') / 255 - self.rgb_mean) / self.rgb_std
  22. def filter(self, imgs):
  23. return [img for img in imgs if (
  24. img.shape[0] >= self.crop_size[0] and
  25. img.shape[1] >= self.crop_size[1])]
  26. def __getitem__(self, idx):
  27. feature, label = voc_rand_crop(self.features[idx], self.labels[idx],
  28. *self.crop_size)
  29. return (feature.transpose(2, 0, 1),
  30. voc_label_indices(label, self.colormap2label))
  31. def __len__(self):
  32. return len(self.features)

```{.python .input}

@tab pytorch

@save

class VOCSegDataset(torch.utils.data.Dataset): “””一个用于加载VOC数据集的自定义数据集”””

  1. def __init__(self, is_train, crop_size, voc_dir):
  2. self.transform = torchvision.transforms.Normalize(
  3. mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
  4. self.crop_size = crop_size
  5. features, labels = read_voc_images(voc_dir, is_train=is_train)
  6. self.features = [self.normalize_image(feature)
  7. for feature in self.filter(features)]
  8. self.labels = self.filter(labels)
  9. self.colormap2label = voc_colormap2label()
  10. print('read ' + str(len(self.features)) + ' examples')
  11. def normalize_image(self, img):
  12. return self.transform(img.float() / 255)
  13. def filter(self, imgs):
  14. return [img for img in imgs if (
  15. img.shape[1] >= self.crop_size[0] and
  16. img.shape[2] >= self.crop_size[1])]
  17. def __getitem__(self, idx):
  18. feature, label = voc_rand_crop(self.features[idx], self.labels[idx],
  19. *self.crop_size)
  20. return (feature, voc_label_indices(label, self.colormap2label))
  21. def __len__(self):
  22. return len(self.features)
  1. ### [**读取数据集**]
  2. 我们通过自定义的`VOCSegDataset`类来分别创建训练集和测试集的实例。
  3. 假设我们指定随机裁剪的输出图像的形状为$320\times 480$
  4. 下面我们可以查看训练集和测试集所保留的样本个数。
  5. ```{.python .input}
  6. #@tab all
  7. crop_size = (320, 480)
  8. voc_train = VOCSegDataset(True, crop_size, voc_dir)
  9. voc_test = VOCSegDataset(False, crop_size, voc_dir)

设批量大小为64,我们定义训练集的迭代器。 打印第一个小批量的形状会发现:与图像分类或目标检测不同,这里的标签是一个三维数组。

```{.python .input} batch_size = 64 train_iter = gluon.data.DataLoader(voc_train, batch_size, shuffle=True, last_batch=’discard’, num_workers=d2l.get_dataloader_workers()) for X, Y in train_iter: print(X.shape) print(Y.shape) break

  1. ```{.python .input}
  2. #@tab pytorch
  3. batch_size = 64
  4. train_iter = torch.utils.data.DataLoader(voc_train, batch_size, shuffle=True,
  5. drop_last=True,
  6. num_workers=d2l.get_dataloader_workers())
  7. for X, Y in train_iter:
  8. print(X.shape)
  9. print(Y.shape)
  10. break

[整合所有组件]

最后,我们定义以下load_data_voc函数来下载并读取Pascal VOC2012语义分割数据集。 它返回训练集和测试集的数据迭代器。

```{.python .input}

@save

def load_data_voc(batch_size, crop_size): “””加载VOC语义分割数据集””” voc_dir = d2l.download_extract(‘voc2012’, os.path.join( ‘VOCdevkit’, ‘VOC2012’)) num_workers = d2l.get_dataloader_workers() train_iter = gluon.data.DataLoader( VOCSegDataset(True, crop_size, voc_dir), batch_size, shuffle=True, last_batch=’discard’, num_workers=num_workers) test_iter = gluon.data.DataLoader( VOCSegDataset(False, crop_size, voc_dir), batch_size, last_batch=’discard’, num_workers=num_workers) return train_iter, test_iter

  1. ```{.python .input}
  2. #@tab pytorch
  3. #@save
  4. def load_data_voc(batch_size, crop_size):
  5. """加载VOC语义分割数据集"""
  6. voc_dir = d2l.download_extract('voc2012', os.path.join(
  7. 'VOCdevkit', 'VOC2012'))
  8. num_workers = d2l.get_dataloader_workers()
  9. train_iter = torch.utils.data.DataLoader(
  10. VOCSegDataset(True, crop_size, voc_dir), batch_size,
  11. shuffle=True, drop_last=True, num_workers=num_workers)
  12. test_iter = torch.utils.data.DataLoader(
  13. VOCSegDataset(False, crop_size, voc_dir), batch_size,
  14. drop_last=True, num_workers=num_workers)
  15. return train_iter, test_iter

小结

  • 语义分割通过将图像划分为属于不同语义类别的区域,来识别并理解图像中像素级别的内容。
  • 语义分割的一个重要的数据集叫做Pascal VOC2012。
  • 由于语义分割的输入图像和标签在像素上一一对应,输入图像会被随机裁剪为固定尺寸而不是缩放。

练习

  1. 如何在自动驾驶和医疗图像诊断中应用语义分割?还能想到其他领域的应用吗?
  2. 回想一下 :numref:sec_image_augmentation中对数据增强的描述。图像分类中使用的哪种图像增强方法是难以用于语义分割的?

:begin_tab:mxnet Discussions :end_tab:

:begin_tab:pytorch Discussions :end_tab: