李沐动手学深度学习V2-语义分割和Pascal VOC2012数据集加载代码实现

一. 语义分割和数据集

1. 介绍

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

2. 图像分割和实例分割

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

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

3. 语义分割数据集 Pascal VOC2012

3.1 语义分割数据集最重要的之一是Pascal VOC2012,数据集的tar文件大约为2GB。提取出的数据集位于. ./data/VOCdevkit/VOC2012

import torch
import torchvision
import d2l.torch
import os
d2l.torch.DATA_HUB['voc2012'] = (d2l.torch.DATA_URL + 'VOCtrainval_11-May-2012.tar',
                           '4e443f8a2eca6b1dac8a6c57641b67dd40621a49')
voc_dir = d2l.torch.download_extract('voc2012', 'VOCdevkit/VOC2012')
print('voc_dir = ',voc_dir)

3.2 进入路径. ./data/VOCdevkit/VOC2012之后,可以看到数据集的不同组件。 ImageSets/Segmentation路径包含用于训练和测试样本的文本文件,而JPEGImages和SegmentationClass路径分别存储着每个示例的输入图像和标签,此处的标签也采用图像格式,其尺寸和它所标注的输入图像的尺寸相同。 此外,标签中颜色相同的像素属于同一个语义类别。 下面将read_voc_images()函数定义为将所有输入的图像和标签读入内存。

 """读取所有VOC图像并标注"""
def read_voc_images(voc_dir,is_train=True):
    fpath = os.path.join(voc_dir,'ImageSets','Segmentation','train.txt' if is_train else 'val.txt')
    with open(fpath,'r') as f:
        images_name = f.read().split()
    print('images_name.len = ',len(images_name))
    mode = torchvision.io.image.ImageReadMode.RGB
    images_feature,images_label = [],[]
    for image_name in images_name:
        image_path = os.path.join(voc_dir,'JPEGImages',f'{image_name}.jpg')
        label_path = os.path.join(voc_dir,'SegmentationClass',f'{image_name}.png')
        images_feature.append(torchvision.io.read_image(image_path))
        images_label.append(torchvision.io.read_image(label_path,mode))
    return images_feature,images_label
train_images,train_labels = read_voc_images(voc_dir,True)
len(train_images),len(train_labels)

3.3 绘制前5个输入图像及其标签,在标签图像中,白色和黑色分别表示边框和背景,而其他颜色则对应不同的类别,结果如下图所示。

n = 5
imgs = train_images[0:n]+train_labels[0:n]
imgs = [image.permute(1,2,0) for image in imgs]
d2l.torch.show_images(imgs,2,n)

图像和标签
3.4 列举RGB颜色值和类名

VOC_COLORMAP = [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0],
                [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128],
                [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0],
                [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128],
                [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0],
                [0, 64, 128]]

VOC_CLASSES = ['background', 'aeroplane', 'bicycle', 'bird', 'boat',
               'bottle', 'bus', 'car', 'cat', 'chair', 'cow',
               'diningtable', 'dog', 'horse', 'motorbike', 'person',
               'potted plant', 'sheep', 'sofa', 'train', 'tv/monitor']

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

'''构建从RGB到VOC类别索引的映射'''
def voc_colormap2label():
    colormaplabel = torch.zeros(256**3,dtype=torch.long)
    for i,colormap in enumerate(VOC_COLORMAP):
        idx = (colormap[0]*256+colormap[1])*256+colormap[2]
        colormaplabel[idx] = i
    return colormaplabel
"""将VOC标签中的RGB值映射到它们对应的类别索引"""
def voc_label_indices(label,colormaplabel):
    label = label.permute(1,2,0).numpy().astype('int32')
    idxs = [(label[:,:,0]*256+label[:,:,1])*256+label[:,:,2]]
    return colormaplabel[idxs]

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

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

VOC中RGB值进行类别转换

4. 预处理数据

**以前网络对图片预处理是通过缩放图像使其符合模型的输入形状,然而在语义分割中,这样做需要将预测的像素类别重新映射回原始尺寸的输入图像。 这样的映射可能不够精确,尤其在不同语义的分割区域。 为了避免这个问题,需要将图像裁剪为固定尺寸,而不是缩放。 具体来说,使用图像增广中的随机裁剪,裁剪输入图像和标签的相同区域,**输出结果如下图所示。

"""随机裁剪特征和标签图像"""
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

imgs = []
for _ in range(n):
    imgs += voc_rand_crop(train_images[0],train_labels[0],200,300)
imgs = [img.permute(1,2,0) for img in imgs]
d2l.torch.show_images(imgs[::2]+imgs[1::2],2,n)

裁剪结果

5. 自定义语义分割数据集类

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

"""一个用于加载VOC数据集的自定义数据集"""
class VOCSegDataset(torch.utils.data.Dataset):
    def __init__(self,is_train,crop_size,voc_dir):
        self.transform = torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
        self.crop_size = crop_size
        features,labels = read_voc_images(voc_dir,is_train)
        self.features = [self.transform_normalize(feature) for feature in self.filter(features)]
        self.labels = self.filter(labels)
        self.colormap2label = voc_colormap2label()
        print('dataset.len =',len(self.features))
    def filter(self,images):
        images = [image for image in images if (image.shape[1]>=self.crop_size[0] and image.shape[2]>=self.crop_size[1])]
        return images
    def transform_normalize(self,image):
        return self.transform(image.float()/255)
    def __getitem__(self, item):
        feature,label = voc_rand_crop(self.features[item],self.labels[item],*self.crop_size)
        return (feature,voc_label_indices(label,self.colormap2label))
    def __len__(self):
        return len(self.features)

6. 读取数据集

通过自定义的VOCSegDataset类来分别创建训练集和测试集的实例, 假设指定随机裁剪的输出图像的形状为 320×480 ,下面可以查看训练集和测试集所保留的样本个数。

crop_size = (320,480)
voc_train = VOCSegDataset(is_train=True,crop_size=crop_size,voc_dir=voc_dir)
voc_val = VOCSegDataset(is_train=False,crop_size=crop_size,voc_dir=voc_dir)
'''
输出结果如下:
images_name.len =  1464
dataset.len = 1114
images_name.len =  1449
dataset.len = 1078
'''

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

batch_size = 64
train_iter = torch.utils.data.DataLoader(voc_train,batch_size,shuffle=True,drop_last=True,num_workers = d2l.torch.get_dataloader_workers())
for X,Y in train_iter:
    print(X.shape)
    print(Y.shape)
    break
'''
输出结果如下:
torch.Size([64, 3, 320, 480])
torch.Size([64, 320, 480])
'''

7. 整合所有组件

定义load_data_voc()函数来下载并读取Pascal VOC2012语义分割数据集,并且返回训练集和测试集的数据迭代器。

def load_data_voc(crop_size,batch_size):
    """加载VOC语义分割数据集"""
    voc_dir = d2l.torch.download_extract('voc2012', os.path.join(
        'VOCdevkit', 'VOC2012'))
    num_workers = d2l.torch.get_dataloader_workers()
    voc_train = VOCSegDataset(is_train=True,crop_size=crop_size,voc_dir=voc_dir)
    voc_val = VOCSegDataset(is_train=False,crop_size=crop_size,voc_dir=voc_dir)
    train_iter = torch.utils.data.DataLoader(voc_train,batch_size,shuffle=True,drop_last=True,num_workers=num_workers)
    val_iter = torch.utils.data.DataLoader(voc_val,batch_size,shuffle=False,drop_last=True,num_workers=num_workers)
    return (train_iter,val_iter)

8. 小结

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

9.全部代码

import torch
import torchvision
import d2l.torch
import os

d2l.torch.DATA_HUB['voc2012'] = (d2l.torch.DATA_URL + 'VOCtrainval_11-May-2012.tar',
                                 '4e443f8a2eca6b1dac8a6c57641b67dd40621a49')
voc_dir = d2l.torch.download_extract('voc2012', 'VOCdevkit/VOC2012')
print('voc_dir = ', voc_dir)

"""读取所有VOC图像并标注"""
def read_voc_images(voc_dir, is_train=True):
    fpath = os.path.join(voc_dir, 'ImageSets', 'Segmentation', 'train.txt' if is_train else 'val.txt')
    with open(fpath, 'r') as f:
        images_name = f.read().split()
    print('images_name.len = ', len(images_name))
    mode = torchvision.io.image.ImageReadMode.RGB
    images_feature, images_label = [], []
    for image_name in images_name:
        image_path = os.path.join(voc_dir, 'JPEGImages', f'{image_name}.jpg')
        label_path = os.path.join(voc_dir, 'SegmentationClass', f'{image_name}.png')
        images_feature.append(torchvision.io.read_image(image_path))
        images_label.append(torchvision.io.read_image(label_path, mode))
    return images_feature, images_label


train_images, train_labels = read_voc_images(voc_dir, True)
len(train_images), len(train_labels)
n = 5
imgs = train_images[0:n] + train_labels[0:n]
imgs = [image.permute(1, 2, 0) for image in imgs]
d2l.torch.show_images(imgs, 2, n)
VOC_COLORMAP = [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0],
                [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128],
                [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0],
                [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128],
                [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0],
                [0, 64, 128]]

VOC_CLASSES = ['background', 'aeroplane', 'bicycle', 'bird', 'boat',
               'bottle', 'bus', 'car', 'cat', 'chair', 'cow',
               'diningtable', 'dog', 'horse', 'motorbike', 'person',
               'potted plant', 'sheep', 'sofa', 'train', 'tv/monitor']
               
'''构建从RGB到VOC类别索引的映射'''
def voc_colormap2label():
    colormaplabel = torch.zeros(256 ** 3, dtype=torch.long)
    for i, colormap in enumerate(VOC_COLORMAP):
        idx = (colormap[0] * 256 + colormap[1]) * 256 + colormap[2]
        colormaplabel[idx] = i
    return colormaplabel


"""将VOC标签中的RGB值映射到它们对应的类别索引"""
def voc_label_indices(label, colormaplabel):
    label = label.permute(1, 2, 0).numpy().astype('int32')
    idxs = [(label[:, :, 0] * 256 + label[:, :, 1]) * 256 + label[:, :, 2]]
    return colormaplabel[idxs]


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

"""随机裁剪特征和标签图像"""
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


imgs = []
for _ in range(n):
    imgs += voc_rand_crop(train_images[0], train_labels[0], 200, 300)
imgs = [img.permute(1, 2, 0) for img in imgs]
d2l.torch.show_images(imgs[::2] + imgs[1::2], 2, n)

"""一个用于加载VOC数据集的自定义数据集"""
class VOCSegDataset(torch.utils.data.Dataset):
    def __init__(self, is_train, crop_size, voc_dir):
        self.transform = torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
        self.crop_size = crop_size
        features, labels = read_voc_images(voc_dir, is_train)
        self.features = [self.transform_normalize(feature) for feature in self.filter(features)]
        self.labels = self.filter(labels)
        self.colormap2label = voc_colormap2label()
        print('dataset.len =', len(self.features))

    def filter(self, images):
        images = [image for image in images if
                  (image.shape[1] >= self.crop_size[0] and image.shape[2] >= self.crop_size[1])]
        return images

    def transform_normalize(self, image):
        return self.transform(image.float() / 255)

    def __getitem__(self, item):
        feature, label = voc_rand_crop(self.features[item], self.labels[item], *self.crop_size)
        return (feature, voc_label_indices(label, self.colormap2label))

    def __len__(self):
        return len(self.features)


crop_size = (320, 480)
voc_train = VOCSegDataset(is_train=True, crop_size=crop_size, voc_dir=voc_dir)
voc_val = VOCSegDataset(is_train=False, crop_size=crop_size, voc_dir=voc_dir)
batch_size = 64
train_iter = torch.utils.data.DataLoader(voc_train, batch_size, shuffle=True, drop_last=True,
                                         num_workers=d2l.torch.get_dataloader_workers())
for X, Y in train_iter:
    print(X.shape)
    print(Y.shape)
    break


def load_data_voc(crop_size, batch_size):
    """加载VOC语义分割数据集"""
    voc_dir = d2l.torch.download_extract('voc2012', os.path.join(
        'VOCdevkit', 'VOC2012'))
    num_workers = d2l.torch.get_dataloader_workers()
    voc_train = VOCSegDataset(is_train=True, crop_size=crop_size, voc_dir=voc_dir)
    voc_val = VOCSegDataset(is_train=False, crop_size=crop_size, voc_dir=voc_dir)
    train_iter = torch.utils.data.DataLoader(voc_train, batch_size, shuffle=True, drop_last=True,
                                             num_workers=num_workers)
    val_iter = torch.utils.data.DataLoader(voc_val, batch_size, shuffle=False, drop_last=True, num_workers=num_workers)
    return (train_iter, val_iter)

10.链接

语义分割第一篇:李沐动手学深度学习V2-语义分割和Pascal VOC2012数据集加载代码实现
语义分割第二篇:李沐动手学深度学习V2-转置卷积和代码实现
语义分割第三篇:李沐动手学深度学习V2-语义分割全卷积网络FCN和代码实现

猜你喜欢

转载自blog.csdn.net/flyingluohaipeng/article/details/125205718