forked from charlesChen02/RandLA-pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_SemanticKITTI.py
219 lines (194 loc) · 8.94 KB
/
test_SemanticKITTI.py
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
# Common
import os
import yaml
import logging
import warnings
import argparse
import numpy as np
from tqdm import tqdm
from functools import partialmethod
# torch
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
# my module
from utils.config import ConfigSemanticKITTI as cfg
from dataset.semkitti_testset import SemanticKITTI
from network.RandLANet import Network
import pickle
import time
tqdm.__init__ = partialmethod(tqdm.__init__, disable=True)
np.random.seed(0)
warnings.filterwarnings("ignore")
parser = argparse.ArgumentParser()
parser.add_argument('--backbone', type=str, default='randla', choices=['randla', 'baflac', 'baaf'])
parser.add_argument('--infer_type', default='all', type=str, choices=['all', 'sub'], help='Infer ALL or just infer Subsample')
parser.add_argument('--checkpoint_path', default='', help='Model checkpoint path [default: None]')
parser.add_argument('--test_id', default='08', type=str, help='Predicted sequence id [default: 08]')
parser.add_argument('--result_dir', default= 'result/', help='Dump dir to save prediction [default: result/]')
parser.add_argument('--yaml_config', default='utils/semantic-kitti.yaml', help='semantic-kitti.yaml path')
parser.add_argument('--batch_size', type=int, default=30, help='Batch Size during training [default: 30]')
parser.add_argument('--index_to_label', action='store_true',
help='Set index-to-label flag when inference / Do not set it on seq 08')
FLAGS = parser.parse_args()
if FLAGS.backbone == 'baflac':
from utils.config import ConfigSemanticKITTI_BAF as cfg
class Tester:
def __init__(self):
# Init Logging
os.makedirs(FLAGS.result_dir, exist_ok=True)
log_fname = os.path.join(FLAGS.result_dir, 'log_test.txt')
LOGGING_FORMAT = '%(asctime)s %(levelname)s: %(message)s'
DATE_FORMAT = '%Y%m%d %H:%M:%S'
logging.basicConfig(level=logging.DEBUG, format=LOGGING_FORMAT, datefmt=DATE_FORMAT, filename=log_fname)
self.logger = logging.getLogger("Tester")
# load yaml file
self.remap_lut = self.load_yaml(FLAGS.yaml_config)
# get_dataset & dataloader
test_dataset = SemanticKITTI('test', test_id=FLAGS.test_id, batch_size=FLAGS.batch_size)
# Network & Optimizer
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
if FLAGS.backbone == 'baflac':
from network.BAF_LAC import BAF_LAC
self.logger.info("Use Baseline: BAF-LAC")
self.net = BAF_LAC(cfg)
self.net.to(device)
collate_fn = test_dataset.collate_fn_baf_lac
elif FLAGS.backbone == 'randla':
from network.RandLANet import Network
self.logger.info("Use Baseline: Rand-LA")
self.net = Network(cfg)
self.net.to(device)
collate_fn = test_dataset.collate_fn
elif FLAGS.backbone == 'baaf':
from network.BAAF import Network
self.logger.info("Use Baseline: BAAF")
self.net = Network(cfg)
self.net.to(device)
collate_fn = test_dataset.collate_fn
else:
raise TypeError("1~5~!! can can need !!!")
self.test_loader = DataLoader(
test_dataset,
batch_size=None,
collate_fn=collate_fn,
pin_memory=True,
num_workers=0,
)
# Load module
CHECKPOINT_PATH = FLAGS.checkpoint_path
self.logger.info("Loading checkpoint %s" % (CHECKPOINT_PATH))
if CHECKPOINT_PATH is not None and os.path.isfile(CHECKPOINT_PATH):
checkpoint = torch.load(CHECKPOINT_PATH)
self.net.load_state_dict(checkpoint['model_state_dict'])
self.logger.info(FLAGS)
# Multiple GPU Testing
if torch.cuda.device_count() > 1:
self.logger.info("Let's use %d GPUs!" % (torch.cuda.device_count()))
# dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
self.net = nn.DataParallel(self.net)
self.test_dataset = test_dataset
# Initialize testing probability
self.test_dataset.init_prob()
self.test_probs = self.init_prob()
self.test_smooth = 0.98
def load_yaml(self, path):
DATA = yaml.safe_load(open(path, 'r'))
# get number of interest classes, and the label mappings
remapdict = DATA["learning_map_inv"]
# make lookup table for mapping
maxkey = max(remapdict.keys())
# +100 hack making lut bigger just in case there are unknown labels
remap_lut = np.zeros((maxkey + 100), dtype=np.int32)
remap_lut[list(remapdict.keys())] = list(remapdict.values())
return remap_lut
def init_prob(self):
probs = [] # [number of instances, number of points]
for item in self.test_dataset.possibility:
prob = np.zeros(shape=[len(item), self.test_dataset.num_classes], dtype=np.float32)
probs.append(prob)
return probs
def test(self):
self.logger.info("Start Testing")
self.rolling_predict()
# Merge Probability
self.merge_and_store()
def rolling_predict(self):
self.net.eval() # set model to eval mode (for bn and dp)
print("rooling predict", flush=True)
iter_loader = iter(self.test_loader)
with torch.no_grad():
min_possibility = self.test_dataset.min_possibility
while np.min(min_possibility) <= 0.8:
batch_data, input_inds, cloud_inds, min_possibility = next(iter_loader)
for key in batch_data:
if type(batch_data[key]) is list:
for i in range(cfg.num_layers):
batch_data[key][i] = batch_data[key][i].cuda(non_blocking=True)
else:
batch_data[key] = batch_data[key].cuda(non_blocking=True)
# Forward pass
torch.cuda.synchronize()
end_points = self.net(batch_data)
end_points['logits'] = end_points['logits'].transpose(1, 2)
# update prediction (multi-thread)
self.update_predict(end_points, batch_data, input_inds, cloud_inds)
# print("Current Possibility: ", np.min(min_possibility), flush=True)
# print()
print("rolling_predict finished")
def update_predict(self, end_points, batch_data, input_inds, cloud_inds):
# Store logits into list
# print("updating predict")
B = end_points['logits'].size(0)
end_points['logits'] = end_points['logits'].cpu().numpy()
for j in range(B):
probs = end_points['logits'][j]
inds = input_inds[j]
c_i = cloud_inds[j][0]
self.test_probs[c_i][inds] = \
self.test_smooth * self.test_probs[c_i][inds] + (1 - self.test_smooth) * probs
def merge_and_store(self):
# initialize result directory
root_dir = os.path.join(FLAGS.result_dir, self.test_dataset.test_scan_number, 'predictions')
os.makedirs(root_dir, exist_ok=True)
self.logger.info(f'mkdir {root_dir}')
print("merging and storing")
N = len(self.test_probs)
for j in tqdm(range(N)):
if FLAGS.infer_type == 'all':
proj_path = os.path.join(self.test_dataset.dataset_path, self.test_dataset.test_scan_number, 'proj')
proj_file = os.path.join(proj_path, self.test_dataset.data_list[j][1] + '_proj.pkl')
if os.path.isfile(proj_file):
with open(proj_file, 'rb') as f:
proj_inds = pickle.load(f)
probs = self.test_probs[j][proj_inds[0], :]
pred = np.argmax(probs, 1).astype(np.uint32)
elif FLAGS.infer_type == 'sub':
pred = np.argmax(self.test_probs[j], 1).astype(np.uint32)
else:
raise TypeError("Choose what you want to infer")
pred += 1
if FLAGS.index_to_label is True: # 0 - 259
pred = self.remap(pred)
name = self.test_dataset.data_list[j][1] + '.label'
output_path = os.path.join(root_dir, name)
pred.tofile(output_path)
else: # 0 - 19
name = self.test_dataset.data_list[j][1] + '.npy'
output_path = os.path.join(root_dir, name)
np.save(output_path, pred)
def remap(self, label):
upper_half = label >> 16 # get upper half for instances
lower_half = label & 0xFFFF # get lower half for semantics
lower_half = self.remap_lut[lower_half] # do the remapping of semantics
label = (upper_half << 16) + lower_half # reconstruct full label
label = label.astype(np.uint32)
return label
def main():
t1 = time.time()
tester = Tester()
tester.test()
t2 = time.time()
print("Time used: ", t2 - t1)
if __name__ == '__main__':
main()