-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtest_360BEV_S2d3d.py
180 lines (139 loc) · 6.33 KB
/
test_360BEV_S2d3d.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
import os
import yaml
import cv2
import numpy as np
import torch.nn
from pathlib import Path
import argparse
from torch.utils import data
from metric.iou import IoU
from utils.semantic_utils import color_label
# from model.trans4pano_map import Trans4map_segformer
# from model.trans4pano_deformable_detr import Trans4map_deformable_detr
from model.BEV360_segformer_s2d3d import BEV360_segformer_s2d3d
from model.BEV360_segnext_s2d3d import BEV360_segnext_s2d3d
from model.dataloader_s2d3d.pano_data_loader import DatasetLoader_pano_detr
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
######################
parser = argparse.ArgumentParser(description="config")
parser.add_argument(
"--config",
nargs="?",
type=str,
default="configs/model_360BEV_s2d3d.yml",
help="Configuration file to use",
)
args = parser.parse_args()
with open(args.config) as fp:
cfg = yaml.safe_load(fp)
########################################################################################################################
output_dir = cfg['output_dir']
Path(output_dir).mkdir(parents=True, exist_ok=True)
cfg_model = cfg['model']
backbone = cfg_model['backbone']
print('backbone:', backbone)
num_classes = cfg_model['n_obj_classes']
if backbone == 'transformer':
model = BEV360_segformer_s2d3d(cfg_model, device)
elif backbone == "segnext":
model = BEV360_segnext_s2d3d(cfg_model, device)
model = model.to(device)
model_path = cfg['model_path']
print('Loading pre-trained weights: ', model_path)
# state = torch.load(model_path, map_location='cpu')
state = torch.load(model_path)
print("best_iou:", state['best_iou'])
model_state = state['model_state']
weights = {}
for k, v in model_state.items():
k = '.'.join(k.split('.')[1:])
weights[k] = v
model.load_state_dict(weights)
model.eval()
#### init test dataset
test_loader = DatasetLoader_pano_detr(cfg["data"], split=cfg["data"]["val_split"])
testingloader = data.DataLoader(
test_loader,
batch_size=1,
num_workers=cfg["training"]["n_workers"],
pin_memory=True,
# sampler=test_sampler,
multiprocessing_context='fork',
)
##### setup Metrics #####
obj_running_metrics_test = IoU(cfg['model']['n_obj_classes'])
cm = 0
with torch.no_grad():
for batch in testingloader:
rgb, rgb_no_norm, masks_inliers, proj_indices, semmap_gt, rotationz, map_mask, map_heights, fname = batch
file_name = fname[0] + '.png'
rgb = rgb.to(device)
proj_indices = proj_indices.to(device)
masks_inliers = masks_inliers.to(device)
map_heights = map_heights.to(device)
semmap_gt = semmap_gt.long()
map_mask = map_mask.to(device)
semmap_pred, observed_masks = model(rgb, proj_indices, masks_inliers, rgb_no_norm, map_mask, map_heights)
if observed_masks.any():
semmap_pred = semmap_pred.permute(0, 2, 3, 1)
############################################################################################################
pred = semmap_pred[observed_masks].softmax(-1)
pred = torch.argmax(pred, dim=1).cpu()
pred = pred
gt = semmap_gt[observed_masks]
assert gt.min() >= 0 and gt.max() < num_classes and semmap_pred.shape[3] == num_classes
cm += np.bincount((gt * num_classes + pred).cpu().numpy(), minlength=num_classes ** 2)
############################################################################################################
semmap_pred_write = semmap_pred.data.max(-1)[1]
semmap_mask_write22 = semmap_pred_write
semmap_pred_write[~observed_masks] = 0
semmap_pred_write = semmap_pred_write.squeeze(0)
############################# semmap projection to show #############################
semmap_gt_write = semmap_gt.squeeze(0)
semmap_gt_write_out = color_label(semmap_gt_write).squeeze(0)
semmap_gt_write_out = semmap_gt_write_out.permute(1, 2, 0)
semmap_gt_write_out = semmap_gt_write_out.cpu().numpy().astype(np.uint8)
semmap_gt_write_out = cv2.cvtColor(semmap_gt_write_out, cv2.COLOR_BGR2RGB)
# ####################################################################################
# ###############################semmap projection mask to show #######################
masked_semmap_gt = semmap_gt[observed_masks]
masked_semmap_pred = semmap_pred[observed_masks]
obj_gt_val = masked_semmap_gt
obj_pred_val = masked_semmap_pred.data.max(-1)[1]
obj_running_metrics_test.add(obj_pred_val, obj_gt_val)
conf_metric = obj_running_metrics_test.conf_metric.conf
conf_metric = torch.FloatTensor(conf_metric)
conf_metric = conf_metric.to(device)
conf_metric = conf_metric.cpu().numpy()
conf_metric = conf_metric.astype(np.int32)
tmp_metrics = IoU(cfg['model']['n_obj_classes'])
tmp_metrics.reset()
tmp_metrics.conf_metric.conf = conf_metric
_, mIoU, acc, _, mRecall, _, mPrecision = tmp_metrics.value()
print("val -- mIoU: {}".format(mIoU))
print("val -- mRecall: {}".format(mRecall))
print("val -- mPrecision: {}".format(mPrecision))
print("val -- Overall_Acc: {}".format(acc))
########################################################################################################################
## Summarize_haha
print(' Summarize_hohonet '.center(50, '='))
cm = cm.reshape(num_classes, num_classes)
# id2class = np.array(valid_dataset.ID2CLASS)
id2class = ['void', 'beam', 'board', 'bookcase', 'ceiling', 'chair', 'clutter', 'column', 'door', 'floor', 'sofa',
'table', 'wall', 'window']
id2class = np.array(id2class)
valid_mask = (cm.sum(1) != 0)
print('valid_mask:', valid_mask)
cm = cm[valid_mask][:, valid_mask]
id2class = id2class[valid_mask]
inter = np.diag(cm)
union = cm.sum(0) + cm.sum(1) - inter
ious = inter / union
recalls = inter / cm.sum(1)
precisions = inter / cm.sum(0)
accs = np.sum(inter) / np.sum(cm)
for name, iou, recall, precision in zip(id2class, ious, recalls, precisions):
print(f'{name:20s}: iou {iou * 100:5.2f} / recall {recall * 100:5.2f} / precision {precision * 100:5.2f}')
print(
f'{"Overall":20s}: iou {ious.mean() * 100:5.2f} / recall {recalls.mean() * 100:5.2f} / precision {precisions.mean() * 100:5.2f} / acc {accs * 100:5.2f}')
# np.savez(os.path.join(args.out, 'cm.npz'), cm=cm)