9.9 语义分割和数据集

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

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

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

    语义分割的一个重要数据集叫作Pascal VOC2012 [1]。为了更好地了解这个数据集,我们先导入实验所需的包或模块。

    我们先下载这个数据集的压缩包(下载地址)。压缩包大小是2 GB左右,下载需要一定时间。下载后解压得到文件夹,然后将其放置在data文件夹下。

    1. !ls ../../data/VOCdevkit/VOC2012
    1. Annotations JPEGImages SegmentationObject
    2. ImageSets SegmentationClass

    进入../../data/VOCdevkit/VOC2012路径后,我们可以获取数据集的不同组成部分。其中ImageSets/Segmentation路径包含了指定训练和测试样本的文本文件,而JPEGImagesSegmentationClass路径下分别包含了样本的输入图像和标签。这里的标签也是图像格式,其尺寸和它所标注的输入图像的尺寸相同。标签中颜色相同的像素属于同一个语义类别。下面定义read_voc_images函数将输入图像和标签读进内存。

    1. # 本函数已保存在d2lzh_pytorch中方便以后使用
    2. def read_voc_images(root="../../data/VOCdevkit/VOC2012",
    3. is_train=True, max_num=None):
    4. txt_fname = '%s/ImageSets/Segmentation/%s' % (
    5. root, 'train.txt' if is_train else 'val.txt')
    6. with open(txt_fname, 'r') as f:
    7. images = f.read().split()
    8. if max_num is not None:
    9. images = images[:min(max_num, len(images))]
    10. features, labels = [None] * len(images), [None] * len(images)
    11. for i, fname in tqdm(enumerate(images)):
    12. features[i] = Image.open('%s/JPEGImages/%s.jpg' % (root, fname)).convert("RGB")
    13. labels[i] = Image.open('%s/SegmentationClass/%s.png' % (root, fname)).convert("RGB")
    14. return features, labels # PIL image
    15. voc_dir = "../../data/VOCdevkit/VOC2012"
    16. train_features, train_labels = read_voc_images(voc_dir, max_num=100)

    我们画出前5张输入图像和它们的标签。在标签图像中,白色和黑色分别代表边框和背景,而其他不同的颜色则对应不同的类别。

    1. n = 5
    2. d2l.show_images(imgs, 2, n);

    接下来,我们列出标签中每个RGB颜色的值及其标注的类别。

    有了上面定义的两个常量以后,我们可以很容易地查找标签中每个像素的类别索引。

    1. colormap2label = torch.zeros(256 ** 3, dtype=torch.uint8)
    2. colormap2label[(colormap[0] * 256 + colormap[1]) * 256 + colormap[2]] = i
    3. # 本函数已保存在d2lzh_pytorch中方便以后使用
    4. def voc_label_indices(colormap, colormap2label):
    5. """
    6. convert colormap (PIL image) to colormap2label (uint8 tensor).
    7. """
    8. colormap = np.array(colormap.convert("RGB")).astype('int32')
    9. idx = ((colormap[:, :, 0] * 256 + colormap[:, :, 1]) * 256
    10. + colormap[:, :, 2])
    11. return colormap2label[idx]

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

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

    输出:

    1. (tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    2. [0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
    3. [0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
    4. [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
    5. [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
    6. [0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
    7. [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
    8. [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
    9. [0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
    10. [0, 0, 0, 0, 0, 0, 0, 0, 1, 1]], dtype=torch.uint8), 'aeroplane')

    在之前的章节中,我们通过缩放图像使其符合模型的输入形状。然而在语义分割里,这样做需要将预测的像素类别重新映射回原始尺寸的输入图像。这样的映射难以做到精确,尤其在不同语义的分割区域。为了避免这个问题,我们将图像裁剪成固定尺寸而不是缩放。具体来说,我们使用图像增广里的随机裁剪,并对输入图像和标签裁剪相同区域。

    1. # 本函数已保存在d2lzh_pytorch中方便以后使用
    2. def voc_rand_crop(feature, label, height, width):
    3. """
    4. Random crop feature (PIL image) and label (PIL image).
    5. """
    6. feature, output_size=(height, width))
    7. feature = torchvision.transforms.functional.crop(feature, i, j, h, w)
    8. label = torchvision.transforms.functional.crop(label, i, j, h, w)
    9. return feature, label
    10. imgs = []
    11. for _ in range(n):
    12. imgs += voc_rand_crop(train_features[0], train_labels[0], 200, 300)
    13. d2l.show_images(imgs[::2] + imgs[1::2], 2, n);

    9.9 语义分割和数据集 - 图3

    我们通过继承PyTorch提供的Dataset类自定义了一个语义分割数据集类VOCSegDataset。通过实现__getitem__函数,我们可以任意访问数据集中索引为idx的输入图像及其每个像素的类别索引。由于数据集中有些图像的尺寸可能小于随机裁剪所指定的输出尺寸,这些样本需要通过自定义的filter函数所移除。此外,我们还对输入图像的RGB三个通道的值分别做标准化。

    。下面我们可以查看训练集和测试集所保留的样本个数。

    1. crop_size = (320, 480)
    2. max_num = 100
    3. voc_train = VOCSegDataset(True, crop_size, voc_dir, colormap2label, max_num)
    4. voc_test = VOCSegDataset(False, crop_size, voc_dir, colormap2label, max_num)

    输出:

    1. read 75 valid examples
    2. read 77 valid examples

    设批量大小为64,分别定义训练集和测试集的迭代器。

    1. batch_size = 64
    2. num_workers = 0 if sys.platform.startswith('win32') else 4
    3. train_iter = torch.utils.data.DataLoader(voc_train, batch_size, shuffle=True,
    4. drop_last=True, num_workers=num_workers)
    5. test_iter = torch.utils.data.DataLoader(voc_test, batch_size, drop_last=True,
    6. num_workers=num_workers)

    打印第一个小批量的类型和形状。不同于图像分类和目标识别,这里的标签是一个三维数组。

    1. for X, Y in train_iter:
    2. print(X.dtype, X.shape)
    3. print(y.dtype, Y.shape)

    输出:

    • 语义分割关注如何将图像分割成属于不同语义类别的区域。
    • 语义分割的一个重要数据集叫作Pascal VOC2012。
    • 由于语义分割的输入图像和标签在像素上一一对应,所以将图像随机裁剪成固定尺寸而不是缩放。
    • 回忆9.1节(图像增广)中的内容。哪些在图像分类中使用的图像增广方法难以用于语义分割?

    [1] Pascal VOC2012数据集。