实现一个语义分割项目

VOC2012数据集 包含了11355张图片及其注释,可用于训练语义分割模型。

一、了解数据集

我们可以在ImageSets/Segmentation/train.txt和ImageSets/Segmentation/val.txt中找到我们的训练集和验证集的数据,图片存放在/JPEGImages中,后缀是.jpg,而label存放在/SegmentationClass中,后缀是.png

左边就是真实的图片,右边就是分割之后的结果

二、数据准备

1、读入训练集和验证集

根据train.txt和val.txt中的文件名进行图片读入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import os

#========================================================
# 读入数据集
#========================================================

def read_images(txt_fname):
root = 'D:/00Projects/VOC'
txt_path = root + '/ImageSets/Segmentation/' + txt_fname
with open(txt_path, 'r') as f:
images = f.read().split()
data = [os.path.join(root, 'JPEGImages', i+'.jpg') for i in images]
label = [os.path.join(root, 'SegmentationClass', i+'.png') for i in images]
return data, label

# traindata_list, trainlabel_list = read_images('train.txt')
# valdata_list, vallabel_list = read_images('val.txt')

2、数据处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import os
import numpy as np
import PIL.Image as pil_image
import torch
from torch.utils import data
import torchvision.transforms as transforms
import random

#========================================================
# 数据预处理
#========================================================

def crop(data, label, height, width):
'''
裁剪成相同大小
data和label都是PIL.Image对象
'''
w, h = data.size
x0, y0 = random.randint(0, w - width), random.randint(0, h - height)
return data.crop((x0, y0, x0 + width, y0 + height)), label.crop((x0, y0, x0 + width, y0 + height))

cm2lbl = np.zeros(256**3) # 每个像素点有0-255的选择, RGB三个通道
for i,cm in enumerate(colormap):
cm2lbl[(cm[0]*256+cm[1])*256+cm[2]] = i # 建立索引

def image2label(im):
data = np.array(im, dtype='int32')
idx = (data[:, :, 0] * 256 + data[:, :, 1]) * 256 + data[:, :, 2]
return np.array(cm2lbl[idx], dtype='int64') # 根据索引得到 label 矩阵

def img_transforms(im, label, crop_size):
im, label = crop(im, label, *crop_size)
im_tfs = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])

im = im_tfs(im)
label = image2label(label)
label = torch.from_numpy(label)
return im, label

#========================================================
# 实例化数据集
#========================================================

class VOCSegDataset(data.Dataset):
def __init__(self, txt_fname, crop_size, transforms):
self.crop_size = crop_size
self.transforms = transforms
data_list, label_list = read_images(txt_fname)
self.data_list = self._filter(data_list)
self.label_list = self._filter(label_list)
print('Read ' + str(len(self.data_list)) + ' images')

def _filter(self, images): # 过滤掉图片大小小于crop大小的图片
return [im for im in images if (pil_image.open(im).size[1] >= self.crop_size[0] and
pil_image.open(im).size[0] >= self.crop_size[1])]

def __getitem__(self, idx):
img = self.data_list[idx]
label = self.label_list[idx]
img = pil_image.open(img).convert('RGB')
label = pil_image.open(label).convert('RGB')
img, label = self.transforms(img, label, self.crop_size)
return img, label

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

# 实例化数据集
input_shape = (224, 224)
voc_train = VOCSegDataset('train.txt', input_shape, img_transforms)
voc_val = VOCSegDataset('val.txt', input_shape, img_transforms)

train_loader = torch.utils.data.DataLoader(voc_train, batch_size=BATCH_SIZE, shuffle=True)
val_loader = torch.utils.data.DataLoader(voc_val, batch_size=BATCH_SIZE)

二、模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import numpy as np
import torch
from torch import nn

#========================================================
# 模型结构设计
#========================================================

class conv2DBatchNormRelu(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding, is_batchnorm=True):
super(conv2DBatchNormRelu,self).__init__()
if is_batchnorm:
self.cbr_unit=nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
)
else:
self.cbr_unit=nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=1),
nn.ReLU(inplace=True)
)

def forward(self,inputs):
outputs = self.cbr_unit(inputs)
return outputs

class segnetDown2(nn.Module):
def __init__(self, in_channels, out_channels):
super(segnetDown2, self).__init__()
self.conv1 = conv2DBatchNormRelu(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.conv2 = conv2DBatchNormRelu(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.maxpool_with_argmax = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=True)

def forward(self,inputs):
outputs = self.conv1(inputs)
outputs = self.conv2(outputs)
unpooled_shape = outputs.size()
outputs,indices = self.maxpool_with_argmax(outputs)
return outputs, indices, unpooled_shape

class segnetDown3(nn.Module):
def __init__(self, in_channels, out_channels):
super(segnetDown3,self).__init__()
self.conv1 = conv2DBatchNormRelu(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.conv2 = conv2DBatchNormRelu(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.conv3 = conv2DBatchNormRelu(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.maxpool_with_argmax = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=True)

def forward(self,inputs):
outputs = self.conv1(inputs)
outputs = self.conv2(outputs)
outputs = self.conv3(outputs)
unpooled_shape = outputs.size()
outputs,indices = self.maxpool_with_argmax(outputs)
return outputs, indices, unpooled_shape

class segnetUp2(nn.Module):
def __init__(self, in_channels, out_channels):
super(segnetUp2, self).__init__()
self.unpool = nn.MaxUnpool2d(kernel_size=2, stride=2)
self.conv1 = conv2DBatchNormRelu(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.conv2 = conv2DBatchNormRelu(out_channels, out_channels, kernel_size=3, stride=1, padding=1)

def forward(self, inputs, indices, output_shape):
outputs = self.unpool(inputs, indices=indices, output_size=output_shape)
outputs = self.conv1(outputs)
outputs = self.conv2(outputs)
return outputs

class segnetUp3(nn.Module):
def __init__(self, in_channels, out_channels):
super(segnetUp3, self).__init__()
self.unpool = nn.MaxUnpool2d(kernel_size=2, stride=2)
self.conv1 = conv2DBatchNormRelu(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.conv2 = conv2DBatchNormRelu(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.conv3 = conv2DBatchNormRelu(out_channels, out_channels, kernel_size=3, stride=1, padding=1)

def forward(self, inputs, indices, output_shape):
outputs = self.unpool(inputs, indices=indices, output_size=output_shape)
outputs = self.conv1(outputs)
outputs = self.conv2(outputs)
outputs = self.conv3(outputs)
return outputs

class segnet(nn.Module):
def __init__(self, in_channels=3, num_classes=21):
super(segnet, self).__init__()
self.down1 = segnetDown2(in_channels=in_channels, out_channels=64)
self.down2 = segnetDown2(64, 128)
self.down3 = segnetDown3(128, 256)
self.down4 = segnetDown3(256, 512)
self.down5 = segnetDown3(512, 512)

self.up5 = segnetUp3(512, 512)
self.up4 = segnetUp3(512, 256)
self.up3 = segnetUp3(256, 128)
self.up2 = segnetUp2(128, 64)
self.up1 = segnetUp2(64, 64)
self.finconv = conv2DBatchNormRelu(64, num_classes, kernel_size=3, stride=1, padding=1)

def forward(self,inputs):
down1, indices_1, unpool_shape1 = self.down1(inputs)
down2, indices_2, unpool_shape2 = self.down2(down1)
down3, indices_3, unpool_shape3 = self.down3(down2)
down4, indices_4, unpool_shape4 = self.down4(down3)
down5, indices_5, unpool_shape5 = self.down5(down4)

up5 = self.up5(down5, indices=indices_5, output_shape=unpool_shape5)
up4 = self.up4(up5, indices=indices_4, output_shape=unpool_shape4)
up3 = self.up3(up4, indices=indices_3, output_shape=unpool_shape3)
up2 = self.up2(up3, indices=indices_2, output_shape=unpool_shape2)
up1 = self.up1(up2, indices=indices_1, output_shape=unpool_shape1)
outputs = self.finconv(up1)

return outputs

三、完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import numpy as np
import torch
from torch import nn
from torch.utils import data
import torch.nn.functional as F
import torch.optim as optim
import PIL.Image as pil_image
import os
import torchvision.models as models
import torchvision.transforms as transforms
import random
import matplotlib.pyplot as plt

#========================================================
# 超参数设置
#========================================================

EPOCH = 50 # 遍历数据集次数
BATCH_SIZE = 32 # 批处理尺寸(batch_size)

# 21个类别
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颜色
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]]

#========================================================
# 读入数据集
#========================================================

def read_images(txt_fname):
root = 'D:/00Projects/VOC'
txt_path = root + '/ImageSets/Segmentation/' + txt_fname
with open(txt_path, 'r') as f:
images = f.read().split()
data = [os.path.join(root, 'JPEGImages', i+'.jpg') for i in images]
label = [os.path.join(root, 'SegmentationClass', i+'.png') for i in images]
return data, label

# traindata, trainlabel = read_images('train.txt')
# valdata, vallabel = read_images('D:/VOC', 'val.txt')

#========================================================
# 数据预处理
#========================================================

def crop(data, label, height, width):
'''
裁剪成相同大小
data和label都是PIL.Image对象
'''
w, h = data.size
x0, y0 = random.randint(0, w - width), random.randint(0, h - height)
return data.crop((x0, y0, x0 + width, y0 + height)), label.crop((x0, y0, x0 + width, y0 + height))

cm2lbl = np.zeros(256**3) # 每个像素点有0-255的选择, RGB三个通道
for i,cm in enumerate(colormap):
cm2lbl[(cm[0]*256+cm[1])*256+cm[2]] = i # 建立索引

def image2label(im):
data = np.array(im, dtype='int32')
idx = (data[:, :, 0] * 256 + data[:, :, 1]) * 256 + data[:, :, 2]
return np.array(cm2lbl[idx], dtype='int64') # 根据索引得到 label 矩阵

def img_transforms(im, label, crop_size):
im, label = crop(im, label, *crop_size)
im_tfs = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])

im = im_tfs(im)
label = image2label(label)
label = torch.from_numpy(label)
return im, label

#========================================================
# 实例化数据集
#========================================================

class VOCSegDataset(data.Dataset):
def __init__(self, txt_fname, crop_size, transforms):
self.crop_size = crop_size
self.transforms = transforms
data_list, label_list = read_images(txt_fname)
self.data_list = self._filter(data_list)
self.label_list = self._filter(label_list)
print('Read ' + str(len(self.data_list)) + ' images')

def _filter(self, images): # 过滤掉图片大小小于crop大小的图片
return [im for im in images if (pil_image.open(im).size[1] >= self.crop_size[0] and
pil_image.open(im).size[0] >= self.crop_size[1])]

def __getitem__(self, idx):
img = self.data_list[idx]
label = self.label_list[idx]
img = pil_image.open(img).convert('RGB')
label = pil_image.open(label).convert('RGB')
img, label = self.transforms(img, label, self.crop_size)
return img, label

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

# 实例化数据集
input_shape = (224, 224)
voc_train = VOCSegDataset('train.txt', input_shape, img_transforms)
voc_val = VOCSegDataset('val.txt', input_shape, img_transforms)

train_loader = torch.utils.data.DataLoader(voc_train, batch_size=BATCH_SIZE, shuffle=True)
val_loader = torch.utils.data.DataLoader(voc_val, batch_size=BATCH_SIZE)

#========================================================
# 模型结构设计
#========================================================

class conv2DBatchNormRelu(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding, is_batchnorm=True):
super(conv2DBatchNormRelu,self).__init__()
if is_batchnorm:
self.cbr_unit=nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
)
else:
self.cbr_unit=nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=1),
nn.ReLU(inplace=True)
)

def forward(self,inputs):
outputs = self.cbr_unit(inputs)
return outputs

class segnetDown2(nn.Module):
def __init__(self, in_channels, out_channels):
super(segnetDown2, self).__init__()
self.conv1 = conv2DBatchNormRelu(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.conv2 = conv2DBatchNormRelu(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.maxpool_with_argmax = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=True)

def forward(self,inputs):
outputs = self.conv1(inputs)
outputs = self.conv2(outputs)
unpooled_shape = outputs.size()
outputs,indices = self.maxpool_with_argmax(outputs)
return outputs, indices, unpooled_shape

class segnetDown3(nn.Module):
def __init__(self, in_channels, out_channels):
super(segnetDown3,self).__init__()
self.conv1 = conv2DBatchNormRelu(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.conv2 = conv2DBatchNormRelu(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.conv3 = conv2DBatchNormRelu(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.maxpool_with_argmax = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=True)

def forward(self,inputs):
outputs = self.conv1(inputs)
outputs = self.conv2(outputs)
outputs = self.conv3(outputs)
unpooled_shape = outputs.size()
outputs,indices = self.maxpool_with_argmax(outputs)
return outputs, indices, unpooled_shape

class segnetUp2(nn.Module):
def __init__(self, in_channels, out_channels):
super(segnetUp2, self).__init__()
self.unpool = nn.MaxUnpool2d(kernel_size=2, stride=2)
self.conv1 = conv2DBatchNormRelu(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.conv2 = conv2DBatchNormRelu(out_channels, out_channels, kernel_size=3, stride=1, padding=1)

def forward(self, inputs, indices, output_shape):
outputs = self.unpool(inputs, indices=indices, output_size=output_shape)
outputs = self.conv1(outputs)
outputs = self.conv2(outputs)
return outputs

class segnetUp3(nn.Module):
def __init__(self, in_channels, out_channels):
super(segnetUp3, self).__init__()
self.unpool = nn.MaxUnpool2d(kernel_size=2, stride=2)
self.conv1 = conv2DBatchNormRelu(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.conv2 = conv2DBatchNormRelu(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.conv3 = conv2DBatchNormRelu(out_channels, out_channels, kernel_size=3, stride=1, padding=1)

def forward(self, inputs, indices, output_shape):
outputs = self.unpool(inputs, indices=indices, output_size=output_shape)
outputs = self.conv1(outputs)
outputs = self.conv2(outputs)
outputs = self.conv3(outputs)
return outputs

class segnet(nn.Module):
def __init__(self, in_channels=3, num_classes=21):
super(segnet, self).__init__()
self.down1 = segnetDown2(in_channels=in_channels, out_channels=64)
self.down2 = segnetDown2(64, 128)
self.down3 = segnetDown3(128, 256)
self.down4 = segnetDown3(256, 512)
self.down5 = segnetDown3(512, 512)

self.up5 = segnetUp3(512, 512)
self.up4 = segnetUp3(512, 256)
self.up3 = segnetUp3(256, 128)
self.up2 = segnetUp2(128, 64)
self.up1 = segnetUp2(64, 64)
self.finconv = conv2DBatchNormRelu(64, num_classes, kernel_size=3, stride=1, padding=1)

def forward(self,inputs):
down1, indices_1, unpool_shape1 = self.down1(inputs)
down2, indices_2, unpool_shape2 = self.down2(down1)
down3, indices_3, unpool_shape3 = self.down3(down2)
down4, indices_4, unpool_shape4 = self.down4(down3)
down5, indices_5, unpool_shape5 = self.down5(down4)

up5 = self.up5(down5, indices=indices_5, output_shape=unpool_shape5)
up4 = self.up4(up5, indices=indices_4, output_shape=unpool_shape4)
up3 = self.up3(up4, indices=indices_3, output_shape=unpool_shape3)
up2 = self.up2(up3, indices=indices_2, output_shape=unpool_shape2)
up1 = self.up1(up2, indices=indices_1, output_shape=unpool_shape1)
outputs = self.finconv(up1)

return outputs

#========================================================
# 模型实例化
#========================================================

# 定义是否使用GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
net = segnet().to(device)

# 定义损失函数loss function 和优化方式
criterion = nn.NLLLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001)

#========================================================
# 训练模型
#========================================================

def train():
for epoch in range(EPOCH):
running_loss = 0.0

for i, data in enumerate(train_loader):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)

optimizer.zero_grad()

preds = net(inputs)
preds = F.log_softmax(preds, dim=1)

loss = criterion(preds, labels)
loss.backward()

optimizer.step()

running_loss += loss.item()

print('[%d] loss: %.3f' % (epoch + 1, running_loss))
torch.save(net.state_dict(), '%s/segnet_best.pth' % ('./model/'))
print('Finished Training')

#========================================================
# 测试模型
#========================================================

def test(image_file, label_file):
net.load_state_dict(torch.load('./model/segnet_best.pth'))
net.eval() # 设置模式为验证模式

image = pil_image.open(image_file).convert('RGB')
label = pil_image.open(label_file).convert('RGB')
w, h = image.size
x0, y0 = random.randint(0, w - 112), random.randint(0, h - 112)
image_crop = image.crop((x0, y0, x0 + 112, y0 + 112))
label_crop = label.crop((x0, y0, x0 + 112, y0 + 112))

im_tfs = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
image_crop_tfs = im_tfs(image_crop).unsqueeze(0).to(device)

out = net(image_crop_tfs)

pred = out.max(1)[1].squeeze().cpu().data.numpy()
cm = np.array(colormap).astype('uint8') # 定义预测函数
pred = cm[pred]

_, figs = plt.subplots(1, 3, figsize=(12, 10))
figs[0].imshow(image_crop)
figs[1].imshow(label_crop)
figs[2].imshow(pred)
plt.show()

#========================================================
# 主程序
#========================================================

if __name__ == '__main__':
train()
test('2007_000033.jpg', '2007_000033.png')

拓展阅读

0%