-
Notifications
You must be signed in to change notification settings - Fork 301
/
utils.py
301 lines (242 loc) · 10.4 KB
/
utils.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
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
import os
import torch
import trimesh
import numpy as np
import torchvision.utils as vutils
from skimage import measure
from loguru import logger
from tools.render import Visualizer
import cv2
# print arguments
def print_args(args):
logger.info("################################ args ################################")
for k, v in args.__dict__.items():
logger.info("{0: <10}\t{1: <30}\t{2: <20}".format(k, str(v), str(type(v))))
logger.info("########################################################################")
# torch.no_grad warpper for functions
def make_nograd_func(func):
def wrapper(*f_args, **f_kwargs):
with torch.no_grad():
ret = func(*f_args, **f_kwargs)
return ret
return wrapper
# convert a function into recursive style to handle nested dict/list/tuple variables
def make_recursive_func(func):
def wrapper(vars):
if isinstance(vars, list):
return [wrapper(x) for x in vars]
elif isinstance(vars, tuple):
return tuple([wrapper(x) for x in vars])
elif isinstance(vars, dict):
return {k: wrapper(v) for k, v in vars.items()}
else:
return func(vars)
return wrapper
@make_recursive_func
def tensor2float(vars):
if isinstance(vars, float):
return vars
elif isinstance(vars, torch.Tensor):
if len(vars.shape) == 0:
return vars.data.item()
else:
return [v.data.item() for v in vars]
else:
raise NotImplementedError("invalid input type {} for tensor2float".format(type(vars)))
@make_recursive_func
def tensor2numpy(vars):
if isinstance(vars, np.ndarray):
return vars
elif isinstance(vars, torch.Tensor):
return vars.detach().cpu().numpy().copy()
else:
raise NotImplementedError("invalid input type {} for tensor2numpy".format(type(vars)))
@make_recursive_func
def tocuda(vars):
if isinstance(vars, torch.Tensor):
return vars.cuda()
elif isinstance(vars, str):
return vars
else:
raise NotImplementedError("invalid input type {} for tensor2numpy".format(type(vars)))
def save_scalars(logger, mode, scalar_dict, global_step):
scalar_dict = tensor2float(scalar_dict)
for key, value in scalar_dict.items():
if not isinstance(value, (list, tuple)):
name = '{}/{}'.format(mode, key)
logger.add_scalar(name, value, global_step)
else:
for idx in range(len(value)):
name = '{}/{}_{}'.format(mode, key, idx)
logger.add_scalar(name, value[idx], global_step)
def save_images(logger, mode, images_dict, global_step):
images_dict = tensor2numpy(images_dict)
def preprocess(name, img):
if not (len(img.shape) == 3 or len(img.shape) == 4):
raise NotImplementedError("invalid img shape {}:{} in save_images".format(name, img.shape))
if len(img.shape) == 3:
img = img[:, np.newaxis, :, :]
img = torch.from_numpy(img[:1])
return vutils.make_grid(img, padding=0, nrow=1, normalize=True, scale_each=True)
for key, value in images_dict.items():
if not isinstance(value, (list, tuple)):
name = '{}/{}'.format(mode, key)
logger.add_image(name, preprocess(name, value), global_step)
else:
for idx in range(len(value)):
name = '{}/{}_{}'.format(mode, key, idx)
logger.add_image(name, preprocess(name, value[idx]), global_step)
class DictAverageMeter(object):
def __init__(self):
self.data = {}
self.count = 0
def update(self, new_input):
self.count += 1
if len(self.data) == 0:
for k, v in new_input.items():
if not isinstance(v, float):
raise NotImplementedError("invalid data {}: {}".format(k, type(v)))
self.data[k] = v
else:
for k, v in new_input.items():
if not isinstance(v, float):
raise NotImplementedError("invalid data {}: {}".format(k, type(v)))
self.data[k] += v
def mean(self):
return {k: v / self.count for k, v in self.data.items()}
def coordinates(voxel_dim, device=torch.device('cuda')):
""" 3d meshgrid of given size.
Args:
voxel_dim: tuple of 3 ints (nx,ny,nz) specifying the size of the volume
Returns:
torch long tensor of size (3,nx*ny*nz)
"""
nx, ny, nz = voxel_dim
x = torch.arange(nx, dtype=torch.long, device=device)
y = torch.arange(ny, dtype=torch.long, device=device)
z = torch.arange(nz, dtype=torch.long, device=device)
x, y, z = torch.meshgrid(x, y, z)
return torch.stack((x.flatten(), y.flatten(), z.flatten()))
def apply_log_transform(tsdf):
sgn = torch.sign(tsdf)
out = torch.log(torch.abs(tsdf) + 1)
out = sgn * out
return out
def sparse_to_dense_torch_batch(locs, values, dim, default_val):
dense = torch.full([dim[0], dim[1], dim[2], dim[3]], float(default_val), device=locs.device)
dense[locs[:, 0], locs[:, 1], locs[:, 2], locs[:, 3]] = values
return dense
def sparse_to_dense_torch(locs, values, dim, default_val, device):
dense = torch.full([dim[0], dim[1], dim[2]], float(default_val), device=device)
if locs.shape[0] > 0:
dense[locs[:, 0], locs[:, 1], locs[:, 2]] = values
return dense
def sparse_to_dense_channel(locs, values, dim, c, default_val, device):
dense = torch.full([dim[0], dim[1], dim[2], c], float(default_val), device=device)
if locs.shape[0] > 0:
dense[locs[:, 0], locs[:, 1], locs[:, 2]] = values
return dense
def sparse_to_dense_np(locs, values, dim, default_val):
dense = np.zeros([dim[0], dim[1], dim[2]], dtype=values.dtype)
dense.fill(default_val)
dense[locs[:, 0], locs[:, 1], locs[:, 2]] = values
return dense
class SaveScene(object):
def __init__(self, cfg):
self.cfg = cfg
log_dir = cfg.LOGDIR.split('/')[-1]
self.log_dir = os.path.join('results', 'scene_' + cfg.DATASET + '_' + log_dir)
self.scene_name = None
self.global_origin = None
self.tsdf_volume = [] # not used during inference.
self.weight_volume = []
self.coords = None
self.keyframe_id = None
if cfg.VIS_INCREMENTAL:
self.vis = Visualizer()
def close(self):
self.vis.close()
cv2.destroyAllWindows()
def reset(self):
self.keyframe_id = 0
self.tsdf_volume = []
self.weight_volume = []
# self.coords = coordinates(np.array([416, 416, 128])).float()
# for scale in range(self.cfg.MODEL.N_LAYER):
# s = 2 ** (self.cfg.MODEL.N_LAYER - scale - 1)
# dim = tuple(np.array([416, 416, 128]) // s)
# self.tsdf_volume.append(torch.ones(dim).cuda())
# self.weight_volume.append(torch.zeros(dim).cuda())
@staticmethod
def tsdf2mesh(voxel_size, origin, tsdf_vol):
verts, faces, norms, vals = measure.marching_cubes(tsdf_vol, level=0)
verts = verts * voxel_size + origin # voxel grid coordinates to world coordinates
mesh = trimesh.Trimesh(vertices=verts, faces=faces, vertex_normals=norms)
return mesh
def vis_incremental(self, epoch_idx, batch_idx, imgs, outputs):
tsdf_volume = outputs['scene_tsdf'][batch_idx].data.cpu().numpy()
origin = outputs['origin'][batch_idx].data.cpu().numpy()
if self.cfg.DATASET == 'demo':
origin[2] -= 1.5
if (tsdf_volume == 1).all():
logger.warning('No valid partial data for scene {}'.format(self.scene_name))
else:
# Marching cubes
mesh = self.tsdf2mesh(self.cfg.MODEL.VOXEL_SIZE, origin, tsdf_volume)
# vis
key_frames = []
for img in imgs[::3]:
img = img.permute(1, 2, 0)
img = img[:, :, [2, 1, 0]]
img = img.data.cpu().numpy()
img = cv2.resize(img, (img.shape[1] // 2, img.shape[0] // 2))
key_frames.append(img)
key_frames = np.concatenate(key_frames, axis=0)
cv2.imshow('Selected Keyframes', key_frames / 255)
cv2.waitKey(1)
# vis mesh
self.vis.vis_mesh(mesh)
def save_incremental(self, epoch_idx, batch_idx, imgs, outputs):
save_path = os.path.join('incremental_' + self.log_dir + '_' + str(epoch_idx), self.scene_name)
if not os.path.exists(save_path):
os.makedirs(save_path)
tsdf_volume = outputs['scene_tsdf'][batch_idx].data.cpu().numpy()
origin = outputs['origin'][batch_idx].data.cpu().numpy()
if self.cfg.DATASET == 'demo':
origin[2] -= 1.5
if (tsdf_volume == 1).all():
logger.warning('No valid partial data for scene {}'.format(self.scene_name))
else:
# Marching cubes
mesh = self.tsdf2mesh(self.cfg.MODEL.VOXEL_SIZE, origin, tsdf_volume)
# save
mesh.export(os.path.join(save_path, 'mesh_{}.ply'.format(self.keyframe_id)))
def save_scene_eval(self, epoch, outputs, batch_idx=0):
tsdf_volume = outputs['scene_tsdf'][batch_idx].data.cpu().numpy()
origin = outputs['origin'][batch_idx].data.cpu().numpy()
if (tsdf_volume == 1).all():
logger.warning('No valid data for scene {}'.format(self.scene_name))
else:
# Marching cubes
mesh = self.tsdf2mesh(self.cfg.MODEL.VOXEL_SIZE, origin, tsdf_volume)
# save tsdf volume for atlas evaluation
data = {'origin': origin,
'voxel_size': self.cfg.MODEL.VOXEL_SIZE,
'tsdf': tsdf_volume}
save_path = '{}_fusion_eval_{}'.format(self.log_dir, epoch)
if not os.path.exists(save_path):
os.makedirs(save_path)
np.savez_compressed(
os.path.join(save_path, '{}.npz'.format(self.scene_name)),
**data)
mesh.export(os.path.join(save_path, '{}.ply'.format(self.scene_name)))
def __call__(self, outputs, inputs, epoch_idx):
# no scene saved, skip
if "scene_name" not in outputs.keys():
return
batch_size = len(outputs['scene_name'])
for i in range(batch_size):
scene = outputs['scene_name'][i]
self.scene_name = scene.replace('/', '-')
if self.cfg.SAVE_SCENE_MESH:
self.save_scene_eval(epoch_idx, outputs, i)