语义分割和数据集

语义分割和数据集

参考:https://zh.d2l.ai/chapter_computer-vision/semantic-segmentation-and-dataset.html
语义分割可以理解为识别并理解图像重每一个像素的内容
在这里插入图片描述
计算机视觉领域还有2个和语义分割相似的问题,即图像分割和实例分割

图像分割将图像划分为若干组成区域,这类问题的方法通常利用图像中像素之间的相关性。它在训练时不需要有关图像像素的标签信息,在预测时也无法保证分割出的区域具有我们希望得到的语义。以 图13.9.1中的图像作为输入,图像分割可能会将狗分为两个区域:一个覆盖以黑色为主的嘴和眼睛,另一个覆盖以黄色为主的其余部分身体。

实例分割也叫同时检测并分割(simultaneous detection and segmentation),它研究如何识别图像中各个目标实例的像素级区域。与语义分割不同,实例分割不仅需要区分语义,还要区分不同的目标实例。例如,如果图像中有两条狗,则实例分割需要区分像素属于的两条狗中的哪一条。

现在先来介绍一个最重要的语义分割数据集之一Pascal VOC2012
导入相应库

import os
import torch
import torchvision
from d2l import torch as d2l
d2l.DATA_HUB['voc2012'] = (d2l.DATA_URL + 'VOCtrainval_11-May-2012.tar',
                           '4e443f8a2eca6b1dac8a6c57641b67dd40621a49')

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

进入VOC2012后,我们可以看到,ImageSets/Segmentation包含用于训练和测试样本的文本文件,JPEGImages和SegmentationClass路径分别存储着每个示例的输入图像和标签。标签也采用的图像格式,尺寸和输入图像的尺寸一样,此外,标签中颜色相同的像素属于同一个语义类别。定义一个函数读入所有的图像和标签

def read_voc_images(voc_dir, is_train=True):
    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, is_train=True)

然后我们来看看图像和标签

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);
#  在标签图像中,白色和黑色分别表示边框和背景,而其他颜色则对应不同的类别

在这里插入图片描述
之后我们定义一下标签的类别以及其对应的像素点的RGB值

# 列举RGB颜色值和类名
#@save
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]]

#@save
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']

之后,为了方便查找labels中每个像素的类别,先定义一个RGB到类别索引的映射,然后由此定义一个数据集中的由labelsRGB颜色到类别索引的函数

# 这样我们就可以方便查找标签中每个像素的类索引,我们定义了voc_colormap2label函数来构建从上述RGB颜色值到类别索引的映射
# voc_label_indices函数将RGB值映射到VOC2012的类别 索引
def voc_colormap2label():
    # 构建从RGB到VOC类别索引的映射
    colormap2label = torch.zeros(256 ** 3, dtype=torch.long)
    for i, colormap in enumerate(VOC_COLORMAP):
        colormap2label[(colormap[0] * 256 + colormap[1]) * 256 + colormap[2]] = i
    return colormap2label

def voc_label_indices(colormap, colormap2label):
    # 将VOC标签中的RGB值转化为他们的类别索引
    colormap = colormap.permute(1, 2, 0).numpy().astype('int32')
    idx = ((colormap[:, :, 0] * 256 + colormap[:, :, 1]) * 256 + colormap[:, :, 2])
    return colormap2label[idx]
y = voc_label_indices(train_labels[0], voc_colormap2label())
y[105:115, 130:140]

在这里插入图片描述
其中0是背景,1代表飞机索引,至于说边框是白色的索引我没找到,可能画图的时候会将这种边界值变成白色的把

图像预处理,再之前,我们是裁剪完然后再缩放回特定的形状使其符合网络的输出,但语义分割不能这样做,重新映射回原来的尺寸的话,labels可能就不对了,因此我们只能裁剪为特定尺寸,代码如下

# 数据预处理
# 图像增广,随机裁剪图像和标签,裁剪的区域需要一样
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_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) # imgs[::2]步长为2,imgs[1::2]从1开始步长为2

在这里插入图片描述
接着我们自定义一个dataset类,通过getitem函数可以任意访问数据集中索引为idx的输入图像及其每个像素的类别索引,由于数据集中有些图像尺寸可能小于要随机裁剪的图像尺寸,通过filter将其过滤,这样也可以被DataLoader给读取

# 由于数据集中有些图像的尺寸可能小于随机裁剪所指定的输出尺寸,这些样本可以通过自定义的filter函数移除掉
# 通过实现__getitem__函数,我们可以任意访问数据集中索引为idx的输入图像及其每个像素的类别索引
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 = is_train)
        self.features = [self.normalize_image(feature) for feature in self.filter(features)]
        self.labels = self.filter(labels)
        self.colormap2label = voc_colormap2label()
        print('read' + str(len(self.features)) + 'examples')
    
    def normalize_image(self, img):
        return self.transform(img.float() / 255)
    
    def filter(self, imgs):
        return [img for img in imgs if (
                img.shape[1] >= self.crop_size[0] and img.shape[2] >= self.crop_size[1])]
    def __getitem__(self, idx):
        feature, label = voc_rand_crop(self.features[idx], self.labels[idx], *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(True, crop_size, voc_dir)
voc_test = VOCSegDataset(False, crop_size, voc_dir)

查看一下X和Y的形状

batch_size = 64
train_iter = torch.utils.data.DataLoader(voc_train, batch_size, shuffle=True,
                                    drop_last=True,
                                    num_workers=0)
# labels是个三维数组
for X, Y in train_iter:
    print(X.shape)
    print(Y.shape)
    break

在这里插入图片描述

可以看到labels是个三维数据,即batch,w,h,他也是个图像
合并一下所有的组件,之后就可以直接用这个函数读训练集和测试集

# 整合所有组件
def load_data_voc(batch_size, crop_size):
    voc_dir = d2l.download_extract('voc2012', os.path.join(
        'VOCdevkit', 'VOC2012'))
    train_iter = torch.utils.data.DataLoader(VOCSegDataset(True, crop_size, voc_dir), batch_size, shuffle=True,
                                    drop_last=True,
                                    num_workers=0)
    test_iter = torch.utils.data.DataLoader(VOCSegDataset(False, crop_size, voc_dir), batch_size, shuffle=False,
                                    drop_last=True,
                                    num_workers=0)
    return train_iter, test_iter
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值