chenzeyang1 commited on
Commit
74bca12
·
verified ·
1 Parent(s): 3fb88cc

Upload 6 files

Browse files
model/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
model/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
model/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
model/util/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
model/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
+
model/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