chenzeyang1 commited on
Commit
ee1c4f3
·
verified ·
1 Parent(s): 4a84b93

Upload 8 files

Browse files
model/RTFNet.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding:utf-8
2
+ # By Yuxiang Sun, Aug. 2, 2019
3
+ # Email: sun.yuxiang@outlook.com
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torchvision.models as models
8
+ import cv2
9
+ import matplotlib.pyplot as plt
10
+ import numpy as np
11
+ from scipy.ndimage import gaussian_filter
12
+ class RTFNet(nn.Module):
13
+
14
+ def __init__(self, n_class):
15
+ super(RTFNet, self).__init__()
16
+
17
+ self.num_resnet_layers = 152
18
+
19
+ if self.num_resnet_layers == 18:
20
+ resnet_raw_model1 = models.resnet18(pretrained=True)
21
+ resnet_raw_model2 = models.resnet18(pretrained=True)
22
+ self.inplanes = 512
23
+ elif self.num_resnet_layers == 34:
24
+ resnet_raw_model1 = models.resnet34(pretrained=True)
25
+ resnet_raw_model2 = models.resnet34(pretrained=True)
26
+ self.inplanes = 512
27
+ elif self.num_resnet_layers == 50:
28
+ resnet_raw_model1 = models.resnet50(pretrained=True)
29
+ resnet_raw_model2 = models.resnet50(pretrained=True)
30
+ self.inplanes = 2048
31
+ elif self.num_resnet_layers == 101:
32
+ resnet_raw_model1 = models.resnet101(pretrained=True)
33
+ resnet_raw_model2 = models.resnet101(pretrained=True)
34
+ self.inplanes = 2048
35
+ elif self.num_resnet_layers == 152:
36
+ resnet_raw_model1 = models.resnet152(pretrained=True)
37
+ resnet_raw_model2 = models.resnet152(pretrained=True)
38
+ self.inplanes = 2048
39
+
40
+ ######## Thermal ENCODER ########
41
+
42
+ self.encoder_thermal_conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)
43
+ self.encoder_thermal_conv1.weight.data = torch.unsqueeze(torch.mean(resnet_raw_model1.conv1.weight.data, dim=1), dim=1)
44
+ self.encoder_thermal_bn1 = resnet_raw_model1.bn1
45
+ self.encoder_thermal_relu = resnet_raw_model1.relu
46
+ self.encoder_thermal_maxpool = resnet_raw_model1.maxpool
47
+ self.encoder_thermal_layer1 = resnet_raw_model1.layer1
48
+ self.encoder_thermal_layer2 = resnet_raw_model1.layer2
49
+ self.encoder_thermal_layer3 = resnet_raw_model1.layer3
50
+ self.encoder_thermal_layer4 = resnet_raw_model1.layer4
51
+
52
+ ######## RGB ENCODER ########
53
+
54
+ self.encoder_rgb_conv1 = resnet_raw_model2.conv1
55
+ self.encoder_rgb_bn1 = resnet_raw_model2.bn1
56
+ self.encoder_rgb_relu = resnet_raw_model2.relu
57
+ self.encoder_rgb_maxpool = resnet_raw_model2.maxpool
58
+ self.encoder_rgb_layer1 = resnet_raw_model2.layer1
59
+ self.encoder_rgb_layer2 = resnet_raw_model2.layer2
60
+ self.encoder_rgb_layer3 = resnet_raw_model2.layer3
61
+ self.encoder_rgb_layer4 = resnet_raw_model2.layer4
62
+
63
+
64
+
65
+ ######## DECODER ########
66
+
67
+ self.deconv1 = self._make_transpose_layer(TransBottleneck, self.inplanes//2, 2, stride=2) # using // for python 3.6
68
+ self.deconv2 = self._make_transpose_layer(TransBottleneck, self.inplanes//2, 2, stride=2) # using // for python 3.6
69
+ self.deconv3 = self._make_transpose_layer(TransBottleneck, self.inplanes//2, 2, stride=2) # using // for python 3.6
70
+ self.deconv4 = self._make_transpose_layer(TransBottleneck, self.inplanes//2, 2, stride=2) # using // for python 3.6
71
+ self.deconv5 = self._make_transpose_layer(TransBottleneck, n_class, 2, stride=2)
72
+
73
+ def _make_transpose_layer(self, block, planes, blocks, stride=1):
74
+
75
+ upsample = None
76
+ if stride != 1:
77
+ upsample = nn.Sequential(
78
+ nn.ConvTranspose2d(self.inplanes, planes, kernel_size=2, stride=stride, padding=0, bias=False),
79
+ nn.BatchNorm2d(planes),
80
+ )
81
+ elif self.inplanes != planes:
82
+ upsample = nn.Sequential(
83
+ nn.Conv2d(self.inplanes, planes, kernel_size=1, stride=stride, padding=0, bias=False),
84
+ nn.BatchNorm2d(planes),
85
+ )
86
+
87
+ for m in upsample.modules():
88
+ if isinstance(m, nn.ConvTranspose2d):
89
+ nn.init.xavier_uniform_(m.weight.data)
90
+ elif isinstance(m, nn.BatchNorm2d):
91
+ m.weight.data.fill_(1)
92
+ m.bias.data.zero_()
93
+
94
+ layers = []
95
+
96
+ for i in range(1, blocks):
97
+ layers.append(block(self.inplanes, self.inplanes))
98
+
99
+ layers.append(block(self.inplanes, planes, stride, upsample))
100
+ self.inplanes = planes
101
+
102
+ return nn.Sequential(*layers)
103
+
104
+ def forward(self, input):
105
+
106
+ rgb = input[:,:3]
107
+ thermal = input[:,3:]
108
+
109
+ verbose = False
110
+
111
+ # encoder
112
+
113
+ ######################################################################
114
+
115
+ if verbose: print("rgb.size() original: ", rgb.size()) # (480, 640)
116
+ if verbose: print("thermal.size() original: ", thermal.size()) # (480, 640)
117
+
118
+ ######################################################################
119
+
120
+ rgb = self.encoder_rgb_conv1(rgb)
121
+ if verbose: print("rgb.size() after conv1: ", rgb.size()) # (240, 320)
122
+ rgb = self.encoder_rgb_bn1(rgb)
123
+ if verbose: print("rgb.size() after bn1: ", rgb.size()) # (240, 320)
124
+ rgb = self.encoder_rgb_relu(rgb)
125
+ if verbose: print("rgb.size() after relu: ", rgb.size()) # (240, 320)
126
+
127
+ thermal = self.encoder_thermal_conv1(thermal)
128
+ if verbose: print("thermal.size() after conv1: ", thermal.size()) # (240, 320)
129
+ thermal = self.encoder_thermal_bn1(thermal)
130
+ if verbose: print("thermal.size() after bn1: ", thermal.size()) # (240, 320)
131
+ thermal = self.encoder_thermal_relu(thermal)
132
+ if verbose: print("thermal.size() after relu: ", thermal.size()) # (240, 320)
133
+
134
+ rgb = rgb + thermal
135
+
136
+ rgb = self.encoder_rgb_maxpool(rgb)
137
+ if verbose: print("rgb.size() after maxpool: ", rgb.size()) # (120, 160)
138
+
139
+ thermal = self.encoder_thermal_maxpool(thermal)
140
+ if verbose: print("thermal.size() after maxpool: ", thermal.size()) # (120, 160)
141
+
142
+ ######################################################################
143
+
144
+ rgb = self.encoder_rgb_layer1(rgb)
145
+ if verbose: print("rgb.size() after layer1: ", rgb.size()) # (120, 160)
146
+ thermal = self.encoder_thermal_layer1(thermal)
147
+ if verbose: print("thermal.size() after layer1: ", thermal.size()) # (120, 160)
148
+
149
+ rgb = rgb + thermal
150
+
151
+ ######################################################################
152
+
153
+ rgb = self.encoder_rgb_layer2(rgb)
154
+ if verbose: print("rgb.size() after layer2: ", rgb.size()) # (60, 80)
155
+ thermal = self.encoder_thermal_layer2(thermal)
156
+ if verbose: print("thermal.size() after layer2: ", thermal.size()) # (60, 80)
157
+
158
+ rgb = rgb + thermal
159
+
160
+ ######################################################################
161
+
162
+ rgb = self.encoder_rgb_layer3(rgb)
163
+ if verbose: print("rgb.size() after layer3: ", rgb.size()) # (30, 40)
164
+ thermal = self.encoder_thermal_layer3(thermal)
165
+ if verbose: print("thermal.size() after layer3: ", thermal.size()) # (30, 40)
166
+
167
+ rgb = rgb + thermal
168
+
169
+ ######################################################################
170
+
171
+ rgb = self.encoder_rgb_layer4(rgb)
172
+ if verbose: print("rgb.size() after layer4: ", rgb.size()) # (15, 20)
173
+ thermal = self.encoder_thermal_layer4(thermal)
174
+ if verbose: print("thermal.size() after layer4: ", thermal.size()) # (15, 20)
175
+
176
+ chenzeyang = thermal[0]
177
+ chenzeyang = torch.squeeze(chenzeyang)
178
+ att = chenzeyang.sum(axis=0).detach().cpu().numpy()
179
+ att = gaussian_filter(att, sigma=2)
180
+ att -= att.min()
181
+ att /= att.max()
182
+ # att1 = att.detach().cpu().numpy()
183
+ attmap = cv2.resize(att, (640, 480), interpolation=cv2.INTER_CUBIC)
184
+ attmap_uint8 = np.uint8(255 * attmap)
185
+ heatmap = cv2.applyColorMap(attmap_uint8, cv2.COLORMAP_JET)
186
+ plt.imshow(cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB))
187
+ # attmap = 255 - attmap.astype("uint8")
188
+ # plt.imshow(attmap)
189
+ plt.savefig("/opt/data/private/RTFNet/RTF_heatrgb_039.png")
190
+ plt.show()
191
+ #cv2.imwrite("/opt/data/private/czy/heatmap_00001D.png", heatmap)
192
+ chenbo = 1
193
+ fuse = rgb + thermal
194
+
195
+ ######################################################################
196
+
197
+ # decoder
198
+
199
+ fuse = self.deconv1(fuse)
200
+ if verbose: print("fuse after deconv1: ", fuse.size()) # (30, 40)
201
+ fuse = self.deconv2(fuse)
202
+ if verbose: print("fuse after deconv2: ", fuse.size()) # (60, 80)
203
+ fuse = self.deconv3(fuse)
204
+ if verbose: print("fuse after deconv3: ", fuse.size()) # (120, 160)
205
+ fuse = self.deconv4(fuse)
206
+ if verbose: print("fuse after deconv4: ", fuse.size()) # (240, 320)
207
+ fuse = self.deconv5(fuse)
208
+ if verbose: print("fuse after deconv5: ", fuse.size()) # (480, 640)
209
+
210
+ return fuse
211
+
212
+ class TransBottleneck(nn.Module):
213
+
214
+ def __init__(self, inplanes, planes, stride=1, upsample=None):
215
+ super(TransBottleneck, self).__init__()
216
+ self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
217
+ self.bn1 = nn.BatchNorm2d(planes)
218
+ self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
219
+ self.bn2 = nn.BatchNorm2d(planes)
220
+
221
+ if upsample is not None and stride != 1:
222
+ self.conv3 = nn.ConvTranspose2d(planes, planes, kernel_size=2, stride=stride, padding=0, bias=False)
223
+ else:
224
+ self.conv3 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
225
+
226
+ self.bn3 = nn.BatchNorm2d(planes)
227
+ self.relu = nn.ReLU(inplace=True)
228
+ self.upsample = upsample
229
+ self.stride = stride
230
+
231
+ for m in self.modules():
232
+ if isinstance(m, nn.Conv2d):
233
+ nn.init.xavier_uniform_(m.weight.data)
234
+ elif isinstance(m, nn.ConvTranspose2d):
235
+ nn.init.xavier_uniform_(m.weight.data)
236
+ elif isinstance(m, nn.BatchNorm2d):
237
+ m.weight.data.fill_(1)
238
+ m.bias.data.zero_()
239
+
240
+ def forward(self, x):
241
+ residual = x
242
+
243
+ out = self.conv1(x)
244
+ out = self.bn1(out)
245
+ out = self.relu(out)
246
+
247
+ out = self.conv2(out)
248
+ out = self.bn2(out)
249
+ out = self.relu(out)
250
+
251
+ out = self.conv3(out)
252
+ out = self.bn3(out)
253
+
254
+ if self.upsample is not None:
255
+ residual = self.upsample(x)
256
+
257
+ out += residual
258
+ out = self.relu(out)
259
+
260
+ return out
261
+
262
+ def unit_test():
263
+ num_minibatch = 2
264
+ rgb = torch.randn(num_minibatch, 3, 480, 640).cuda(0)
265
+ thermal = torch.randn(num_minibatch, 1, 480, 640).cuda(0)
266
+ rtf_net = RTFNet(20).cuda(0)
267
+ input = torch.cat((rgb, thermal), dim=1)
268
+ rtf_net(input)
269
+ #print('The model: ', rtf_net.modules)
270
+
271
+ if __name__ == '__main__':
272
+ unit_test()
model/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .RTFNet import RTFNet
util/KP_dataset.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Written by Ukcheol Shin, Jan. 24, 2023 using the following two repositories.
2
+ # MS-UDA: https://github.com/yeong5366/MS-UDA
3
+ # Mask2Former: https://github.com/facebookresearch/Mask2Former
4
+
5
+ import cv2
6
+ import numpy as np
7
+ import os, torch
8
+ # from imageio import imread
9
+ from torch.nn import functional as F
10
+ from torch.utils.data.dataset import Dataset
11
+ import PIL
12
+
13
+ class KP_dataset(Dataset):
14
+
15
+ def __init__(self, data_dir, split):
16
+ super(KP_dataset, self).__init__()
17
+
18
+ assert (split in ['train', 'val', 'test', 'test_day', 'test_night']),\
19
+ 'split must be train | val | test | test_day | test_night |'
20
+
21
+ if split == 'train':
22
+ with open(os.path.join(data_dir, 'train_day.txt'), 'r') as file:
23
+ self.data_list = [name.strip() for idx, name in enumerate(file)]
24
+ with open(os.path.join(data_dir, 'train_night.txt'), 'r') as file:
25
+ self.data_list += [name.strip()for idx, name in enumerate(file)]
26
+ elif split == 'val':
27
+ with open(os.path.join(data_dir, 'val_day.txt'), 'r') as file:
28
+ self.data_list = [name.strip() for idx, name in enumerate(file)]
29
+ with open(os.path.join(data_dir, 'val_night.txt'), 'r') as file:
30
+ self.data_list += [name.strip()for idx, name in enumerate(file)]
31
+ elif split == 'test':
32
+ with open(os.path.join(data_dir, 'test_day.txt'), 'r') as file:
33
+ self.data_list = [name.strip() for idx, name in enumerate(file)]
34
+ with open(os.path.join(data_dir, 'test_night.txt'), 'r') as file:
35
+ self.data_list += [name.strip()for idx, name in enumerate(file)]
36
+ self.data_list.sort()
37
+
38
+ self.data_dir = data_dir
39
+ self.split = split
40
+ self.n_data = len(self.data_list)
41
+ self.size_divisibility = -1
42
+ self.ignore_label = 19
43
+
44
+ def read_image(self, name, folder):
45
+ splited_name = name.split('_')
46
+ file_path = os.path.join(self.data_dir, 'images', splited_name[0], splited_name[1], folder, splited_name[2].replace('png','jpg',1))
47
+ image = imread(file_path).astype('float32') # HxWxC
48
+ return image
49
+
50
+ def read_label(self, name, folder):
51
+ file_path = os.path.join(self.data_dir, '%s/%s' % (folder, name))
52
+ image = imread(file_path).astype('float32')
53
+ return image
54
+
55
+ def __getitem__(self, index):
56
+ name = self.data_list[index]
57
+ image_rgb = self.read_image(name, 'visible') # 通过实验,我发现KP和PST数据集RGB和thr分开的,即RGB是3通道,thr是1通道
58
+ image_thr = np.expand_dims(self.read_image(name, 'lwir').mean(axis=2), axis=2)
59
+ image = np.concatenate((image_rgb,image_thr),axis=2) # 这句话将RGB图和thr图从通道上连接了,难怪通道数是4
60
+ label = self.read_label(name, 'labels').astype("double")
61
+
62
+ # Pad image and segmentation label here!
63
+ #image = torch.as_tensor(np.ascontiguousarray(image.transpose(2, 0, 1)))
64
+ #label = torch.as_tensor(label.astype("long"))
65
+ #image = np.asarray(PIL.Image.fromarray(image).resize((self.input_w, self.input_h)))
66
+ #image = image.astype('float32')
67
+ image = np.transpose(image, (2,0,1))/255.0
68
+ #label = np.asarray(PIL.Image.fromarray(label).resize((self.input_w, self.input_h), resample=PIL.Image.NEAREST))
69
+ #label = label.astype('int64')
70
+
71
+ if self.size_divisibility > 0:
72
+ image_size = (image.shape[-2], image.shape[-1])
73
+ padding_size = [
74
+ 0,
75
+ self.size_divisibility - image_size[1],
76
+ 0,
77
+ self.size_divisibility - image_size[0],
78
+ ]
79
+ image = F.pad(image, padding_size, value=128).contiguous()
80
+ label = F.pad(label, padding_size, value=self.ignore_label).contiguous()
81
+
82
+ image_shape = (image.shape[-2], image.shape[-1]) # h, w
83
+
84
+ # Packing data
85
+ result = {}
86
+ result["name"] = name
87
+ result["image"] = image
88
+ #result["label"] = label.long()
89
+
90
+ return torch.tensor(image), torch.tensor(label), name
91
+
92
+ def __len__(self):
93
+ return self.n_data
util/MF_dataset.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # By Yuxiang Sun, Jul. 3, 2021
2
+ # Email: sun.yuxiang@outlook.com
3
+
4
+ import os, torch
5
+ from torch.utils.data.dataset import Dataset
6
+ import numpy as np
7
+ import PIL
8
+
9
+ class MF_dataset(Dataset):
10
+
11
+ def __init__(self, data_dir, split, input_h=480, input_w=640 ,transform=[]):
12
+ super(MF_dataset, self).__init__()
13
+
14
+ assert split in ['train', 'val', 'test', 'test_day', 'test_night', 'val_test', 'most_wanted'], \
15
+ 'split must be "train"|"val"|"test"|"test_day"|"test_night"|"val_test"|"most_wanted"' # test_day, test_night
16
+
17
+ with open(os.path.join(data_dir, split+'.txt'), 'r') as f:
18
+ self.names = [name.strip() for name in f.readlines()]
19
+
20
+ self.data_dir = data_dir
21
+ self.split = split
22
+ self.input_h = input_h
23
+ self.input_w = input_w
24
+ self.transform = transform
25
+ self.n_data = len(self.names)
26
+
27
+ def read_image(self, name, folder):
28
+ file_path = os.path.join(self.data_dir, '%s/%s.png' % (folder, name))
29
+ image = np.asarray(PIL.Image.open(file_path))
30
+ return image
31
+
32
+ def __getitem__(self, index):
33
+ name = self.names[index]
34
+ image = self.read_image(name, 'images')
35
+ label = self.read_image(name, 'labels')
36
+ for func in self.transform:
37
+ image, label = func(image, label)
38
+
39
+ image = np.asarray(PIL.Image.fromarray(image).resize((self.input_w, self.input_h)))
40
+ image = image.astype('float32')
41
+ image = np.transpose(image, (2,0,1))/255.0
42
+ label = np.asarray(PIL.Image.fromarray(label).resize((self.input_w, self.input_h), resample=PIL.Image.NEAREST))
43
+ label = label.astype('int64')
44
+
45
+ return torch.tensor(image), torch.tensor(label), name
46
+
47
+ def __len__(self):
48
+ return self.n_data
util/PST_dataset.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Written by Ukcheol Shin, Jan. 24, 2023 using the following two repositories.
2
+ # PST900: https://github.com/ShreyasSkandanS/pst900_thermal_rgb
3
+ # Mask2Former: https://github.com/facebookresearch/Mask2Former
4
+
5
+ import cv2
6
+ import numpy as np
7
+ import os, torch
8
+ # from imageio import imread
9
+ from torch.nn import functional as F
10
+ from torch.utils.data.dataset import Dataset
11
+
12
+
13
+ class PST_dataset(Dataset):
14
+
15
+ def __init__(self, data_dir, split):
16
+ super(PST_dataset, self).__init__()
17
+
18
+ assert split in ['train', 'val', 'test'], \
19
+ 'split must be "train"|"val"|"test"'
20
+
21
+ # read dataset list, all files have the same name across 'rgb', 'label', 'thermal', 'depth' folders
22
+ self.data_dir = os.path.join(data_dir, split) # 这行和下一行都是我修改之后,先把未被修改的data_dir与split结合
23
+ data_dir = data_dir + split # 不加这行data_dir为./dataset/PSTdataset/RGB导致找不到文件,加入之后路径变为./dataset/PSTdataset/split/RGB
24
+ self.data_list = os.listdir(os.path.join(data_dir, 'rgb'))
25
+ self.data_list.sort()
26
+
27
+ # self.data_dir = os.path.join(data_dir, split)
28
+ self.split = split
29
+ self.n_data = len(self.data_list)
30
+ self.size_divisibility = -1
31
+ self.ignore_label = 19
32
+
33
+ def read_image(self, name, folder):
34
+ file_path = os.path.join(self.data_dir, '%s/%s' % (folder, name))
35
+ image = imread(file_path).astype('float32')
36
+ return image
37
+
38
+ def __getitem__(self, index):
39
+ name = self.data_list[index]
40
+ image_rgb = self.read_image(name, 'rgb') # 通过实验,我发现KP和PST数据集RGB和thr分开的,即RGB是3通道,thr是1通道
41
+ image_thr = np.expand_dims(self.read_image(name, 'thermal'), axis=2)
42
+ image = np.concatenate((image_rgb,image_thr),axis=2)
43
+ # depth = self.read_image(name, 'depth')
44
+
45
+ label = self.read_image(name, 'labels').astype("double")
46
+
47
+ # Pad image and segmentation label here!
48
+ #image = torch.as_tensor(np.ascontiguousarray(image.transpose(2, 0, 1)))
49
+ #label = torch.as_tensor(label.astype("long"))
50
+ image = np.transpose(image, (2, 0, 1)) / 255.0
51
+ if self.size_divisibility > 0:
52
+ image_size = (image.shape[-2], image.shape[-1])
53
+ padding_size = [
54
+ 0,
55
+ self.size_divisibility - image_size[1],
56
+ 0,
57
+ self.size_divisibility - image_size[0],
58
+ ]
59
+ image = F.pad(image, padding_size, value=128).contiguous()
60
+ label = F.pad(label, padding_size, value=self.ignore_label).contiguous()
61
+
62
+ image_shape = (image.shape[-2], image.shape[-1]) # h, w
63
+
64
+ # Packing data
65
+ #result = {}
66
+ #result["name"] = name
67
+ #result["image"] = image
68
+ #result["sem_seg_gt"] = sem_seg_gt.long()
69
+
70
+ return torch.tensor(image), torch.tensor(label), name
71
+
72
+ def __len__(self):
73
+ return self.n_data
util/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
util/augmentation.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from PIL import Image
3
+ #from ipdb import set_trace as st
4
+
5
+
6
+ class RandomFlip():
7
+ def __init__(self, prob=0.5):
8
+ #super(RandomFlip, self).__init__()
9
+ self.prob = prob
10
+
11
+ def __call__(self, image, label):
12
+ if np.random.rand() < self.prob:
13
+ image = image[:,::-1]
14
+ label = label[:,::-1]
15
+ return image, label
16
+
17
+
18
+ class RandomCrop():
19
+ def __init__(self, crop_rate=0.1, prob=1.0):
20
+ #super(RandomCrop, self).__init__()
21
+ self.crop_rate = crop_rate
22
+ self.prob = prob
23
+
24
+ def __call__(self, image, label):
25
+ if np.random.rand() < self.prob:
26
+ w, h, c = image.shape
27
+
28
+ h1 = np.random.randint(0, h*self.crop_rate)
29
+ w1 = np.random.randint(0, w*self.crop_rate)
30
+ h2 = np.random.randint(h-h*self.crop_rate, h+1)
31
+ w2 = np.random.randint(w-w*self.crop_rate, w+1)
32
+
33
+ image = image[w1:w2, h1:h2]
34
+ label = label[w1:w2, h1:h2]
35
+
36
+ return image, label
37
+
38
+
39
+ class RandomCropOut():
40
+ def __init__(self, crop_rate=0.2, prob=1.0):
41
+ #super(RandomCropOut, self).__init__()
42
+ self.crop_rate = crop_rate
43
+ self.prob = prob
44
+
45
+ def __call__(self, image, label):
46
+ if np.random.rand() < self.prob:
47
+ w, h, c = image.shape
48
+
49
+ h1 = np.random.randint(0, h*self.crop_rate)
50
+ w1 = np.random.randint(0, w*self.crop_rate)
51
+ h2 = int(h1 + h*self.crop_rate)
52
+ w2 = int(w1 + w*self.crop_rate)
53
+
54
+ image[w1:w2, h1:h2] = 0
55
+ label[w1:w2, h1:h2] = 0
56
+
57
+ return image, label
58
+
59
+
60
+ class RandomBrightness():
61
+ def __init__(self, bright_range=0.15, prob=0.9):
62
+ #super(RandomBrightness, self).__init__()
63
+ self.bright_range = bright_range
64
+ self.prob = prob
65
+
66
+ def __call__(self, image, label):
67
+ if np.random.rand() < self.prob:
68
+ bright_factor = np.random.uniform(1-self.bright_range, 1+self.bright_range)
69
+ image = (image * bright_factor).astype(image.dtype)
70
+
71
+ return image, label
72
+
73
+
74
+ class RandomNoise():
75
+ def __init__(self, noise_range=5, prob=0.9):
76
+ #super(RandomNoise, self).__init__()
77
+ self.noise_range = noise_range
78
+ self.prob = prob
79
+
80
+ def __call__(self, image, label):
81
+ if np.random.rand() < self.prob:
82
+ w, h, c = image.shape
83
+
84
+ noise = np.random.randint(
85
+ -self.noise_range,
86
+ self.noise_range,
87
+ (w,h,c)
88
+ )
89
+
90
+ image = (image + noise).clip(0,255).astype(image.dtype)
91
+
92
+ return image, label
93
+
94
+
95
+
util/util.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # By Yuxiang Sun, Dec. 4, 2020
2
+ # Email: sun.yuxiang@outlook.com
3
+
4
+ import numpy as np
5
+ from PIL import Image
6
+
7
+ # 0:unlabeled, 1:car, 2:person, 3:bike, 4:curve, 5:car_stop, 6:guardrail, 7:color_cone, 8:bump
8
+ def get_palette():
9
+ unlabelled = [0,0,0]
10
+ car = [64,0,128]
11
+ person = [64,64,0]
12
+ bike = [0,128,192]
13
+ curve = [0,0,192]
14
+ car_stop = [128,128,0]
15
+ guardrail = [64,64,128]
16
+ color_cone = [192,128,128]
17
+ bump = [192,64,0]
18
+ palette = np.array([unlabelled,car, person, bike, curve, car_stop, guardrail, color_cone, bump])
19
+
20
+ #road = [128, 64, 128]
21
+ #sidewalk = [244, 35, 232]
22
+ #building = [70, 70, 70]
23
+ #wall = [102, 102, 156]
24
+ #fence = [190, 153, 153]
25
+ #pole = [153, 153, 153]
26
+ #traffic_light = [250, 170, 30]
27
+ #traffic_sign = [220, 220, 0]
28
+ #vegetation = [107, 142, 35]
29
+ #terrain = [152, 251, 152]
30
+ #sky = [70, 130, 180]
31
+ #person = [220, 20, 60]
32
+ #rider = [255, 0, 0]
33
+ #car = [0, 0, 142]
34
+ #truck = [0, 0, 70]
35
+ #bus = [0, 60, 100]
36
+ #train = [0, 80, 100]
37
+ #motorcycle = [0, 0, 230]
38
+ #bicycle = [119, 11, 32]
39
+
40
+ #void = [0, 0, 0]
41
+ # unlabelled = [0, 0, 0]
42
+ # fire_extinhuisher = [0, 0, 255]
43
+ # backpack = [0, 255, 0]
44
+ # hand_drill = [255, 0, 0]
45
+ # rescue_randy = [255, 255, 255]
46
+ # palette = np.array([unlabelled, fire_extinhuisher, backpack, hand_drill, rescue_randy]).astype(np.uint8)
47
+ return palette
48
+
49
+ def visualize(image_name, predictions, weight_name):
50
+ palette = get_palette()
51
+ for (i, pred) in enumerate(predictions):
52
+ pred = predictions[i].cpu().numpy()
53
+ img = np.zeros((pred.shape[0], pred.shape[1], 3), dtype=np.uint8)
54
+ for cid in range(0, len(palette)): # fix the mistake from the MFNet code on Dec.27, 2019
55
+ img[pred == cid] = palette[cid]
56
+ img = Image.fromarray(np.uint8(img))
57
+ img.save('run/Pred_' + weight_name + '_' + image_name[i] + '.png')
58
+
59
+ def compute_results(conf_total):
60
+ n_class = conf_total.shape[0]
61
+ consider_unlabeled = True # must consider the unlabeled, please set it to True
62
+ if consider_unlabeled is True:
63
+ start_index = 0
64
+ else:
65
+ start_index = 1
66
+ precision_per_class = np.zeros(n_class)
67
+ recall_per_class = np.zeros(n_class)
68
+ iou_per_class = np.zeros(n_class)
69
+ for cid in range(start_index, n_class): # cid: class id
70
+ if conf_total[start_index:, cid].sum() == 0:
71
+ precision_per_class[cid] = np.nan
72
+ else:
73
+ precision_per_class[cid] = float(conf_total[cid, cid]) / float(conf_total[start_index:, cid].sum()) # precision = TP/TP+FP
74
+ if conf_total[cid, start_index:].sum() == 0:
75
+ recall_per_class[cid] = np.nan
76
+ else:
77
+ recall_per_class[cid] = float(conf_total[cid, cid]) / float(conf_total[cid, start_index:].sum()) # recall = TP/TP+FN
78
+ if (conf_total[cid, start_index:].sum() + conf_total[start_index:, cid].sum() - conf_total[cid, cid]) == 0:
79
+ iou_per_class[cid] = np.nan
80
+ else:
81
+ iou_per_class[cid] = float(conf_total[cid, cid]) / float((conf_total[cid, start_index:].sum() + conf_total[start_index:, cid].sum() - conf_total[cid, cid])) # IoU = TP/TP+FP+FN
82
+
83
+ return precision_per_class, recall_per_class, iou_per_class