This repository has been archived by the owner on Oct 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 52
/
trainer.py
2088 lines (1768 loc) · 78.1 KB
/
trainer.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Meta Platforms, Inc. and affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import matplotlib.pylab as plt
import torch
import torch.optim as optim
from torchvision import transforms
import trimesh
import imgviz
import json
import cv2
import copy
import os
from scipy import ndimage
from scipy.spatial import KDTree
from isdf.datasets import (
dataset, image_transforms, sdf_util, data_util
)
from isdf.datasets.data_util import FrameData
from isdf.modules import (
fc_map, embedding, render, sample, loss
)
from isdf import geometry, visualisation
from isdf.eval import metrics, eval_pts
from isdf.visualisation import draw, draw3D
from isdf.eval.metrics import start_timing, end_timing
class Trainer():
def __init__(
self,
device,
config_file,
chkpt_load_file=None,
incremental=True,
grid_dim=200,
):
super(Trainer, self).__init__()
self.device = device
self.incremental = incremental
self.tot_step_time = 0.
self.last_is_keyframe = False
self.steps_since_frame = 0
self.optim_frames = 0
self.gt_depth_vis = None
self.gt_im_vis = None
# eval params
self.gt_sdf_interp = None
self.stage_sdf_interp = None
self.sdf_dims = None
self.sdf_transform = None
self.grid_dim = grid_dim
self.new_grid_dim = None
self.chunk_size = 100000
with open(config_file) as json_file:
self.config = json.load(json_file)
self.frames = FrameData() # keyframes
self.set_params()
self.set_cam()
self.set_directions()
self.load_data()
# scene params for visualisation
self.scene_center = None
self.inv_bounds_transform = None
self.active_idxs = None
self.active_pixels = None
if self.gt_scene:
scene_mesh = trimesh.exchange.load.load(
self.scene_file, process=False)
self.set_scene_properties(scene_mesh)
if self.dataset_format == "realsense_franka_offline":
self.set_scene_properties()
self.load_networks()
if chkpt_load_file is not None:
self.load_checkpoint(chkpt_load_file)
self.sdf_map.train()
# for evaluation
if self.do_eval:
if self.sdf_transf_file is not None:
self.load_gt_sdf()
self.cosSim = torch.nn.CosineSimilarity(dim=-1, eps=1e-6)
# Init functions ---------------------------------------
def get_latest_frame_id(self):
return int(self.tot_step_time * self.fps)
def set_scene_properties(self, scene_mesh = None):
# if self.live:
# # bounds is axis algined, camera initial pose defines origin
# ax_aligned_box = scene_mesh.bounding_box
# T_extent_to_scene, bounds_extents = \
# trimesh.bounds.oriented_bounds(ax_aligned_box)
# else:
# bounds_transform is a transformation matrix which moves
# the center of the bounding box of the mesh to the origin.
# bounds_extents is the extents of the mesh once transformed
# with bounds_transform
if "realsense_franka" in self.dataset_format:
# define our own workspace bounds
T_extent_to_scene = trimesh.transformations.rotation_matrix(np.deg2rad(self.config["workspace"]["rotate_z"]), [0, 0, 1]) # flip workspace
T_extent_to_scene[:3, 3] = np.array(self.config["workspace"]["offset"])
bounds_extents = np.array(self.config["workspace"]["extents"])
self.scene_center = np.array(self.config["workspace"]["center"])
else:
T_extent_to_scene, bounds_extents = \
trimesh.bounds.oriented_bounds(scene_mesh)
self.scene_center = scene_mesh.bounds.mean(axis=0)
self.inv_bounds_transform = torch.from_numpy(
T_extent_to_scene).float().to(self.device)
self.bounds_transform_np = np.linalg.inv(T_extent_to_scene)
self.bounds_transform = torch.from_numpy(
self.bounds_transform_np).float().to(self.device)
# Need to divide by range_dist as it will scale the grid which
# is created in range = [-1, 1]
# Also divide by 0.9 so extents are a bit larger than gt mesh
grid_range = [-1.0, 1.0]
range_dist = grid_range[1] - grid_range[0]
self.scene_scale_np = bounds_extents / (range_dist * 0.9)
self.scene_scale = torch.from_numpy(
self.scene_scale_np).float().to(self.device)
self.inv_scene_scale = 1. / self.scene_scale
self.grid_pc = geometry.transform.make_3D_grid(
grid_range,
self.grid_dim,
self.device,
transform=self.bounds_transform,
scale=self.scene_scale,
)
self.grid_pc = self.grid_pc.view(-1, 3).to(self.device)
self.up_ix = np.argmax(np.abs(np.matmul(
self.up, self.bounds_transform_np[:3, :3])))
self.grid_up = self.bounds_transform_np[:3, self.up_ix]
self.up_aligned = np.dot(self.grid_up, self.up) > 0
self.crop_dist = 0.1 if "franka" in self.dataset_format else 0.25
def set_params(self):
# Dataset
# require dataset format, depth scale and camera params
self.dataset_format = self.config["dataset"]["format"]
self.live = False
if self.dataset_format in ["arkit", "realsense", "realsense_franka"]:
self.live = True
if "realsense_franka" in self.dataset_format:
self.ext_calib = self.config["ext_calib"]
else:
self.ext_calib = None
self.inv_depth_scale = 1. / self.config["dataset"]["depth_scale"]
self.distortion_coeffs = []
if self.dataset_format == "ScanNet":
self.set_scannet_cam_params(
self.config["dataset"]["intrinsics_file"])
else:
self.fx = self.config["dataset"]["camera"]["fx"]
self.fy = self.config["dataset"]["camera"]["fy"]
self.cx = self.config["dataset"]["camera"]["cx"]
self.cy = self.config["dataset"]["camera"]["cy"]
self.H = self.config["dataset"]["camera"]["h"]
self.W = self.config["dataset"]["camera"]["w"]
if "k1" in self.config["dataset"]["camera"]:
self.distortion_coeffs.append(self.config["dataset"]["camera"]["k1"])
if "k2" in self.config["dataset"]["camera"]:
self.distortion_coeffs.append(self.config["dataset"]["camera"]["k2"])
if "p1" in self.config["dataset"]["camera"]:
self.distortion_coeffs.append(self.config["dataset"]["camera"]["p1"])
if "p2" in self.config["dataset"]["camera"]:
self.distortion_coeffs.append(self.config["dataset"]["camera"]["p2"])
if "k3" in self.config["dataset"]["camera"]:
self.distortion_coeffs.append(self.config["dataset"]["camera"]["k3"])
self.gt_scene = False
self.fps = 30 # this can be set to anything when in live mode
if not self.live:
self.seq_dir = self.config["dataset"]["seq_dir"]
self.seq = [x for x in self.seq_dir.split('/') if x != ''][-1]
self.ims_file = self.seq_dir
if self.dataset_format != "realsense_franka_offline":
self.ims_file = os.path.join(self.ims_file, "results")
self.fps = self.config["dataset"]["fps"]
self.obj_bounds_file = None
if os.path.exists(self.seq_dir + "/obj_bounds.txt"):
self.obj_bounds_file = self.seq_dir + "/obj_bounds.txt"
if "gt_sdf_dir" in self.config["dataset"]:
gt_sdf_dir = self.config["dataset"]["gt_sdf_dir"]
self.scene_file = gt_sdf_dir + "mesh.obj"
self.gt_sdf_file = gt_sdf_dir + "/1cm/sdf.npy"
self.stage_sdf_file = gt_sdf_dir + "/1cm/stage_sdf.npy"
self.sdf_transf_file = gt_sdf_dir + "/1cm/transform.txt"
self.gt_scene = True
self.scannet_dir = None
if self.dataset_format == "ScanNet":
self.scannet_dir = self.config["dataset"]["scannet_dir"]
if "im_indices" in self.config["dataset"]:
self.indices = self.config["dataset"]["im_indices"]
self.noisy_depth = False
if "noisy_depth" in self.config["dataset"]:
self.noisy_depth = bool(self.config["dataset"]["noisy_depth"])
self.traj_file = self.seq_dir + "/traj.txt"
# assert os.path.exists(self.traj_file)
self.gt_traj = None
self.n_steps = self.config["trainer"]["steps"]
# Model
self.do_active = bool(self.config["model"]["do_active"])
# scaling applied to network output before interpreting value as sdf
self.scale_output = self.config["model"]["scale_output"]
# noise applied to network output
self.noise_std = self.config["model"]["noise_std"]
self.noise_kf = self.config["model"]["noise_kf"]
self.noise_frame = self.config["model"]["noise_frame"]
# sliding window size for optimising latest frames
self.window_size = self.config["model"]["window_size"]
self.hidden_layers_block = self.config["model"]["hidden_layers_block"]
self.hidden_feature_size = self.config["model"]["hidden_feature_size"]
# multiplier for time spent doing training vs time elapsed
# to simulate scenarios with e.g. 50% perception time, 50% planning
self.frac_time_perception = \
self.config["model"]["frac_time_perception"]
# optimisation steps per kf
self.iters_per_kf = self.config["model"]["iters_per_kf"]
self.iters_per_frame = self.config["model"]["iters_per_frame"]
# thresholds for adding frame to keyframe set
self.kf_dist_th = self.config["model"]["kf_dist_th"]
self.kf_pixel_ratio = self.config["model"]["kf_pixel_ratio"]
embed_config = self.config["model"]["embedding"]
# scaling applied to coords before embedding
self.scale_input = embed_config["scale_input"]
self.n_embed_funcs = embed_config["n_embed_funcs"]
# boolean to use gaussian embedding
self.gauss_embed = bool(embed_config["gauss_embed"])
self.gauss_embed_std = embed_config["gauss_embed_std"]
self.optim_embedding = bool(embed_config["optim_embedding"])
# Evaluation
self.do_vox_comparison = (
bool(self.config["eval"]["do_vox_comparison"])
and "eval_pts_root" in self.config["eval"])
self.do_eval = self.config["eval"]["do_eval"]
self.eval_freq_s = self.config["eval"]["eval_freq_s"]
self.sdf_eval = bool(self.config["eval"]["sdf_eval"])
self.mesh_eval = bool(self.config["eval"]["mesh_eval"])
self.eval_times = []
if self.do_vox_comparison and "eval_pts_root" in self.config["eval"]:
self.eval_pts_root = self.config["eval"]["eval_pts_root"]
self.eval_pts_dir = self.config["eval"]["eval_pts_root"]
self.eval_pts_dir += "/vox/"
if self.frac_time_perception == 1.:
self.eval_pts_dir += "0.055/"
elif self.frac_time_perception == 0.75:
self.eval_pts_dir += "0.063/"
elif self.frac_time_perception == 0.5:
self.eval_pts_dir += "0.078/"
elif self.frac_time_perception == 0.25:
self.eval_pts_dir += "0.11/"
else:
raise ValueError(
'Frace perception time not in [0.25, 0.5, 0.75, 1.]')
self.eval_pts_dir += [
x for x in self.seq_dir.split('/') if x != ""][-1] +\
"/eval_pts/"
self.eval_times = [float(x) for x in os.listdir(self.eval_pts_dir)]
self.eval_times.sort()
print("eval pts dir", self.eval_pts_dir)
self.cached_dataset = eval_pts.get_cache_dataset(
self.seq_dir, self.dataset_format, self.scannet_dir)
# save
self.save_period = self.config["save"]["save_period"]
self.save_times = np.arange(
self.save_period, 2000, self.save_period).tolist()
self.save_checkpoints = bool(self.config["save"]["save_checkpoints"])
self.save_slices = bool(self.config["save"]["save_slices"])
self.save_meshes = bool(self.config["save"]["save_meshes"])
# Loss
self.bounds_method = self.config["loss"]["bounds_method"]
assert self.bounds_method in ["ray", "normal", "pc"]
self.loss_type = self.config["loss"]["loss_type"]
assert self.loss_type in ["L1", "L2"]
self.trunc_weight = self.config["loss"]["trunc_weight"]
# distance at which losses transition (see paper for details)
self.trunc_distance = self.config["loss"]["trunc_distance"]
self.eik_weight = self.config["loss"]["eik_weight"]
# where to apply the eikonal loss
self.eik_apply_dist = self.config["loss"]["eik_apply_dist"]
self.grad_weight = self.config["loss"]["grad_weight"]
self.orien_loss = bool(self.config["loss"]["orien_loss"])
self.do_normal = False
if self.bounds_method == "normal" or self.grad_weight != 0:
self.do_normal = True
# optimiser
self.learning_rate = self.config["optimiser"]["lr"]
self.weight_decay = self.config["optimiser"]["weight_decay"]
# Sampling
self.max_depth = self.config["sample"]["depth_range"][1]
self.min_depth = self.config["sample"]["depth_range"][0]
self.dist_behind_surf = self.config["sample"]["dist_behind_surf"]
self.n_rays = self.config["sample"]["n_rays"]
self.n_rays_is_kf = self.config["sample"]["n_rays_is_kf"]
# num stratified samples per ray
self.n_strat_samples = self.config["sample"]["n_strat_samples"]
# num surface samples per ray
self.n_surf_samples = self.config["sample"]["n_surf_samples"]
def set_scannet_cam_params(self, file):
info = {}
with open(file, 'r') as f:
for line in f.read().splitlines():
split = line.split(' = ')
info[split[0]] = split[1]
self.fx = float(info['fx_depth'])
self.fy = float(info['fy_depth'])
self.cx = float(info['mx_depth'])
self.cy = float(info['my_depth'])
self.H = int(info['depthHeight'])
self.W = int(info['depthWidth'])
def set_cam(self):
reduce_factor = 16
self.H_vis = self.H // reduce_factor
self.W_vis = self.W // reduce_factor
self.fx_vis = self.fx / reduce_factor
self.fy_vis = self.fy / reduce_factor
self.cx_vis = self.cx / reduce_factor
self.cy_vis = self.cy / reduce_factor
reduce_factor_up = 8
self.H_vis_up = self.H // reduce_factor_up
self.W_vis_up = self.W // reduce_factor_up
self.fx_vis_up = self.fx / reduce_factor_up
self.fy_vis_up = self.fy / reduce_factor_up
self.cx_vis_up = self.cx / reduce_factor_up
self.cy_vis_up = self.cy / reduce_factor_up
self.loss_approx_factor = 8
w_block = self.W // self.loss_approx_factor
h_block = self.H // self.loss_approx_factor
increments_w = torch.arange(
self.loss_approx_factor, device=self.device) * w_block
increments_h = torch.arange(
self.loss_approx_factor, device=self.device) * h_block
c, r = torch.meshgrid(increments_w, increments_h)
c, r = c.t(), r.t()
self.increments_single = torch.stack((r, c), dim=2).view(-1, 2)
# base radius for integrated PE
# norm_dirs_C = self.dirs_C / torch.linalg.norm(
# self.dirs_C, dim=-1, keepdims=True)
# dx = torch.sqrt(torch.sum(
# (self.dirs_C[:, 1, 0, :] - self.dirs_C[:, 0, 0, :])**2, -1))
# self.pix_radius = dx.item() * 2 / np.sqrt(12)
def set_directions(self):
self.dirs_C = geometry.transform.ray_dirs_C(
1,
self.H,
self.W,
self.fx,
self.fy,
self.cx,
self.cy,
self.device,
depth_type="z",
)
self.dirs_C_vis = geometry.transform.ray_dirs_C(
1,
self.H_vis,
self.W_vis,
self.fx_vis,
self.fy_vis,
self.cx_vis,
self.cy_vis,
self.device,
depth_type="z",
).view(1, -1, 3)
self.dirs_C_vis_up = geometry.transform.ray_dirs_C(
1,
self.H_vis_up,
self.W_vis_up,
self.fx_vis_up,
self.fy_vis_up,
self.cx_vis_up,
self.cy_vis_up,
self.device,
depth_type="z",
).view(1, -1, 3)
def load_networks(self):
positional_encoding = embedding.PostionalEncoding(
min_deg=0,
max_deg=self.n_embed_funcs,
scale=self.scale_input,
transform=self.inv_bounds_transform,
)
self.sdf_map = fc_map.SDFMap(
positional_encoding,
hidden_size=self.hidden_feature_size,
hidden_layers_block=self.hidden_layers_block,
scale_output=self.scale_output,
).to(self.device)
self.optimiser = optim.AdamW(
self.sdf_map.parameters(),
lr=self.learning_rate,
weight_decay=self.weight_decay
)
def load_checkpoint(self, checkpoint_load_file):
checkpoint = torch.load(checkpoint_load_file)
self.sdf_map.load_state_dict(checkpoint["model_state_dict"])
# self.optimiser.load_state_dict(checkpoint["optimizer_state_dict"])
def load_gt_sdf(self):
sdf_grid = np.load(self.gt_sdf_file)
if self.dataset_format == "ScanNet":
sdf_grid = np.abs(sdf_grid)
self.sdf_transform = np.loadtxt(self.sdf_transf_file)
self.gt_sdf_interp = sdf_util.sdf_interpolator(
sdf_grid, self.sdf_transform)
self.sdf_dims = torch.tensor(sdf_grid.shape)
# Data methods ---------------------------------------
def load_data(self):
rgb_transform = transforms.Compose(
[image_transforms.BGRtoRGB()])
depth_transform = transforms.Compose(
[image_transforms.DepthScale(self.inv_depth_scale),
image_transforms.DepthFilter(self.max_depth)])
camera_matrix = None
noisy_depth = None
if self.dataset_format == "ScanNet":
dataset_class = dataset.ScanNetDataset
col_ext = ".jpg"
self.up = np.array([0., 0., 1.])
ims_file = self.scannet_dir
elif self.dataset_format == "replica":
dataset_class = dataset.ReplicaDataset
col_ext = ".jpg"
self.up = np.array([0., 1., 0.])
ims_file = self.ims_file
elif self.dataset_format == "replicaCAD":
dataset_class = dataset.ReplicaDataset
col_ext = ".png"
self.up = np.array([0., 1., 0.])
ims_file = self.ims_file
noisy_depth = self.noisy_depth
elif self.dataset_format == "arkit":
dataset_class = dataset.ARKit
col_ext = None
self.up = np.array([0., 0., 1.])
ims_file = None
self.traj_file = None
elif self.dataset_format in ["realsense", "realsense_franka"]:
dataset_class = dataset.ROSSubscriber
col_ext = None
self.up = np.array([0., 0., 1.])
ims_file = self.ext_calib # extrinsic calib
self.traj_file = None
camera_matrix = np.array([[self.fx, 0.0, self.cx], [0.0, self.fy, self.cy], [0.0, 0.0, 1.0]])
elif self.dataset_format == "realsense_franka_offline":
dataset_class = dataset.RealsenseFrankaOffline
col_ext = ".jpg"
self.up = np.array([0., 0., 1.])
ims_file = self.ims_file
camera_matrix = np.array([[self.fx, 0.0, self.cx], [0.0, self.fy, self.cy], [0.0, 0.0, 1.0]])
self.scene_dataset = dataset_class(
ims_file,
traj_file=self.traj_file,
rgb_transform=rgb_transform,
depth_transform=depth_transform,
col_ext=col_ext,
noisy_depth=noisy_depth,
distortion_coeffs=self.distortion_coeffs,
camera_matrix=camera_matrix,
)
if self.incremental is False:
if "im_indices" not in self.config["dataset"]:
if "n_views" in self.config["dataset"]:
n_views = self.config["dataset"]["n_views"]
if n_views > 0:
n_dataset = len(self.scene_dataset)
if self.config["dataset"]["random_views"]:
self.indices = np.random.choice(np.arange(0, n_dataset), size=n_views, replace=False)
else:
self.indices = np.linspace(0, n_dataset, n_views, dtype = int, endpoint= False)
print("Frame indices", self.indices)
self.last_is_keyframe = True
idxs = self.indices
frame_data = self.get_data(idxs)
self.add_data(frame_data)
def get_data(self, idxs):
frames_data = FrameData()
for idx in idxs:
sample = self.scene_dataset[idx]
im_np = sample["image"][None, ...]
depth_np = sample["depth"][None, ...]
T_np = sample["T"][None, ...]
im = torch.from_numpy(im_np).float().to(self.device) / 255.
depth = torch.from_numpy(depth_np).float().to(self.device)
T = torch.from_numpy(T_np).float().to(self.device)
data = FrameData(
frame_id=np.array([idx]),
im_batch=im,
im_batch_np=im_np,
depth_batch=depth,
depth_batch_np=depth_np,
T_WC_batch=T,
T_WC_batch_np=T_np,
)
if self.do_normal:
pc = geometry.transform.pointcloud_from_depth_torch(
depth[0], self.fx, self.fy, self.cx, self.cy)
normals = geometry.transform.estimate_pointcloud_normals(pc)
data.normal_batch = normals[None, :]
if self.gt_traj is not None:
data.T_WC_gt = self.gt_traj[idx][None, ...]
frames_data.add_frame_data(data, replace=False)
return frames_data
def add_data(self, data, replace=False):
# if last frame isn't a keyframe then the new frame
# replaces last frame in batch.
replace = self.last_is_keyframe is False
self.frames.add_frame_data(data, replace)
if self.last_is_keyframe:
print("New keyframe. KF ids:", self.frames.frame_id[:-1])
def add_frame(self, frame_data):
if self.last_is_keyframe:
self.frozen_sdf_map = copy.deepcopy(self.sdf_map)
self.add_data(frame_data)
self.steps_since_frame = 0
self.last_is_keyframe = False
self.optim_frames = self.iters_per_frame
self.noise_std = self.noise_frame
# Keyframe methods ----------------------------------
def is_keyframe(self, T_WC, depth_gt):
sample_pts = self.sample_points(
depth_gt, T_WC, n_rays=self.n_rays_is_kf, dist_behind_surf=0.8)
pc = sample_pts["pc"]
z_vals = sample_pts["z_vals"]
depth_sample = sample_pts["depth_sample"]
with torch.set_grad_enabled(False):
sdf = self.frozen_sdf_map(pc, noise_std=self.noise_std)
z_vals, ind1 = z_vals.sort(dim=-1)
ind0 = torch.arange(z_vals.shape[0])[:, None].repeat(
1, z_vals.shape[1])
sdf = sdf[ind0, ind1]
view_depth = render.sdf_render_depth(z_vals, sdf)
loss = torch.abs(view_depth - depth_sample) / depth_sample
below_th = loss < self.kf_dist_th
size_loss = below_th.shape[0]
below_th_prop = below_th.sum().float() / size_loss
is_keyframe = below_th_prop.item() < self.kf_pixel_ratio
print(
"Proportion of loss below threshold",
below_th_prop.item(),
"for KF should be less than",
self.kf_pixel_ratio,
" ---> is keyframe:",
is_keyframe
)
return is_keyframe
def check_keyframe_latest(self):
"""
returns whether or not to add a new frame.
"""
add_new_frame = False
if self.last_is_keyframe:
# Latest frame is already a keyframe. We have now
# finished the extra steps and want to add a new frame
add_new_frame = True
else:
# Check if latest frame should be a keyframe.
T_WC = self.frames.T_WC_batch[-1].unsqueeze(0)
depth_gt = self.frames.depth_batch[-1].unsqueeze(0)
self.last_is_keyframe = self.is_keyframe(T_WC, depth_gt)
time_since_kf = self.tot_step_time - self.frames.frame_id[-2] / 30.
if time_since_kf > 5. and not self.live:
print("More than 5 seconds since last kf, so add new")
self.last_is_keyframe = True
if self.last_is_keyframe:
self.optim_frames = self.iters_per_kf
self.noise_std = self.noise_kf
else:
add_new_frame = True
return add_new_frame
def select_keyframes(self):
"""
Use most recent two keyframes then fill rest of window
based on loss distribution across the remaining keyframes.
"""
n_frames = len(self.frames)
limit = n_frames - 2
denom = self.frames.frame_avg_losses[:-2].sum()
loss_dist = self.frames.frame_avg_losses[:-2] / denom
loss_dist_np = loss_dist.cpu().numpy()
select_size = self.window_size - 2
rand_ints = np.random.choice(
np.arange(0, limit),
size=select_size,
replace=False,
p=loss_dist_np)
last = n_frames - 1
idxs = [*rand_ints, last - 1, last]
return idxs
def clear_keyframes(self):
self.frames = FrameData() # keyframes
self.gt_depth_vis = None
self.gt_im_vis = None
# Main training methods ----------------------------------
def sample_points(
self,
depth_batch,
T_WC_batch,
norm_batch=None,
active_loss_approx=None,
n_rays=None,
dist_behind_surf=None,
n_strat_samples=None,
n_surf_samples=None,
):
"""
Sample points by first sampling pixels, then sample depths along
the backprojected rays.
"""
if n_rays is None:
n_rays = self.n_rays
if dist_behind_surf is None:
dist_behind_surf = self.dist_behind_surf
if n_strat_samples is None:
n_strat_samples = self.n_strat_samples
if n_surf_samples is None:
n_surf_samples = self.n_surf_samples
n_frames = depth_batch.shape[0]
if active_loss_approx is None:
indices_b, indices_h, indices_w = sample.sample_pixels(
n_rays, n_frames, self.H, self.W, device=self.device)
else:
# indices_b, indices_h, indices_w = \
# active_sample.active_sample_pixels(
# n_rays, n_frames, self.H, self.W, device=self.device,
# loss_approx=active_loss_approx,
# increments_single=self.increments_single
# )
raise Exception('Active sampling not currently supported.')
get_masks = active_loss_approx is None
(
dirs_C_sample,
depth_sample,
norm_sample,
T_WC_sample,
binary_masks,
indices_b,
indices_h,
indices_w
) = sample.get_batch_data(
depth_batch,
T_WC_batch,
self.dirs_C,
indices_b,
indices_h,
indices_w,
norm_batch=norm_batch,
get_masks=get_masks,
)
max_depth = depth_sample + dist_behind_surf
pc, z_vals = sample.sample_along_rays(
T_WC_sample,
self.min_depth,
max_depth,
n_strat_samples,
n_surf_samples,
dirs_C_sample,
gt_depth=depth_sample,
grad=False,
)
sample_pts = {
"depth_batch": depth_batch,
"pc": pc,
"z_vals": z_vals,
"indices_b": indices_b,
"indices_h": indices_h,
"indices_w": indices_w,
"dirs_C_sample": dirs_C_sample,
"depth_sample": depth_sample,
"T_WC_sample": T_WC_sample,
"norm_sample": norm_sample,
"binary_masks": binary_masks,
}
return sample_pts
def sdf_eval_and_loss(
self,
sample,
do_avg_loss=True,
):
pc = sample["pc"]
z_vals = sample["z_vals"]
indices_b = sample["indices_b"]
indices_h = sample["indices_h"]
indices_w = sample["indices_w"]
dirs_C_sample = sample["dirs_C_sample"]
depth_sample = sample["depth_sample"]
T_WC_sample = sample["T_WC_sample"]
norm_sample = sample["norm_sample"]
binary_masks = sample["binary_masks"]
depth_batch = sample["depth_batch"]
do_sdf_grad = self.eik_weight != 0 or self.grad_weight != 0
if do_sdf_grad:
pc.requires_grad_()
sdf = self.sdf_map(pc, noise_std=self.noise_std)
sdf_grad = None
if do_sdf_grad:
sdf_grad = fc_map.gradient(pc, sdf)
# compute bounds
bounds, grad_vec = loss.bounds(
self.bounds_method,
dirs_C_sample,
depth_sample,
T_WC_sample,
z_vals,
pc,
self.trunc_distance,
norm_sample,
do_grad=True,
)
# compute loss
sdf_loss_mat, free_space_ixs = loss.sdf_loss(
sdf, bounds, self.trunc_distance, loss_type=self.loss_type)
eik_loss_mat = None
if self.eik_weight != 0:
eik_loss_mat = torch.abs(sdf_grad.norm(2, dim=-1) - 1)
grad_loss_mat = None
if self.grad_weight != 0:
pred_norms = sdf_grad[:, 0]
surf_loss_mat = 1 - self.cosSim(pred_norms, norm_sample)
grad_vec[torch.where(grad_vec[..., 0].isnan())] = \
norm_sample[torch.where(grad_vec[..., 0].isnan())[0]]
grad_loss_mat = 1 - self.cosSim(grad_vec, sdf_grad[:, 1:])
grad_loss_mat = torch.cat(
(surf_loss_mat[:, None], grad_loss_mat), dim=1)
if self.orien_loss:
grad_loss_mat = (grad_loss_mat > 1).float()
total_loss, total_loss_mat, losses = loss.tot_loss(
sdf_loss_mat, grad_loss_mat, eik_loss_mat,
free_space_ixs, bounds, self.eik_apply_dist,
self.trunc_weight, self.grad_weight, self.eik_weight,
)
loss_approx, frame_avg_loss = None, None
if do_avg_loss:
loss_approx, frame_avg_loss = loss.frame_avg(
total_loss_mat, depth_batch, indices_b, indices_h, indices_w,
self.W, self.H, self.loss_approx_factor, binary_masks)
# # # for plot
# z_to_euclidean_depth = dirs_C_sample.norm(dim=-1)
# ray_target = depth_sample[:, None] - z_vals
# ray_target = z_to_euclidean_depth[:, None] * ray_target
# # apply correction based on angle between ray and normal
# costheta = torch.abs(self.cosSim(-dirs_C_sample, norm_sample))
# # only apply correction out to truncation distance
# sub = self.trunc_distance * (1. - costheta)
# normal_target_fs = ray_target - sub[:, None]
# # target_normal = ray_target.clone()
# target_normal = normal_target_fs
# ixs = target_normal < self.trunc_distance
# target_normal[ixs] = (ray_target * costheta[:, None])[ixs]
# self.check_gt_sdf(
# depth_sample, z_vals, dirs_C_sample, pc,
# ray_target, target_sdf, target_normal)
return (
total_loss,
losses,
loss_approx,
frame_avg_loss,
)
def check_gt_sdf(self, depth_sample, z_vals, dirs_C_sample, pc,
target_ray, target_pc, target_normal):
# origins, dirs_W):
# reorder in increasing z vals
z_vals, indices = z_vals.sort(dim=-1)
row_ixs = torch.arange(pc.shape[0])[:, None].repeat(1, pc.shape[1])
pc = pc[row_ixs, indices]
target_ray = target_ray[row_ixs, indices]
target_pc = target_pc[row_ixs, indices]
if target_normal is not None:
target_normal = target_normal[row_ixs, indices]
z2euc_sample = torch.norm(dirs_C_sample, dim=-1)
z_vals = z_vals * z2euc_sample[:, None]
scene = trimesh.Scene(trimesh.load(self.scene_file))
with torch.set_grad_enabled(False):
j = 0
fig, ax = plt.subplots(3, 1, figsize=(11, 10))
for i in [9, 19, 23]: # range(0, 100):
gt_sdf = sdf_util.eval_sdf_interp(
self.gt_sdf_interp,
pc[i].reshape(-1, 3).detach().cpu().numpy(),
handle_oob='fill', oob_val=np.nan)
x = z_vals[i].cpu()
lw = 2.5
ax[j].hlines(0, x[0], x[-1], color="gray", linestyle="--")
ax[j].plot(
x, gt_sdf, label="True signed distance",
color="C1", linewidth=lw
)
ax[j].plot(
x, target_ray[i].cpu(), label="Ray",
color="C3", linewidth=lw
)
if target_normal is not None:
ax[j].plot(
x, target_normal[i].cpu(), label="Normal",
color="C2", linewidth=lw
)
ax[j].plot(
x, target_pc[i].cpu(), label="Batch distance",
color="C0", linewidth=lw
)
# print("diffs", target_sdf[i].cpu() - gt_sdf)
if j == 2:
ax[j].set_xlabel("Distance along ray, d [m]", fontsize=24)
ax[j].set_yticks([0, 4, 8])
# ax[j].set_ylabel("Signed distance (m)", fontsize=21)
ax[j].tick_params(axis='both', which='major', labelsize=24)
# ax[j].set_xticks(fontsize=20)
# ax[j].set_yticks(fontsize=20)
# if j == 0:
# ax[j].legend(fontsize=20)
j += 1
fig.text(
0.05, 0.5, 'Signed distance [m]',
va='center', rotation='vertical', fontsize=24
)
# plt.tight_layout()
plt.show()
# intersection = dirs_W[i] * depth_sample[i] + origins[i]
# int_pc = trimesh.PointCloud(
# intersection[None, :].cpu(), [255, 0, 0, 255])
# scene.add_geometry(int_pc)
# pts = pc[i].detach().cpu().numpy()
# colormap_fn = sdf_util.get_colormap()
# col = colormap_fn.to_rgba(gt_sdf, alpha=1., bytes=False)
# tm_pc = trimesh.PointCloud(pts, col)
# scene.add_geometry(tm_pc)
scene.show()
def step(self):
start, end = start_timing()
depth_batch = self.frames.depth_batch
T_WC_batch = self.frames.T_WC_batch
norm_batch = self.frames.normal_batch if self.do_normal else None
if len(self.frames) > self.window_size and self.incremental:
idxs = self.select_keyframes()
# print("selected frame ids", self.frames.frame_id[idxs[:-1]])
else:
idxs = np.arange(T_WC_batch.shape[0])
self.active_idxs = idxs
depth_batch = depth_batch[idxs]
T_WC_select = T_WC_batch[idxs]
sample_pts = self.sample_points(
depth_batch, T_WC_select, norm_batch=norm_batch)
self.active_pixels = {
'indices_b': sample_pts['indices_b'],
'indices_h': sample_pts['indices_h'],
'indices_w': sample_pts['indices_w'],
}
total_loss, losses, active_loss_approx, frame_avg_loss = \
self.sdf_eval_and_loss(sample_pts, do_avg_loss=True)
self.frames.frame_avg_losses[idxs] = frame_avg_loss
total_loss.backward()
self.optimiser.step()
for param_group in self.optimiser.param_groups:
params = param_group["params"]
for param in params:
param.grad = None
# if self.do_active:
# sample_pts = self.sample_points(
# depth_batch, T_WC_select, norm_batch=norm_batch,
# active_loss_approx=active_loss_approx)
# loss_active, _, _, _ = \
# self.sdf_eval_and_loss(sample_pts, do_avg_loss=False)
# loss_active.backward()
# self.optimiser.step()
# for param_group in self.optimiser.param_groups:
# params = param_group["params"]
# for param in params: