0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

PyTorch教程-14.9. 语义分割和数据集

jf_pJlTbmA9 来源:PyTorch 作者:PyTorch 2023-06-05 15:44 次阅读

在 第 14.3 节-第 14.8 节讨论对象检测任务时,矩形边界框用于标记和预测图像中的对象。本节将讨论语义分割问题,重点关注如何将图像划分为属于不同语义类的区域。与目标检测不同,语义分割在像素级别识别和理解图像中的内容:它对语义区域的标记和预测是在像素级别。 图 14.9.1显示了语义分割中图像的狗、猫和背景的标签。与目标检测相比,语义分割中标记的像素级边界明显更细粒度。

poYBAGR9O9WAJnnkAAdSBrW48yA985.svg

图 14.9.1语义分割中图像的狗、猫和背景的标签。

14.9.1。图像分割和实例分割

计算机视觉领域还有两个与语义分割类似的重要任务,即图像分割和实例分割。我们将如下简要地将它们与语义分割区分开来。

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

实例分割也称为同时检测和分割。它研究如何识别图像中每个对象实例的像素级区域。与语义分割不同,实例分割不仅需要区分语义,还需要区分不同的对象实例。例如,如果图像中有两只狗,实例分割需要区分一个像素属于这两只狗中的哪一只。

14.9.2。Pascal VOC2012 语义分割数据集

最重要的语义分割数据集之一是Pascal VOC2012。下面,我们将看看这个数据集。

%matplotlib inline
import os
import torch
import torchvision
from d2l import torch as d2l

%matplotlib inline
import os
from mxnet import gluon, image, np, npx
from d2l import mxnet as d2l

npx.set_np()

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

#@save
d2l.DATA_HUB['voc2012'] = (d2l.DATA_URL + 'VOCtrainval_11-May-2012.tar',
              '4e443f8a2eca6b1dac8a6c57641b67dd40621a49')

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

Downloading ../data/VOCtrainval_11-May-2012.tar from http://d2l-data.s3-accelerate.amazonaws.com/VOCtrainval_11-May-2012.tar...

#@save
d2l.DATA_HUB['voc2012'] = (d2l.DATA_URL + 'VOCtrainval_11-May-2012.tar',
              '4e443f8a2eca6b1dac8a6c57641b67dd40621a49')

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

进入路径后../data/VOCdevkit/VOC2012,我们可以看到数据集的不同组成部分。该ImageSets/Segmentation路径包含指定训练和测试样本的文本文件,而 JPEGImages和SegmentationClass路径分别存储每个示例的输入图像和标签。这里的label也是image格式的,和它的labeled input image大小一样。此外,任何标签图像中具有相同颜色的像素属于同一语义类。下面定义了read_voc_images将所有输入图像和标签读入内存的函数。

#@save
def read_voc_images(voc_dir, is_train=True):
  """Read all VOC feature and label images."""
  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)

#@save
def read_voc_images(voc_dir, is_train=True):
  """Read all VOC feature and label images."""
  txt_fname = os.path.join(voc_dir, 'ImageSets', 'Segmentation',
               'train.txt' if is_train else 'val.txt')
  with open(txt_fname, 'r') as f:
    images = f.read().split()
  features, labels = [], []
  for i, fname in enumerate(images):
    features.append(image.imread(os.path.join(
      voc_dir, 'JPEGImages', f'{fname}.jpg')))
    labels.append(image.imread(os.path.join(
      voc_dir, 'SegmentationClass', f'{fname}.png')))
  return features, labels

train_features, train_labels = read_voc_images(voc_dir, True)

我们绘制前五个输入图像及其标签。在标签图像中,白色和黑色分别代表边框和背景,而其他颜色对应不同的类别。

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

poYBAGR4YpiAUiS-AAFQfESlL94544.png

n = 5
imgs = train_features[:n] + train_labels[:n]
d2l.show_images(imgs, 2, n);

poYBAGR4YpiAUiS-AAFQfESlL94544.png

接下来,我们枚举该数据集中所有标签的 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']

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

使用上面定义的两个常量,我们可以方便地找到标签中每个像素的类索引。我们定义了voc_colormap2label 构建从上述 RGB 颜色值到类索引的映射的函数,以及voc_label_indices将任何 RGB 值映射到此 Pascal VOC2012 数据集中它们的类索引的函数。

#@save
def voc_colormap2label():
  """Build the mapping from RGB to class indices for VOC labels."""
  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

#@save
def voc_label_indices(colormap, colormap2label):
  """Map any RGB values in VOC labels to their class indices."""
  colormap = colormap.permute(1, 2, 0).numpy().astype('int32')
  idx = ((colormap[:, :, 0] * 256 + colormap[:, :, 1]) * 256
      + colormap[:, :, 2])
  return colormap2label[idx]

#@save
def voc_colormap2label():
  """Build the mapping from RGB to class indices for VOC labels."""
  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):
  """Map any RGB values in VOC labels to their class indices."""
  colormap = colormap.astype(np.int32)
  idx = ((colormap[:, :, 0] * 256 + colormap[:, :, 1]) * 256
      + colormap[:, :, 2])
  return colormap2label[idx]

例如,在第一个示例图像中,飞机前部的类别索引为 1,而背景索引为 0。

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

(tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
     [0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
     [0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
     [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
     [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
     [0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
     [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
     [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
     [0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
     [0, 0, 0, 0, 0, 0, 0, 0, 1, 1]]),
 'aeroplane')

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

(array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
    [0., 0., 0., 0., 0., 0., 0., 1., 1., 1.],
    [0., 0., 0., 0., 0., 0., 1., 1., 1., 1.],
    [0., 0., 0., 0., 0., 1., 1., 1., 1., 1.],
    [0., 0., 0., 0., 0., 1., 1., 1., 1., 1.],
    [0., 0., 0., 0., 1., 1., 1., 1., 1., 1.],
    [0., 0., 0., 0., 0., 1., 1., 1., 1., 1.],
    [0., 0., 0., 0., 0., 1., 1., 1., 1., 1.],
    [0., 0., 0., 0., 0., 0., 1., 1., 1., 1.],
    [0., 0., 0., 0., 0., 0., 0., 0., 1., 1.]]),
 'aeroplane')

14.9.2.1。数据预处理

在之前的实验中,例如 第 8.1 节-第 8.4 节中,图像被重新缩放以适应模型所需的输入形状。然而,在语义分割中,这样做需要将预测的像素类重新缩放回输入图像的原始形状。这种重新缩放可能不准确,尤其是对于具有不同类别的分段区域。为避免此问题,我们将图像裁剪为固定形状而不是重新缩放。具体来说,使用图像增强的随机裁剪,我们裁剪输入图像和标签的相同区域。

#@save
def voc_rand_crop(feature, label, height, width):
  """Randomly crop both feature and label images."""
  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);

poYBAGR4Yp2ABe2KAAEmElQGy2o580.png

#@save
def voc_rand_crop(feature, label, height, width):
  """Randomly crop both feature and label images."""
  feature, rect = image.random_crop(feature, (width, height))
  label = image.fixed_crop(label, *rect)
  return feature, label

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

poYBAGR4Yp-ADPm6AAFArSWl-RA380.png

14.9.2.2。自定义语义分割数据集类

VOCSegDataset 我们通过继承Dataset高级 API 提供的类来定义自定义语义分割数据集类。通过实现该__getitem__函数,我们可以任意访问数据集中索引的输入图像idx以及该图像中每个像素的类索引。由于数据集中的某些图像的尺寸小于随机裁剪的输出尺寸,因此这些示例被自定义函数过滤掉filter。此外,我们还定义了normalize_image函数来标准化输入图像的三个 RGB 通道的值。

#@save
class VOCSegDataset(torch.utils.data.Dataset):
  """A customized dataset to load the VOC 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)

#@save
class VOCSegDataset(gluon.data.Dataset):
  """A customized dataset to load the VOC dataset."""
  def __init__(self, is_train, crop_size, voc_dir):
    self.rgb_mean = np.array([0.485, 0.456, 0.406])
    self.rgb_std = np.array([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 (img.astype('float32') / 255 - self.rgb_mean) / self.rgb_std

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

  def __getitem__(self, idx):
    feature, label = voc_rand_crop(self.features[idx], self.labels[idx],
                    *self.crop_size)
    return (feature.transpose(2, 0, 1),
        voc_label_indices(label, self.colormap2label))

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

14.9.2.3。读取数据集

我们使用自定义VOCSegDataset 类分别创建训练集和测试集的实例。假设我们指定随机裁剪图像的输出形状是320×480. 下面我们可以查看训练集和测试集中保留的示例数量。

crop_size = (320, 480)
voc_train = VOCSegDataset(True, crop_size, voc_dir)
voc_test = VOCSegDataset(False, crop_size, voc_dir)

read 1114 examples
read 1078 examples

crop_size = (320, 480)
voc_train = VOCSegDataset(True, crop_size, voc_dir)
voc_test = VOCSegDataset(False, crop_size, voc_dir)

read 1114 examples
read 1078 examples

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

batch_size = 64
train_iter = torch.utils.data.DataLoader(voc_train, batch_size, shuffle=True,
                  drop_last=True,
                  num_workers=d2l.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])

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

(64, 3, 320, 480)
(64, 320, 480)

14.9.2.4。把它们放在一起

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

#@save
def load_data_voc(batch_size, crop_size):
  """Load the VOC semantic segmentation dataset."""
  voc_dir = d2l.download_extract('voc2012', os.path.join(
    'VOCdevkit', 'VOC2012'))
  num_workers = d2l.get_dataloader_workers()
  train_iter = torch.utils.data.DataLoader(
    VOCSegDataset(True, crop_size, voc_dir), batch_size,
    shuffle=True, drop_last=True, num_workers=num_workers)
  test_iter = torch.utils.data.DataLoader(
    VOCSegDataset(False, crop_size, voc_dir), batch_size,
    drop_last=True, num_workers=num_workers)
  return train_iter, test_iter

#@save
def load_data_voc(batch_size, crop_size):
  """Load the VOC semantic segmentation dataset."""
  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

14.9.3。概括

语义分割通过将图像划分为属于不同语义类的区域,以像素级别识别和理解图像中的内容。

最重要的语义分割数据集之一是 Pascal VOC2012。

在语义分割中,由于输入图像和标签在像素上一一对应,输入图像被随机裁剪成固定形状而不是重新缩放。

14.9.4。练习

语义分割如何应用于自动驾驶汽车和医学图像诊断?你能想到其他应用吗?

回想一下14.1 节中对数据扩充的描述 。图像分类中使用的哪种图像增强方法不能应用于语义分割?

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 数据集
    +关注

    关注

    4

    文章

    1178

    浏览量

    24352
  • pytorch
    +关注

    关注

    2

    文章

    761

    浏览量

    12835
收藏 人收藏

    评论

    相关推荐

    使用LabVIEW实现基于pytorch的DeepLabv3图像语义分割

    使用LabVIEW实现deeplabV3语义分割
    的头像 发表于 03-22 15:06 1293次阅读
    使用LabVIEW实现基于<b class='flag-5'>pytorch</b>的DeepLabv3图像<b class='flag-5'>语义</b><b class='flag-5'>分割</b>

    使用LabVIEW实现 DeepLabv3+ 语义分割含源码

    使用LabVIEW实现 DeepLabv3+ 语义分割含源码
    的头像 发表于 05-26 10:23 586次阅读
    使用LabVIEW实现 DeepLabv3+ <b class='flag-5'>语义</b><b class='flag-5'>分割</b>含源码

    目标检测和图像语义分割领域性能评价指标

    目标检测和图像语义分割领域的性能评价指标
    发表于 05-13 09:57

    高阶API构建模型和数据使用

    了TensorFlow2.0Beta版本,同pytorch一样支持动态执行(TensorFlow2.0默认eager模式,无需启动会话执行计算图),同时删除了杂乱低阶API,使用高阶API简单地构建复杂神经网络模型,本文主要分享用高阶API构建模型和数据
    发表于 11-04 07:49

    几大主流公开遥感数据

    By 超神经内容提要:利用遥感影像进行土地类别分型,最常用的方法是语义分割。本文继上期土地分类模型训练教程之后,又整理了几大主流公开遥感数据。关键词:遥感
    发表于 08-31 07:01

    语义分割算法系统介绍

    图像语义分割是图像处理和是机器视觉技术中关于图像理解的重要任务。语义分割即是对图像中每一个像素点进行分类,确定每个点的类别,从而进行区域划分,为了能够帮助大家更好的了解
    的头像 发表于 11-05 10:34 4764次阅读

    语义分割速览—全卷积网络FCN

    分割任务论文集与各方实现:[链接]pytorch model zoo:[链接]gluon model zoo:[链接]SOTA Leaderboard:[链接]
    的头像 发表于 12-10 19:24 1379次阅读

    分析总结基于深度神经网络的图像语义分割方法

    语义分割和弱监督学习图像语义分割,对每种方法中代表性算法的效果以及优缺点进行对比与分析,并阐述深度神经网络对语义
    发表于 03-19 14:14 21次下载
    分析总结基于深度神经网络的图像<b class='flag-5'>语义</b><b class='flag-5'>分割</b>方法

    基于深度学习的三维点云语义分割研究分析

    近年来,深度传感器和三维激光扫描仪的普及推动了三维点云处理方法的快速发展。点云语义分割作为理解三维场景的关键步骤,受到了研究者的广泛关注。随着深度学习的迅速发展并广泛应用到三维语义分割
    发表于 04-01 14:48 16次下载
    基于深度学习的三维点云<b class='flag-5'>语义</b><b class='flag-5'>分割</b>研究分析

    语义分割数据集:从理论到实践

    语义分割是计算机视觉领域中的一个重要问题,它的目标是将图像或视频中的语义信息(如人、物、场景等)从背景中分离出来,以便于进行目标检测、识别和分类等任务。语义
    的头像 发表于 04-23 16:45 530次阅读

    语义分割标注:从认知到实践

    随着人工智能技术的不断发展,语义分割标注已经成为计算机视觉领域的一个热门话题。语义分割是指将图像中的每个像素分配给一个预定义的语义类别,以便
    的头像 发表于 04-30 21:20 768次阅读

    PyTorch教程10.5之机器翻译和数据

    电子发烧友网站提供《PyTorch教程10.5之机器翻译和数据集.pdf》资料免费下载
    发表于 06-05 15:14 0次下载
    <b class='flag-5'>PyTorch</b>教程10.5之机器翻译<b class='flag-5'>和数据</b>集

    PyTorch教程14.9语义分割和数据

    电子发烧友网站提供《PyTorch教程14.9语义分割和数据集.pdf》资料免费下载
    发表于 06-05 11:10 0次下载
    <b class='flag-5'>PyTorch</b>教程<b class='flag-5'>14.9</b>之<b class='flag-5'>语义</b><b class='flag-5'>分割</b><b class='flag-5'>和数据</b>集

    PyTorch教程16.1之情绪分析和数据

    电子发烧友网站提供《PyTorch教程16.1之情绪分析和数据集.pdf》资料免费下载
    发表于 06-05 10:54 0次下载
    <b class='flag-5'>PyTorch</b>教程16.1之情绪分析<b class='flag-5'>和数据</b>集

    使用PyTorch加速图像分割

    使用PyTorch加速图像分割
    的头像 发表于 08-31 14:27 493次阅读
    使用<b class='flag-5'>PyTorch</b>加速图像<b class='flag-5'>分割</b>