天天看點

動手學深度學習之語義分割和資料集

語義分割

  • 語義分割将圖檔中的每個像素分類到對應的類别。一般來說通過聚類将比較像的東西放到一起,就是将比較相似的東西放到一起。和一般的分割不同的時候會告訴我們每個像素的label。
    動手學深度學習之語義分割和資料集

應用

  • 背景虛化
    動手學深度學習之語義分割和資料集
  • 路面分割
    動手學深度學習之語義分割和資料集

執行個體分割

  • 語義分割隻關心每個像素是屬于哪一個類,執行個體分割會告訴我們每個像素具體是屬于誰。
    動手學深度學習之語義分割和資料集

語義分割和資料集

最重要的的語義分割資料集之一是PascalVOC2012

%matplotlib inline
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')
           
Downloading ../data/VOCtrainval_11-May-2012.tar from http://d2l-data.s3-accelerate.amazonaws.com/VOCtrainval_11-May-2012.tar...
           
# 将所有輸入的圖像和标簽讀入記憶體
# 對于語義分割的圖檔來來說它的輸入是一張圖檔,它的label也是一張圖檔,label的圖檔每個像素對應的就是一個标号。
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  # 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')))  # 這裡是将圖檔讀取進來,也就是我們訓練使用的features
        labels.append(
            torchvision.io.read_image(
                os.path.join(voc_dir, 'SegmentationClass', f'{fname}.png'),
                mode))  # 這裡是label
    return features, labels

train_features, train_labels = read_voc_images(voc_dir, True)
           
# 繪制前5個輸入圖像及其标簽
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值的對應
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的值我們換算成标号,或者給我們一個标号,然後我們換算成RGB的值
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  # 這裡的意思就是将RGB換算成一個數字
    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])  # 将RGB換成下标
    return colormap2label[idx]
           
# 例子
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')
           
# 使用圖像增廣中的随機裁剪,裁剪輸入圖像和标簽的相同區域
# 這裡的意思就是假設我們的圖檔裁剪了一塊出來,我們将标号也要做相應的裁剪。
def voc_rand_crop(feature, label, height, width):
    """随機裁剪特征和标簽圖像。"""
    rect = torchvision.transforms.RandomCrop.get_params(
        feature, (height, width))  # 做随機的Crop
    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);
           
動手學深度學習之語義分割和資料集
# 自定義語義分割資料集類
class VOCSegDataset(torch.utils.data.Dataset):
    """一個用于加載VOC資料集的自定義資料集。"""
    def __init__(self, is_train, crop_size, voc_dir):  # 是否是訓練集,crop大小,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)  # 将标簽也做一個feature
        self.colormap2label = voc_colormap2label()
        print('read ' + str(len(self.features)) + ' examples')

    def normalize_image(self, img):
        return self.transform(img.float())

    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))  # 每一個傳回第idx個樣本

    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)
           
read 1114 examples
read 1078 examples
           
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
           
# 整合所有元件
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 = 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
           

繼續閱讀