Skip to content

Commit cd848d2

Browse files
committed
add 9.9
1 parent 2dfc314 commit cd848d2

File tree

8 files changed

+812
-2
lines changed

8 files changed

+812
-2
lines changed

code/chapter09_computer-vision/9.9_semantic-segmentation-and-dataset.ipynb

Lines changed: 425 additions & 0 deletions
Large diffs are not rendered by default.

code/d2lzh_pytorch/utils.py

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1080,6 +1080,82 @@ def load_data_pikachu(batch_size, edge_size=256, data_dir = '../../data/pikachu'
10801080
return train_iter, val_iter
10811081

10821082

1083+
# ################################# 9.9 #########################
1084+
def read_voc_images(root="../../data/VOCdevkit/VOC2012",
1085+
is_train=True, max_num=None):
1086+
txt_fname = '%s/ImageSets/Segmentation/%s' % (
1087+
root, 'train.txt' if is_train else 'val.txt')
1088+
with open(txt_fname, 'r') as f:
1089+
images = f.read().split()
1090+
if max_num is not None:
1091+
images = images[:min(max_num, len(images))]
1092+
features, labels = [None] * len(images), [None] * len(images)
1093+
for i, fname in tqdm(enumerate(images)):
1094+
features[i] = Image.open('%s/JPEGImages/%s.jpg' % (root, fname)).convert("RGB")
1095+
labels[i] = Image.open('%s/SegmentationClass/%s.png' % (root, fname)).convert("RGB")
1096+
return features, labels # PIL image
1097+
1098+
# colormap2label = torch.zeros(256 ** 3, dtype=torch.uint8)
1099+
# for i, colormap in enumerate(VOC_COLORMAP):
1100+
# colormap2label[(colormap[0] * 256 + colormap[1]) * 256 + colormap[2]] = i
1101+
def voc_label_indices(colormap, colormap2label):
1102+
"""
1103+
convert colormap (PIL image) to colormap2label (uint8 tensor).
1104+
"""
1105+
colormap = np.array(colormap.convert("RGB")).astype('int32')
1106+
idx = ((colormap[:, :, 0] * 256 + colormap[:, :, 1]) * 256
1107+
+ colormap[:, :, 2])
1108+
return colormap2label[idx]
1109+
1110+
def voc_rand_crop(feature, label, height, width):
1111+
"""
1112+
Random crop feature (PIL image) and label (PIL image).
1113+
"""
1114+
i, j, h, w = torchvision.transforms.RandomCrop.get_params(
1115+
feature, output_size=(height, width))
1116+
1117+
feature = torchvision.transforms.functional.crop(feature, i, j, h, w)
1118+
label = torchvision.transforms.functional.crop(label, i, j, h, w)
1119+
1120+
return feature, label
1121+
1122+
class VOCSegDataset(torch.utils.data.Dataset):
1123+
def __init__(self, is_train, crop_size, voc_dir, colormap2label, max_num=None):
1124+
"""
1125+
crop_size: (h, w)
1126+
"""
1127+
self.rgb_mean = np.array([0.485, 0.456, 0.406])
1128+
self.rgb_std = np.array([0.229, 0.224, 0.225])
1129+
self.tsf = torchvision.transforms.Compose([
1130+
torchvision.transforms.ToTensor(),
1131+
torchvision.transforms.Normalize(mean=self.rgb_mean,
1132+
std=self.rgb_std)
1133+
])
1134+
1135+
self.crop_size = crop_size # (h, w)
1136+
features, labels = read_voc_images(root=voc_dir,
1137+
is_train=is_train,
1138+
max_num=max_num)
1139+
self.features = self.filter(features) # PIL image
1140+
self.labels = self.filter(labels) # PIL image
1141+
self.colormap2label = colormap2label
1142+
print('read ' + str(len(self.features)) + ' valid examples')
1143+
1144+
def filter(self, imgs):
1145+
return [img for img in imgs if (
1146+
img.size[1] >= self.crop_size[0] and
1147+
img.size[0] >= self.crop_size[1])]
1148+
1149+
def __getitem__(self, idx):
1150+
feature, label = voc_rand_crop(self.features[idx], self.labels[idx],
1151+
*self.crop_size)
1152+
1153+
return (self.tsf(feature),
1154+
voc_label_indices(label, self.colormap2label))
1155+
1156+
def __len__(self):
1157+
return len(self.features)
1158+
10831159

10841160

10851161
# ############################# 10.7 ##########################

docs/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ docsify serve docs
114114
* [9.6 目标检测数据集(皮卡丘)](chapter09_computer-vision/9.6_object-detection-dataset.md)
115115
- [ ] 9.7 单发多框检测(SSD)
116116
* [9.8 区域卷积神经网络(R-CNN)系列](chapter09_computer-vision/9.8_rcnn.md)
117-
- [ ] 9.9 语义分割和数据集
117+
* [9.9 语义分割和数据集](chapter09_computer-vision/9.9_semantic-segmentation-and-dataset.md)
118118
- [ ] 9.10 全卷积网络(FCN)
119119
* [9.11 样式迁移](chapter09_computer-vision/9.11_neural-style.md)
120120
- [ ] 9.12 实战Kaggle比赛:图像分类(CIFAR-10)

docs/_sidebar.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@
7676
* [9.6 目标检测数据集(皮卡丘)](chapter09_computer-vision/9.6_object-detection-dataset.md)
7777
* 9.7 单发多框检测(SSD)
7878
* [9.8 区域卷积神经网络(R-CNN)系列](chapter09_computer-vision/9.8_rcnn.md)
79-
* 9.9 语义分割和数据集
79+
* [9.9 语义分割和数据集](chapter09_computer-vision/9.9_semantic-segmentation-and-dataset.md)
8080
* 9.10 全卷积网络(FCN)
8181
* [9.11 样式迁移](chapter09_computer-vision/9.11_neural-style.md)
8282
* 9.12 实战Kaggle比赛:图像分类(CIFAR-10)
Lines changed: 264 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
1+
# 9.9 语义分割和数据集
2+
3+
在前几节讨论的目标检测问题中,我们一直使用方形边界框来标注和预测图像中的目标。本节将探讨语义分割(semantic segmentation)问题,它关注如何将图像分割成属于不同语义类别的区域。值得一提的是,这些语义区域的标注和预测都是像素级的。图9.10展示了语义分割中图像有关狗、猫和背景的标签。可以看到,与目标检测相比,语义分割标注的像素级的边框显然更加精细。
4+
5+
<div align=center>
6+
<img width="400" src="../img/chapter09/9.9_segmentation.svg"/>
7+
</div>
8+
<div align=center>图9.10 语义分割中图像有关狗、猫和背景的标签</div>
9+
10+
## 9.9.1 图像分割和实例分割
11+
12+
计算机视觉领域还有2个与语义分割相似的重要问题,即图像分割(image segmentation)和实例分割(instance segmentation)。我们在这里将它们与语义分割简单区分一下。
13+
14+
* 图像分割将图像分割成若干组成区域。这类问题的方法通常利用图像中像素之间的相关性。它在训练时不需要有关图像像素的标签信息,在预测时也无法保证分割出的区域具有我们希望得到的语义。以图9.10的图像为输入,图像分割可能将狗分割成两个区域:一个覆盖以黑色为主的嘴巴和眼睛,而另一个覆盖以黄色为主的其余部分身体。
15+
* 实例分割又叫同时检测并分割(simultaneous detection and segmentation)。它研究如何识别图像中各个目标实例的像素级区域。与语义分割有所不同,实例分割不仅需要区分语义,还要区分不同的目标实例。如果图像中有两只狗,实例分割需要区分像素属于这两只狗中的哪一只。
16+
17+
18+
## 9.9.2 Pascal VOC2012语义分割数据集
19+
20+
语义分割的一个重要数据集叫作Pascal VOC2012 [1]。为了更好地了解这个数据集,我们先导入实验所需的包或模块。
21+
22+
``` python
23+
%matplotlib inline
24+
import time
25+
import torch
26+
import torch.nn.functional as F
27+
import torchvision
28+
import numpy as np
29+
from PIL import Image
30+
from tqdm import tqdm
31+
32+
import sys
33+
sys.path.append("..")
34+
import d2lzh_pytorch as d2l
35+
```
36+
37+
我们先下载这个数据集的压缩包([下载地址](http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar))。压缩包大小是2 GB左右,下载需要一定时间。下载后解压得到`VOCdevkit/VOC2012`文件夹,然后将其放置在`data`文件夹下。
38+
39+
``` python
40+
!ls ../../data/VOCdevkit/VOC2012
41+
```
42+
```
43+
Annotations JPEGImages SegmentationObject
44+
ImageSets SegmentationClass
45+
```
46+
47+
进入`../../data/VOCdevkit/VOC2012`路径后,我们可以获取数据集的不同组成部分。其中`ImageSets/Segmentation`路径包含了指定训练和测试样本的文本文件,而`JPEGImages``SegmentationClass`路径下分别包含了样本的输入图像和标签。这里的标签也是图像格式,其尺寸和它所标注的输入图像的尺寸相同。标签中颜色相同的像素属于同一个语义类别。下面定义`read_voc_images`函数将输入图像和标签读进内存。
48+
49+
``` python
50+
# 本函数已保存在d2lzh_pytorch中方便以后使用
51+
def read_voc_images(root="../../data/VOCdevkit/VOC2012",
52+
is_train=True, max_num=None):
53+
txt_fname = '%s/ImageSets/Segmentation/%s' % (
54+
root, 'train.txt' if is_train else 'val.txt')
55+
with open(txt_fname, 'r') as f:
56+
images = f.read().split()
57+
if max_num is not None:
58+
images = images[:min(max_num, len(images))]
59+
features, labels = [None] * len(images), [None] * len(images)
60+
for i, fname in tqdm(enumerate(images)):
61+
features[i] = Image.open('%s/JPEGImages/%s.jpg' % (root, fname)).convert("RGB")
62+
labels[i] = Image.open('%s/SegmentationClass/%s.png' % (root, fname)).convert("RGB")
63+
return features, labels # PIL image
64+
65+
voc_dir = "../../data/VOCdevkit/VOC2012"
66+
train_features, train_labels = read_voc_images(voc_dir, max_num=100)
67+
```
68+
69+
我们画出前5张输入图像和它们的标签。在标签图像中,白色和黑色分别代表边框和背景,而其他不同的颜色则对应不同的类别。
70+
71+
``` python
72+
n = 5
73+
imgs = train_features[0:n] + train_labels[0:n]
74+
d2l.show_images(imgs, 2, n);
75+
```
76+
<div align=center>
77+
<img width="500" src="../img/chapter09/9.9_output1.png"/>
78+
</div>
79+
80+
接下来,我们列出标签中每个RGB颜色的值及其标注的类别。
81+
82+
``` python
83+
# 本函数已保存在d2lzh_pytorch中方便以后使用
84+
VOC_COLORMAP = [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0],
85+
[0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128],
86+
[64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0],
87+
[64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128],
88+
[0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0],
89+
[0, 64, 128]]
90+
# 本函数已保存在d2lzh_pytorch中方便以后使用
91+
VOC_CLASSES = ['background', 'aeroplane', 'bicycle', 'bird', 'boat',
92+
'bottle', 'bus', 'car', 'cat', 'chair', 'cow',
93+
'diningtable', 'dog', 'horse', 'motorbike', 'person',
94+
'potted plant', 'sheep', 'sofa', 'train', 'tv/monitor']
95+
```
96+
97+
有了上面定义的两个常量以后,我们可以很容易地查找标签中每个像素的类别索引。
98+
99+
``` python
100+
colormap2label = torch.zeros(256 ** 3, dtype=torch.uint8)
101+
for i, colormap in enumerate(VOC_COLORMAP):
102+
colormap2label[(colormap[0] * 256 + colormap[1]) * 256 + colormap[2]] = i
103+
104+
# 本函数已保存在d2lzh_pytorch中方便以后使用
105+
def voc_label_indices(colormap, colormap2label):
106+
"""
107+
convert colormap (PIL image) to colormap2label (uint8 tensor).
108+
"""
109+
colormap = np.array(colormap.convert("RGB")).astype('int32')
110+
idx = ((colormap[:, :, 0] * 256 + colormap[:, :, 1]) * 256
111+
+ colormap[:, :, 2])
112+
return colormap2label[idx]
113+
```
114+
115+
例如,第一张样本图像中飞机头部区域的类别索引为1,而背景全是0。
116+
117+
``` python
118+
y = voc_label_indices(train_labels[0], colormap2label)
119+
y[105:115, 130:140], VOC_CLASSES[1]
120+
```
121+
输出:
122+
```
123+
(tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
124+
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
125+
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
126+
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
127+
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
128+
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
129+
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
130+
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
131+
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
132+
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1]], dtype=torch.uint8), 'aeroplane')
133+
```
134+
135+
### 9.9.2.1 预处理数据
136+
137+
在之前的章节中,我们通过缩放图像使其符合模型的输入形状。然而在语义分割里,这样做需要将预测的像素类别重新映射回原始尺寸的输入图像。这样的映射难以做到精确,尤其在不同语义的分割区域。为了避免这个问题,我们将图像裁剪成固定尺寸而不是缩放。具体来说,我们使用图像增广里的随机裁剪,并对输入图像和标签裁剪相同区域。
138+
139+
``` python
140+
# 本函数已保存在d2lzh_pytorch中方便以后使用
141+
def voc_rand_crop(feature, label, height, width):
142+
"""
143+
Random crop feature (PIL image) and label (PIL image).
144+
"""
145+
i, j, h, w = torchvision.transforms.RandomCrop.get_params(
146+
feature, output_size=(height, width))
147+
148+
feature = torchvision.transforms.functional.crop(feature, i, j, h, w)
149+
label = torchvision.transforms.functional.crop(label, i, j, h, w)
150+
151+
return feature, label
152+
153+
imgs = []
154+
for _ in range(n):
155+
imgs += voc_rand_crop(train_features[0], train_labels[0], 200, 300)
156+
d2l.show_images(imgs[::2] + imgs[1::2], 2, n);
157+
```
158+
<div align=center>
159+
<img width="500" src="../img/chapter09/9.9_output2.png"/>
160+
</div>
161+
162+
### 9.9.2.2 自定义语义分割数据集类
163+
164+
我们通过继承PyTorch提供的`Dataset`类自定义了一个语义分割数据集类`VOCSegDataset`。通过实现`__getitem__`函数,我们可以任意访问数据集中索引为`idx`的输入图像及其每个像素的类别索引。由于数据集中有些图像的尺寸可能小于随机裁剪所指定的输出尺寸,这些样本需要通过自定义的`filter`函数所移除。此外,我们还对输入图像的RGB三个通道的值分别做标准化。
165+
166+
``` python
167+
# 本函数已保存在d2lzh_pytorch中方便以后使用
168+
class VOCSegDataset(torch.utils.data.Dataset):
169+
def __init__(self, is_train, crop_size, voc_dir, colormap2label, max_num=None):
170+
"""
171+
crop_size: (h, w)
172+
"""
173+
self.rgb_mean = np.array([0.485, 0.456, 0.406])
174+
self.rgb_std = np.array([0.229, 0.224, 0.225])
175+
self.tsf = torchvision.transforms.Compose([
176+
torchvision.transforms.ToTensor(),
177+
torchvision.transforms.Normalize(mean=self.rgb_mean,
178+
std=self.rgb_std)
179+
])
180+
181+
self.crop_size = crop_size # (h, w)
182+
features, labels = read_voc_images(root=voc_dir,
183+
is_train=is_train,
184+
max_num=max_num)
185+
self.features = self.filter(features) # PIL image
186+
self.labels = self.filter(labels) # PIL image
187+
self.colormap2label = colormap2label
188+
print('read ' + str(len(self.features)) + ' valid examples')
189+
190+
def filter(self, imgs):
191+
return [img for img in imgs if (
192+
img.size[1] >= self.crop_size[0] and
193+
img.size[0] >= self.crop_size[1])]
194+
195+
def __getitem__(self, idx):
196+
feature, label = voc_rand_crop(self.features[idx], self.labels[idx],
197+
*self.crop_size)
198+
199+
return (self.tsf(feature), # float32 tensor
200+
voc_label_indices(label, self.colormap2label)) # uint8 tensor
201+
202+
def __len__(self):
203+
return len(self.features)
204+
```
205+
206+
### 9.9.2.3 读取数据集
207+
208+
我们通过自定义的`VOCSegDataset`类来分别创建训练集和测试集的实例。假设我们指定随机裁剪的输出图像的形状为$320\times 480$。下面我们可以查看训练集和测试集所保留的样本个数。
209+
210+
``` python
211+
crop_size = (320, 480)
212+
max_num = 100
213+
voc_train = VOCSegDataset(True, crop_size, voc_dir, colormap2label, max_num)
214+
voc_test = VOCSegDataset(False, crop_size, voc_dir, colormap2label, max_num)
215+
```
216+
输出:
217+
```
218+
read 75 valid examples
219+
read 77 valid examples
220+
```
221+
222+
设批量大小为64,分别定义训练集和测试集的迭代器。
223+
224+
``` python
225+
batch_size = 64
226+
num_workers = 0 if sys.platform.startswith('win32') else 4
227+
train_iter = torch.utils.data.DataLoader(voc_train, batch_size, shuffle=True,
228+
drop_last=True, num_workers=num_workers)
229+
test_iter = torch.utils.data.DataLoader(voc_test, batch_size, drop_last=True,
230+
num_workers=num_workers)
231+
```
232+
233+
打印第一个小批量的类型和形状。不同于图像分类和目标识别,这里的标签是一个三维数组。
234+
235+
``` python
236+
for X, Y in train_iter:
237+
print(X.dtype, X.shape)
238+
print(y.dtype, Y.shape)
239+
break
240+
```
241+
输出:
242+
```
243+
torch.float32 torch.Size([64, 3, 320, 480])
244+
torch.uint8 torch.Size([64, 320, 480])
245+
```
246+
247+
## 小结
248+
249+
* 语义分割关注如何将图像分割成属于不同语义类别的区域。
250+
* 语义分割的一个重要数据集叫作Pascal VOC2012。
251+
* 由于语义分割的输入图像和标签在像素上一一对应,所以将图像随机裁剪成固定尺寸而不是缩放。
252+
253+
## 练习
254+
255+
* 回忆9.1节(图像增广)中的内容。哪些在图像分类中使用的图像增广方法难以用于语义分割?
256+
257+
## 参考文献
258+
259+
[1] Pascal VOC2012数据集。http://host.robots.ox.ac.uk/pascal/VOC/voc2012/
260+
261+
262+
-----------
263+
> 注:除代码外本节与原书基本相同,[原书传送门](http://zh.d2l.ai/chapter_computer-vision/semantic-segmentation-and-dataset.html)
264+

docs/img/chapter09/9.9_output1.png

283 KB
Loading

docs/img/chapter09/9.9_output2.png

242 KB
Loading

0 commit comments

Comments
 (0)