forked from NVlabs/BundleSDF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nerf_runner.py
1543 lines (1287 loc) · 66.1 KB
/
nerf_runner.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) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import os, sys,copy,cv2,itertools,uuid,joblib,uuid
import shutil
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
import imageio,trimesh
import json
import pdb
import random
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import pickle
import matplotlib.pyplot as plt
from nerf_helpers import *
from Utils import *
def batchify(fn, chunk):
"""Constructs a version of 'fn' that applies to smaller batches.
"""
if chunk is None:
return fn
def ret(inputs):
return torch.cat([fn(inputs[i:i+chunk]) for i in range(0, inputs.shape[0], chunk)], 0)
return ret
def compute_near_far_and_filter_rays(cam_in_world,rays,cfg):
'''
@cam_in_world: in normalized space
@rays: (...,D) in camera
Return:
(-1,D+2) with near far
'''
D = rays.shape[-1]
rays = rays.reshape(-1,D)
dirs_unit = rays[:,:3]/np.linalg.norm(rays[:,:3],axis=-1).reshape(-1,1)
dirs = (cam_in_world[:3,:3]@rays[:,:3].T).T
origins = (cam_in_world@to_homo(np.zeros(dirs.shape)).T).T[:,:3]
bounds = np.array(cfg['bounding_box']).reshape(2,3)
tmin,tmax = ray_box_intersection_batch(origins,dirs,bounds)
tmin = tmin.data.cpu().numpy()
tmax = tmax.data.cpu().numpy()
ishit = tmin>=0
near = (dirs_unit*tmin.reshape(-1,1))[:,2]
far = (dirs_unit*tmax.reshape(-1,1))[:,2]
good_rays = rays[ishit]
near = near[ishit]
far = far[ishit]
near = np.abs(near)
far = np.abs(far)
good_rays = np.concatenate((good_rays,near.reshape(-1,1),far.reshape(-1,1)), axis=-1) #(N,8+2)
return good_rays
@torch.no_grad()
def sample_rays_uniform(N_samples,near,far,lindisp=False,perturb=True):
'''
@near: (N_ray,1)
'''
N_ray = near.shape[0]
t_vals = torch.linspace(0., 1., steps=N_samples, device=near.device).reshape(1,-1)
if not lindisp:
z_vals = near * (1.-t_vals) + far * (t_vals)
else:
z_vals = 1./(1./near * (1.-t_vals) + 1./far * (t_vals)) #(N_ray,N_sample)
if perturb > 0.:
mids = .5 * (z_vals[...,1:] + z_vals[...,:-1])
upper = torch.cat([mids, z_vals[...,-1:]], -1)
lower = torch.cat([z_vals[...,:1], mids], -1)
t_rand = torch.rand(z_vals.shape, device=far.device)
z_vals = lower + (upper - lower) * t_rand
z_vals = torch.clip(z_vals,near,far)
return z_vals.reshape(N_ray,N_samples)
class DataLoader:
def __init__(self,rays,batch_size):
self.rays = rays
self.batch_size = batch_size
self.pos = 0
self.ids = torch.randperm(len(self.rays))
def __next__(self):
if self.pos+self.batch_size<len(self.ids):
self.batch_ray_ids = self.ids[self.pos:self.pos+self.batch_size]
out = self.rays[self.batch_ray_ids]
self.pos += self.batch_size
return out.cuda()
self.ids = torch.randperm(len(self.rays))
self.pos = self.batch_size
self.batch_ray_ids = self.ids[:self.batch_size]
return self.rays[self.batch_ray_ids].cuda()
class NerfRunner:
def __init__(self,cfg,images,depths,masks,normal_maps,poses,K,_run=None,occ_masks=None,build_octree_pcd=None):
set_seed(0)
self.cfg = cfg
self.cfg['tv_loss_weight'] = eval(str(self.cfg['tv_loss_weight']))
self._run = _run
self.images = images
self.depths = depths
self.masks = masks
self.poses = poses
self.normal_maps = normal_maps
self.occ_masks = occ_masks
self.K = K.copy()
self.mesh = None
self.train_pose = False
self.N_iters = self.cfg['n_step']+1
self.build_octree_pts = np.asarray(build_octree_pcd.points).copy() # Make it pickable
down_scale_ratio = cfg['down_scale_ratio']
self.down_scale = np.ones((2),dtype=np.float32)
if down_scale_ratio!=1:
H,W = images[0].shape[:2]
############## No interpolatio nto keep consistency
down_scale_ratio = int(down_scale_ratio)
self.images = images[:, ::down_scale_ratio, ::down_scale_ratio]
self.depths = depths[:, ::down_scale_ratio, ::down_scale_ratio]
self.masks = masks[:, ::down_scale_ratio, ::down_scale_ratio]
if normal_maps is not None:
self.normal_maps = normal_maps[:, ::down_scale_ratio, ::down_scale_ratio]
if occ_masks is not None:
self.occ_masks = occ_masks[:, ::down_scale_ratio, ::down_scale_ratio]
self.H, self.W = self.images.shape[1:3]
self.cfg['dilate_mask_size'] = int(self.cfg['dilate_mask_size']//down_scale_ratio)
self.K[0] *= float(self.W)/W
self.K[1] *= float(self.H)/H
self.down_scale = np.array([float(self.W)/W, float(self.H)/H])
self.H, self.W = self.images[0].shape[:2]
self.octree_m = None
if self.cfg['use_octree']:
self.build_octree()
self.create_nerf()
self.create_optimizer()
self.amp_scaler = torch.cuda.amp.GradScaler(enabled=self.cfg['amp'])
self.global_step = 0
print("sc_factor",self.cfg['sc_factor'])
print("translation",self.cfg['translation'])
self.c2w_array = torch.tensor(poses).float().cuda()
self.best_models = None
self.best_loss = np.inf
rays_ = []
for i_mask in range(len(self.masks)):
rays = self.make_frame_rays(i_mask)
rays_.append(rays)
rays = np.concatenate(rays_, axis=0)
if self.cfg['denoise_depth_use_octree_cloud']:
logging.info("denoise cloud")
mask = (rays[:,self.ray_mask_slice]>0) & (rays[:,self.ray_depth_slice]<=self.cfg['far']*self.cfg['sc_factor'])
rays_dir = rays[mask][:,self.ray_dir_slice]
rays_depth = rays[mask][:,self.ray_depth_slice]
pts3d = rays_dir*rays_depth.reshape(-1,1)
frame_ids = rays[mask][:,self.ray_frame_id_slice].astype(int)
pts3d_w = (self.poses[frame_ids]@to_homo(pts3d)[...,None])[:,:3,0]
logging.info(f"Denoising rays based on octree cloud")
kdtree = cKDTree(self.build_octree_pts)
dists,indices = kdtree.query(pts3d_w,k=1,workers=-1)
bad_mask = dists>0.02*self.cfg['sc_factor']
bad_ids = np.arange(len(rays))[mask][bad_mask]
rays[bad_ids,self.ray_depth_slice] = BAD_DEPTH*self.cfg['sc_factor']
rays[bad_ids, self.ray_type_slice] = 1
rays = rays[rays[:,self.ray_type_slice]==0]
logging.info(f"bad_mask#={bad_mask.sum()}")
rays = torch.tensor(rays, dtype=torch.float).cuda()
self.rays = rays
print("rays",rays.shape)
self.data_loader = DataLoader(rays=self.rays, batch_size=self.cfg['N_rand'])
def create_nerf(self,device=torch.device("cuda")):
"""Instantiate NeRF's MLP model.
"""
models = {}
embed_fn, input_ch = get_embedder(self.cfg['multires'], self.cfg, i=self.cfg['i_embed'], octree_m=self.octree_m)
embed_fn = embed_fn.to(device)
models['embed_fn'] = embed_fn
input_ch_views = 0
embeddirs_fn = None
if self.cfg['use_viewdirs']:
embeddirs_fn, input_ch_views = get_embedder(self.cfg['multires_views'], self.cfg, i=self.cfg['i_embed_views'], octree_m=self.octree_m)
models['embeddirs_fn'] = embeddirs_fn
output_ch = 4
skips = [4]
model = NeRFSmall(num_layers=2,hidden_dim=64,geo_feat_dim=15,num_layers_color=3,hidden_dim_color=64,input_ch=input_ch, input_ch_views=input_ch_views+self.cfg['frame_features']).to(device)
model = model.to(device)
models['model'] = model
model_fine = None
if self.cfg['N_importance'] > 0:
if not self.cfg['share_coarse_fine']:
model_fine = NeRFSmall(num_layers=2,hidden_dim=64,geo_feat_dim=15,num_layers_color=3,hidden_dim_color=64,input_ch=input_ch, input_ch_views=input_ch_views).to(device)
models['model_fine'] = model_fine
# Create feature array
num_training_frames = len(self.images)
feature_array = None
if self.cfg['frame_features'] > 0:
feature_array = FeatureArray(num_training_frames, self.cfg['frame_features']).to(device)
models['feature_array'] = feature_array
# Create pose array
pose_array = None
if self.cfg['optimize_poses']:
pose_array = PoseArray(num_training_frames,max_trans=self.cfg['max_trans']*self.cfg['sc_factor'],max_rot=self.cfg['max_rot']).to(device)
models['pose_array'] = pose_array
self.models = models
def make_frame_rays(self,frame_id):
mask = self.masks[frame_id,...,0].copy()
rays = get_camera_rays_np(self.H, self.W, self.K) # [self.H, self.W, 3] We create rays frame-by-frame to save memory
rays = np.concatenate([rays, self.images[frame_id]], -1) # [H, W, 6]
rays = np.concatenate([rays, self.depths[frame_id]], -1) # [H, W, 7]
rays = np.concatenate([rays, self.masks[frame_id]>0], -1) # [H, W, 8]
if self.normal_maps is not None:
rays = np.concatenate([rays, self.normal_maps[frame_id]], -1) # [H, W, 11]
rays = np.concatenate([rays, frame_id*np.ones(self.depths[frame_id].shape)], -1) # [H, W, 12]
ray_types = np.zeros((self.H,self.W,1)) # 0 is good; 1 is invalid depth (uncertain)
invalid_depth = ((self.depths[frame_id,...,0]<self.cfg['near']*self.cfg['sc_factor']) | (self.depths[frame_id,...,0]>self.cfg['far']*self.cfg['sc_factor'])) & (mask>0)
ray_types[invalid_depth] = 1
rays = np.concatenate((rays,ray_types), axis=-1)
self.ray_dir_slice = [0,1,2]
self.ray_rgb_slice = [3,4,5]
self.ray_depth_slice = 6
self.ray_mask_slice = 7
if self.normal_maps is not None:
self.ray_normal_slice = [8,9,10]
self.ray_frame_id_slice = 11
self.ray_type_slice = 12
else:
self.ray_frame_id_slice = 8
self.ray_type_slice = 9
n = rays.shape[-1]
########## Option2: dilate
down_scale_ratio = int(self.cfg['down_scale_ratio'])
if frame_id==0: #!NOTE first frame ob mask is assumed perfect
kernel = np.ones((100, 100), np.uint8)
mask = cv2.dilate(mask, kernel, iterations=1)
if self.occ_masks is not None:
mask[self.occ_masks[frame_id]>0] = 0
else:
dilate = 60//down_scale_ratio
kernel = np.ones((dilate, dilate), np.uint8)
mask = cv2.dilate(mask, kernel, iterations=1)
if self.occ_masks is not None:
mask[self.occ_masks[frame_id]>0] = 0
if self.cfg['rays_valid_depth_only']:
mask[invalid_depth] = 0
vs,us = np.where(mask>0)
cur_rays = rays[vs,us].reshape(-1,n)
cur_rays = cur_rays[cur_rays[:,self.ray_type_slice]==0]
cur_rays = compute_near_far_and_filter_rays(self.poses[frame_id],cur_rays,self.cfg)
if self.normal_maps is not None:
self.ray_near_slice = 13
self.ray_far_slice = 14
else:
self.ray_near_slice = 10
self.ray_far_slice = 11
if self.cfg['use_octree']:
rays_o_world = (self.poses[frame_id]@to_homo(np.zeros((len(cur_rays),3))).T).T[:,:3]
rays_o_world = torch.from_numpy(rays_o_world).cuda().float()
rays_unit_d_cam = cur_rays[:,:3]/np.linalg.norm(cur_rays[:,:3],axis=-1).reshape(-1,1)
rays_d_world = (self.poses[frame_id][:3,:3]@rays_unit_d_cam.T).T
rays_d_world = torch.from_numpy(rays_d_world).cuda().float()
vox_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor']
level = int(np.floor(np.log2(2.0/vox_size)))
near,far,_,ray_depths_in_out = self.octree_m.ray_trace(rays_o_world,rays_d_world,level=level)
near = near.cpu().numpy()
valid = (near>0).reshape(-1)
cur_rays = cur_rays[valid]
return cur_rays
def compute_rays_z_in_out(self):
N_rays = len(self.rays)
rays_o = torch.zeros((N_rays,3), dtype=torch.float, device=self.rays.device)
rays_d = self.rays[:,self.ray_dir_slice]
viewdirs = rays_d/rays_d.norm(dim=-1,keepdim=True)
frame_ids = self.rays[:,self.ray_frame_id_slice].long()
tf = self.c2w_array[frame_ids.view(-1)]
if self.models['pose_array'] is not None:
tf = self.models['pose_array'].get_matrices(frame_ids)@tf
rays_o_w = transform_pts(rays_o,tf)
viewdirs_w = (tf[:,:3,:3]@viewdirs[:,None].permute(0,2,1))[:,:3,0]
voxel_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor']
level = int(np.floor(np.log2(2.0/voxel_size)))
near,far,_,depths_in_out = self.octree_m.ray_trace(rays_o_w,viewdirs_w,level=level,debug=0)
N_intersect = depths_in_out.shape[1]
########### Convert the time to Z
z_in_out = (depths_in_out.cuda()*torch.abs(viewdirs[...,2].view(N_rays,1,1))).cuda()
z_in_out = z_in_out.float()
depths = self.rays[:,self.ray_depth_slice].view(-1,1)
trunc = self.get_truncation()
valid = (depths>=self.cfg['near']*self.cfg['sc_factor']) & (depths<=self.cfg['far']*self.cfg['sc_factor']).expand(-1,N_intersect)
valid = valid & (z_in_out>0).all(dim=-1) #(N_ray, N_intersect)
z_in_out[valid] = torch.clip(z_in_out[valid],
min=torch.zeros_like(z_in_out[valid]),
max=torch.ones_like(z_in_out[valid])*(depths.reshape(-1,1,1).expand(-1,N_intersect,2)[valid]+trunc))
self.z_in_out = z_in_out
def add_new_frames(self,images,depths,masks,normal_maps,poses,occ_masks=None, new_pcd=None, reuse_weights=False):
'''Add new frames and continue training
@images: (N,H,W,3) new images
@poses: All frames, they need to reset
'''
prev_n_image = len(self.images)
down_scale_ratio = int(self.cfg['down_scale_ratio'])
images = images[:, ::down_scale_ratio, ::down_scale_ratio]
depths = depths[:, ::down_scale_ratio, ::down_scale_ratio]
masks = masks[:, ::down_scale_ratio, ::down_scale_ratio]
if normal_maps is not None:
normal_maps = normal_maps[:, ::down_scale_ratio, ::down_scale_ratio]
self.normal_maps = np.concatenate((self.normal_maps, normal_maps), axis=0)
if occ_masks is not None:
occ_masks = occ_masks[:, ::down_scale_ratio, ::down_scale_ratio]
self.occ_masks = np.concatenate((self.occ_masks, occ_masks), axis=0)
self.images = np.concatenate((self.images, images), axis=0)
self.depths = np.concatenate((self.depths, depths), axis=0)
self.masks = np.concatenate((self.masks, masks), axis=0)
self.poses = poses.copy()
self.c2w_array = torch.tensor(poses, dtype=torch.float).cuda()
if self.cfg['use_octree']:
pcd = new_pcd.voxel_down_sample(0.005)
self.build_octree_pts = np.asarray(pcd.points).copy()
self.build_octree()
if not reuse_weights:
self.create_nerf()
else:
########### Add new frame weights
if self.cfg['frame_features'] > 0:
feature_array = FeatureArray(len(self.images), self.cfg['frame_features']).to(self.rays.device)
if reuse_weights:
for i in range(prev_n_image):
feature_array.data.data[i] = self.models['feature_array'].data.data[i].detach().clone()
self.models['feature_array'] = feature_array
########!NOTE Dont need to copy delta poses, they are new
if self.cfg['optimize_poses']:
pose_array = PoseArray(len(self.images),max_trans=self.cfg['max_trans']*self.cfg['sc_factor'],max_rot=self.cfg['max_rot']).to(self.rays.device)
self.models['pose_array'] = pose_array
self.create_optimizer()
self.global_step = 0
self.best_models = None
self.best_loss = np.inf
if not self.cfg['no_batching']:
print("Using mask")
rays_ = []
for i_mask in range(prev_n_image, len(self.masks)):
rays = self.make_frame_rays(i_mask)
rays_.append(rays)
rays = np.concatenate(rays_, axis=0)
if self.cfg['denoise_depth_use_octree_cloud']:
logging.info("denoise cloud")
mask = (rays[:,self.ray_mask_slice]>0) & (rays[:,self.ray_depth_slice]<=self.cfg['far']*self.cfg['sc_factor'])
rays_dir = rays[mask][:,self.ray_dir_slice]
rays_depth = rays[mask][:,self.ray_depth_slice]
pts3d = rays_dir*rays_depth.reshape(-1,1)
frame_ids = rays[mask][:,self.ray_frame_id_slice].astype(int)
pts3d_w = (self.poses[frame_ids]@to_homo(pts3d)[...,None])[:,:3,0]
logging.info(f"Denoising rays based on octree cloud")
kdtree = cKDTree(self.build_octree_pts)
dists,indices = kdtree.query(pts3d_w,k=1,workers=-1)
bad_mask = dists>0.02*self.cfg['sc_factor']
bad_ids = np.arange(len(rays))[mask][bad_mask]
rays[bad_ids,self.ray_depth_slice] = BAD_DEPTH*self.cfg['sc_factor']
rays[bad_ids, self.ray_type_slice] = 1
rays = rays[rays[:,self.ray_type_slice]==0]
logging.info(f"bad_mask#={bad_mask.sum()}")
rays = torch.tensor(rays, device=self.rays.device, dtype=torch.float)
self.rays = torch.cat((self.rays,rays), dim=0).cpu()
self.data_loader = DataLoader(rays=self.rays, batch_size=self.cfg['N_rand'])
def build_octree(self):
if self.cfg['save_octree_clouds']:
dir = f"{self.cfg['save_dir']}/build_octree_cloud.ply"
pcd = toOpen3dCloud(self.build_octree_pts)
o3d.io.write_point_cloud(dir,pcd)
if self._run is not None:
self._run.add_artifact(dir)
pts = torch.tensor(self.build_octree_pts).cuda().float() # Must be within [-1,1]
octree_smallest_voxel_size = self.cfg['octree_smallest_voxel_size']*self.cfg['sc_factor']
finest_n_voxels = 2.0/octree_smallest_voxel_size
max_level = int(np.ceil(np.log2(finest_n_voxels)))
octree_smallest_voxel_size = 2.0/(2**max_level)
#################### Dilate
dilate_radius = int(np.ceil(self.cfg['octree_dilate_size']/self.cfg['octree_smallest_voxel_size']))
dilate_radius = max(1, dilate_radius)
logging.info(f"Octree voxel dilate_radius:{dilate_radius}")
shifts = []
for dx in [-1,0,1]:
for dy in [-1,0,1]:
for dz in [-1,0,1]:
shifts.append([dx,dy,dz])
shifts = torch.tensor(shifts).cuda().long() # (27,3)
coords = torch.floor((pts+1)/octree_smallest_voxel_size).long() #(N,3)
dilated_coords = coords.detach().clone()
for iter in range(dilate_radius):
dilated_coords = (dilated_coords[None].expand(shifts.shape[0],-1,-1) + shifts[:,None]).reshape(-1,3)
dilated_coords = torch.unique(dilated_coords,dim=0)
pts = (dilated_coords+0.5) * octree_smallest_voxel_size - 1
pts = torch.clip(pts,-1,1)
if self.cfg['save_octree_clouds']:
pcd = toOpen3dCloud(pts.data.cpu().numpy())
dir = f"{self.cfg['save_dir']}/build_octree_cloud_dilated.ply"
o3d.io.write_point_cloud(dir,pcd)
if self._run is not None:
self._run.add_artifact(dir)
####################
assert pts.min()>=-1 and pts.max()<=1
self.octree_m = OctreeManager(pts, max_level)
if self.cfg['save_octree_clouds']:
dir = f"{self.cfg['save_dir']}/octree_boxes_max_level.ply"
self.octree_m.draw_boxes(level=max_level,outfile=dir)
if self._run is not None:
self._run.add_artifact(dir)
vox_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor']
level = int(np.floor(np.log2(2.0/vox_size)))
if self.cfg['save_octree_clouds']:
dir = f"{self.cfg['save_dir']}/octree_boxes_ray_tracing_level.ply"
self.octree_m.draw_boxes(level=level,outfile=dir)
if self._run is not None:
self._run.add_artifact(dir)
def create_optimizer(self):
params = []
for k in self.models:
if self.models[k] is not None and k!='pose_array':
params += list(self.models[k].parameters())
param_groups = [{'name':'basic', 'params':params, 'lr':self.cfg['lrate']}]
if self.models['pose_array'] is not None:
param_groups.append({'name':'pose_array', 'params':self.models['pose_array'].parameters(), 'lr':self.cfg['lrate_pose']})
self.optimizer = torch.optim.Adam(param_groups, betas=(0.9, 0.999),weight_decay=0,eps=1e-15)
self.param_groups_init = copy.deepcopy(self.optimizer.param_groups)
def copy_from(self,other,ignore=[]):
'''
@other: another runner instance
'''
n_frames_other = len(other.images)
for k in self.models.keys():
if k in ignore:
continue
print(f"Copy {k}")
if self.models[k] is not None:
if k in ['pose_array','feature_array']:
self.models[k].data.data = torch.cat([other.models[k].data[:n_frames_other].detach(),self.models[k].data[n_frames_other:].detach()], dim=0)
self.models[k].data.requires_grad = True
else:
tmp = other.models[k].state_dict()
self.models[k].load_state_dict(tmp)
self.create_optimizer() # Reset optimizer's params
def load_weights(self,ckpt_path):
print('Reloading from', ckpt_path)
ckpt = torch.load(ckpt_path)
print("ckpt keys: ",ckpt.keys())
self.models['model'].load_state_dict(ckpt['model'])
if self.models['model_fine'] is not None:
self.models['model_fine'].load_state_dict(ckpt['model_fine'])
if self.models['embed_fn'] is not None:
self.models['embed_fn'].load_state_dict(ckpt['embed_fn'])
if self.models['embeddirs_fn'] is not None:
self.models['embeddirs_fn'].load_state_dict(ckpt['embeddirs_fn'])
if self.models['feature_array'] is not None:
self.models['feature_array'].load_state_dict(ckpt['feature_array'])
if self.models['pose_array'] is not None:
self.models['pose_array'].load_state_dict(ckpt['pose_array'])
if 'octree' in ckpt:
self.octree_m = OctreeManager(octree=ckpt['octree'])
self.optimizer.load_state_dict(ckpt['optimizer'])
def save_weights(self,out_file,models):
data = {
'global_step': self.global_step,
'model': models['model'].state_dict(),
'optimizer': self.optimizer.state_dict(),
}
if 'model_fine' in models and models['model_fine'] is not None:
data['model_fine'] = models['model_fine'].state_dict()
if models['embed_fn'] is not None:
data['embed_fn'] = models['embed_fn'].state_dict()
if models['embeddirs_fn'] is not None:
data['embeddirs_fn'] = models['embeddirs_fn'].state_dict()
if self.cfg['optimize_poses']>0:
data['pose_array'] = models['pose_array'].state_dict()
if self.cfg['frame_features'] > 0:
data['feature_array'] = models['feature_array'].state_dict()
if self.octree_m is not None:
data['octree'] = self.octree_m.octree
dir = out_file
torch.save(data,dir)
print('Saved checkpoints at', dir)
if self._run is not None:
self._run.add_artifact(dir)
dir1 = copy.deepcopy(dir)
dir = f'{os.path.dirname(out_file)}/model_latest.pth'
if dir1!=dir:
os.system(f'cp {dir1} {dir}')
if self._run is not None:
self._run.add_artifact(dir)
def schedule_lr(self):
for i,param_group in enumerate(self.optimizer.param_groups):
init_lr = self.param_groups_init[i]['lr']
new_lrate = init_lr * (self.cfg['decay_rate'] ** (float(self.global_step) / self.N_iters))
param_group['lr'] = new_lrate
def render_images(self,img_i,cur_rays=None):
if cur_rays is None:
frame_ids = self.rays[:, self.ray_frame_id_slice].cuda()
cur_rays = self.rays[frame_ids==img_i].cuda()
gt_depth = cur_rays[:,self.ray_depth_slice]
gt_rgb = cur_rays[:,self.ray_rgb_slice].cpu()
ray_type = cur_rays[:,self.ray_type_slice].data.cpu().numpy()
near = cur_rays[:,self.ray_near_slice]
far = cur_rays[:,self.ray_far_slice]
ray_ids = torch.arange(len(self.rays), device=cur_rays.device)[frame_ids==img_i].long()
ids = img_i * torch.ones([len(cur_rays), 1], device=cur_rays.device).long()
ori_chunk = self.cfg['chunk']
self.cfg['chunk'] = copy.deepcopy(self.cfg['N_rand'])
with torch.no_grad():
rgb, extras = self.render(rays=cur_rays, ray_ids=ray_ids, frame_ids=ids,lindisp=False,perturb=False,raw_noise_std=0, depth=gt_depth, near=near, far=far)
self.cfg['chunk'] = ori_chunk
sdf = extras['raw'][...,-1]
z_vals = extras['z_vals']
signs = sdf[:, 1:] * sdf[:, :-1]
empty_rays = (signs>0).all(dim=-1)
mask = signs<0
inds = torch.argmax(mask.float(), axis=1)
inds = inds[..., None]
depth = torch.gather(z_vals,dim=1,index=inds)
depth[empty_rays] = self.cfg['far']*self.cfg['sc_factor']
depth = depth[..., None].data.cpu().numpy()
rgb = rgb.data.cpu().numpy()
rgb_full = np.zeros((self.H,self.W,3),dtype=float)
depth_full = np.zeros((self.H,self.W),dtype=float)
ray_mask_full = np.zeros((self.H,self.W,3),dtype=np.uint8)
X = cur_rays[:,self.ray_dir_slice].data.cpu().numpy()
X[:,[1,2]] = -X[:,[1,2]]
projected = ([email protected]).T
uvs = projected/projected[:,2].reshape(-1,1)
uvs = uvs.round().astype(int)
uvs_good = uvs[ray_type==0]
ray_mask_full[uvs_good[:,1],uvs_good[:,0]] = [255,0,0]
uvs_uncertain = uvs[ray_type==1]
ray_mask_full[uvs_uncertain[:,1],uvs_uncertain[:,0]] = [0,255,0]
rgb_full[uvs[:,1],uvs[:,0]] = rgb.reshape(-1,3)
depth_full[uvs[:,1],uvs[:,0]] = depth.reshape(-1)
gt_rgb_full = np.zeros((self.H,self.W,3),dtype=float)
gt_rgb_full[uvs[:,1],uvs[:,0]] = gt_rgb.reshape(-1,3).data.cpu().numpy()
gt_depth_full = np.zeros((self.H,self.W),dtype=float)
gt_depth_full[uvs[:,1],uvs[:,0]] = gt_depth.reshape(-1).data.cpu().numpy()
return rgb_full, depth_full, ray_mask_full, gt_rgb_full, gt_depth_full, extras
def get_gradients(self):
if self.models['pose_array'] is not None:
max_pose_grad = torch.abs(self.models['pose_array'].data.grad).max()
max_embed_grad = 0
for embed in self.models['embed_fn'].embeddings:
max_embed_grad = max(max_embed_grad,torch.abs(embed.weight.grad).max())
if self.models['feature_array'] is not None:
max_feature_grad = torch.abs(self.models['feature_array'].data.grad).max()
return max_pose_grad, max_embed_grad, max_feature_grad
def gradient_clip(self):
if self.cfg['amp']:
self.amp_scaler.unscale_(self.optimizer)
params = []
for pg in self.optimizer.param_groups:
for p in pg['params']:
params.append(p)
error_if_nonfinite = not self.cfg['amp']
torch.nn.utils.clip_grad_norm_(params,max_norm=self.cfg['gradient_max_norm'],norm_type='inf',error_if_nonfinite=error_if_nonfinite)
if self.models['pose_array'] is not None:
torch.nn.utils.clip_grad_norm_(self.models['pose_array'].data,max_norm=self.cfg['gradient_pose_max_norm'],norm_type='inf',error_if_nonfinite=error_if_nonfinite)
def get_truncation(self):
'''Annearl truncation over training
'''
if self.cfg['trunc_decay_type']=='linear':
truncation = self.cfg['trunc_start'] - (self.cfg['trunc_start']-self.cfg['trunc']) * float(self.global_step)/self.cfg['n_step']
elif self.cfg['trunc_decay_type']=='exp':
lamb = np.log(self.cfg['trunc']/self.cfg['trunc_start']) / (self.cfg['n_step']/4)
truncation = self.cfg['trunc_start']*np.exp(self.global_step*lamb)
truncation = max(truncation,self.cfg['trunc'])
else:
truncation = self.cfg['trunc']
truncation *= self.cfg['sc_factor']
return truncation
def train_loop(self,batch):
target_s = batch[:, self.ray_rgb_slice] # Color (N,3)
target_d = batch[:, self.ray_depth_slice] # Normalized scale (N)
target_mask = batch[:,self.ray_mask_slice].bool().reshape(-1)
frame_ids = batch[:,self.ray_frame_id_slice]
rgb, extras = self.render(rays=batch, ray_ids=self.data_loader.batch_ray_ids, frame_ids=frame_ids,depth=target_d,lindisp=False,perturb=True,raw_noise_std=self.cfg['raw_noise_std'], near=batch[:,self.ray_near_slice], far=batch[:,self.ray_far_slice], get_normals=False)
valid_samples = extras['valid_samples'] #(N_ray,N_samples)
z_vals = extras['z_vals'] # [N_rand, N_samples + N_importance]
sdf = extras['raw'][..., -1]
N_rays,N_samples = sdf.shape[:2]
valid_rays = (valid_samples>0).any(dim=-1).bool().reshape(N_rays) & (batch[:,self.ray_type_slice]==0)
ray_type = batch[:,self.ray_type_slice].reshape(-1)
ray_weights = torch.ones((N_rays), device=rgb.device, dtype=torch.float32)
ray_weights[(frame_ids==0).view(-1)] = self.cfg['first_frame_weight']
ray_weights = ray_weights*valid_rays.view(-1)
sample_weights = ray_weights.view(N_rays,1).expand(-1,N_samples) * valid_samples
img_loss = (((rgb-target_s)**2 * ray_weights.view(-1,1))).mean()
rgb_loss = self.cfg['rgb_weight'] * img_loss
loss = rgb_loss
rgb0_loss = torch.tensor(0)
if 'rgb0' in extras:
img_loss0 = (((extras['rgb0']-target_s)**2 * ray_weights.view(-1,1))).mean()
rgb0_loss = img_loss0*self.cfg['rgb_weight']
loss += rgb0_loss
depth_loss = torch.tensor(0)
depth_loss0 = torch.tensor(0)
if self.cfg['depth_weight']>0:
signs = sdf[:, 1:] * sdf[:, :-1]
mask = signs<0
inds = torch.argmax(mask.float(), axis=1)
inds = inds[..., None]
z_min = torch.gather(z_vals,dim=1,index=inds)
weights = ray_weights * (depth<=self.cfg['far']*self.cfg['sc_factor']) * (mask.any(dim=-1))
depth_loss = ((z_min*weights-depth.view(-1,1)*weights)**2).mean() * self.cfg['depth_weight']
loss = loss+depth_loss
truncation = self.get_truncation()
sample_weights[ray_type==1] = 0
fs_loss, sdf_loss,front_mask,sdf_mask = get_sdf_loss(z_vals, target_d.reshape(-1,1).expand(-1,N_samples), sdf, truncation, self.cfg,return_mask=True, sample_weights=sample_weights, rays_d=batch[:,self.ray_dir_slice])
fs_loss = fs_loss*self.cfg['fs_weight']
sdf_loss = sdf_loss*self.cfg['trunc_weight']
loss = loss + fs_loss + sdf_loss
fs_rgb_loss = torch.tensor(0)
if self.cfg['fs_rgb_weight']>0:
fs_rgb_loss = ((((torch.sigmoid(extras['raw'][...,:3])-1)*front_mask[...,None])**2) * sample_weights[...,None]).mean()
loss += fs_rgb_loss*self.cfg['fs_rgb_weight']
eikonal_loss = torch.tensor(0)
if self.cfg['eikonal_weight']>0:
nerf_normals = extras['normals']
eikonal_loss = ((torch.norm(nerf_normals[sdf<1], dim=-1)-1)**2).mean() * self.cfg['eikonal_weight']
loss += eikonal_loss
point_cloud_loss = torch.tensor(0)
point_cloud_normal_loss = torch.tensor(0)
reg_features = torch.tensor(0)
if self.models['feature_array'] is not None:
reg_features = self.cfg['feature_reg_weight'] * (self.models['feature_array'].data**2).mean()
loss += reg_features
if self.models['pose_array'] is not None:
pose_array = self.models['pose_array']
pose_reg = self.cfg['pose_reg_weight']*pose_array.data[1:].norm()
loss += pose_reg
variation_loss = torch.tensor(0)
self.optimizer.zero_grad()
self.amp_scaler.scale(loss).backward()
self.amp_scaler.step(self.optimizer)
self.amp_scaler.update()
if self.global_step%10==0 and self.global_step>0:
self.schedule_lr()
if self.global_step%self.cfg['i_weights']==0 and self.global_step>0:
self.save_weights(out_file=os.path.join(self.cfg['save_dir'], f'model_latest.pth'), models=self.models)
if self.global_step % self.cfg['i_img'] == 0 and self.global_step>0:
ids = torch.unique(self.rays[:, self.ray_frame_id_slice]).data.cpu().numpy().astype(int).tolist()
ids.sort()
last = ids[-1]
ids = ids[::max(1,len(ids)//5)]
if last not in ids:
ids.append(last)
canvas = []
for frame_idx in ids:
rgb, depth, ray_mask, gt_rgb, gt_depth, _ = self.render_images(frame_idx)
mask_vis = (rgb*255*0.2 + ray_mask*0.8).astype(np.uint8)
mask_vis = np.clip(mask_vis,0,255)
rgb = np.concatenate((rgb,gt_rgb),axis=1)
far = self.cfg['far']*self.cfg['sc_factor']
gt_depth = np.clip(gt_depth, self.cfg['near']*self.cfg['sc_factor'], far)
depth_vis = np.concatenate((to8b(depth / far), to8b(gt_depth / far)), axis=1)
depth_vis = np.tile(depth_vis[...,None],(1,1,3))
row = np.concatenate((to8b(rgb),depth_vis,mask_vis),axis=1)
canvas.append(row)
canvas = np.concatenate(canvas,axis=0).astype(np.uint8)
dir = f"{self.cfg['save_dir']}/image_step_{self.global_step:07d}.png"
imageio.imwrite(dir,canvas)
if self._run is not None:
self._run.add_artifact(dir)
if self.global_step%self.cfg['i_print']==0:
msg = f"Iter: {self.global_step}, valid_samples: {valid_samples.sum()}/{torch.numel(valid_samples)}, valid_rays: {valid_rays.sum()}/{torch.numel(valid_rays)}, "
metrics = {
'loss':loss.item(),
'rgb_loss':rgb_loss.item(),
'rgb0_loss':rgb0_loss.item(),
'fs_rgb_loss': fs_rgb_loss.item(),
'depth_loss':depth_loss.item(),
'depth_loss0':depth_loss0.item(),
'fs_loss':fs_loss.item(),
'point_cloud_loss': point_cloud_loss.item(),
'point_cloud_normal_loss':point_cloud_normal_loss.item(),
'sdf_loss':sdf_loss.item(),
'eikonal_loss': eikonal_loss.item(),
"variation_loss": variation_loss.item(),
'truncation(meter)': self.get_truncation()/self.cfg['sc_factor'],
}
if self.models['pose_array'] is not None:
metrics['pose_reg'] = pose_reg.item()
if 'feature_array' in self.models:
metrics['reg_features'] = reg_features.item()
for k in metrics.keys():
msg += f"{k}: {metrics[k]:.7f}, "
msg += "\n"
logging.info(msg)
if self._run is not None:
for k in metrics.keys():
self._run.log_scalar(k,metrics[k],self.global_step)
if self.global_step % self.cfg['i_mesh'] == 0 and self.global_step > 0:
with torch.no_grad():
model = self.models['model_fine'] if self.models['model_fine'] is not None else self.models['model']
mesh = self.extract_mesh(isolevel=0, voxel_size=self.cfg['mesh_resolution'])
self.mesh = copy.deepcopy(mesh)
if mesh is not None:
dir = os.path.join(self.cfg['save_dir'], f'step_{self.global_step:07d}_mesh_normalized_space.obj')
mesh.export(dir)
if self._run is not None:
self._run.add_artifact(dir)
dir = os.path.join(self.cfg['save_dir'], f'step_{self.global_step:07d}_mesh_real_world.obj')
if self.models['pose_array'] is not None:
_,offset = get_optimized_poses_in_real_world(self.poses,self.models['pose_array'],translation=self.cfg['translation'],sc_factor=self.cfg['sc_factor'])
else:
offset = np.eye(4)
mesh = mesh_to_real_world(mesh,offset,translation=self.cfg['translation'],sc_factor=self.cfg['sc_factor'])
mesh.export(dir)
if self._run is not None:
self._run.add_artifact(dir)
if self.global_step % self.cfg['i_pose'] == 0 and self.global_step > 0:
if self.models['pose_array'] is not None:
optimized_poses,offset = get_optimized_poses_in_real_world(self.poses,self.models['pose_array'],translation=self.cfg['translation'],sc_factor=self.cfg['sc_factor'])
else:
optimized_poses = self.poses
dir = os.path.join(self.cfg['save_dir'], f'step_{self.global_step:07d}_optimized_poses.txt')
np.savetxt(dir,optimized_poses.reshape(-1,4))
if self._run is not None:
self._run.add_artifact(dir)
def train(self):
set_seed(0)
for iter in range(self.N_iters):
if iter%(self.N_iters//10)==0:
logging.info(f'train progress {iter}/{self.N_iters}')
batch = next(self.data_loader)
self.train_loop(batch.cuda())
self.global_step += 1
def make_key_ray_ids(self):
with gzip.open(f"{self.cfg['datadir']}/matches_all.pkl",'rb') as ff:
matches_table = pickle.load(ff)
key_ray_ids = []
kpts_vox_ids = []
match_ray_ids = []
vox_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor']
level = int(np.floor(np.log2(2.0/vox_size)))
for k in matches_table.keys():
if len(matches_table[k])==0:
continue
idA,idB = k
matches_table[k] = np.array(matches_table[k]) #(N,4)
matches_table[k] = matches_table[k]/np.tile(self.down_scale.reshape(1,2),(1,2))
def dirs_to_uvs(ray_dirs):
ray_dirs[:,[1,2]] *= -1
projected = (self.K@(ray_dirs/ray_dirs[:,2:3]).T).T
uvs = projected[:,:2]
return uvs
def kpts_to_ray_ids(kpts,id,dilate=True):
cur_frame_mask = (self.rays[:,self.ray_frame_id_slice]==id).data.cpu().numpy()
cur_rays = self.rays[cur_frame_mask].data.cpu().numpy()
uvs = dirs_to_uvs(cur_rays[:,:3]) #(N,2)
kdtree = cKDTree(uvs)
if dilate:
steps = np.array(list(itertools.product(np.arange(-5,6),repeat=2))).reshape(-1,2)
kpts = (kpts[None]+steps.reshape(-1,1,2)).reshape(-1,2)
dists,indices = kdtree.query(kpts,k=1,workers=-1)
return np.arange(len(self.rays))[cur_frame_mask][indices.reshape(-1)]
def rays_to_pts_world(rays):
depth = rays[:,self.ray_depth_slice].data.cpu().numpy()
dirs = rays[:,self.ray_dir_slice].data.cpu().numpy()
pts = dirs*depth.reshape(-1,1)
frame_ids = rays[:,self.ray_frame_id_slice].data.cpu().numpy().astype(int)
pts = (self.poses[frame_ids]@to_homo(pts)[...,None])[:,:3,0]
return pts
def rays_to_vox_ids(rays):
frame_ids = rays[:,self.ray_frame_id_slice].long()
rays_o = torch.zeros((len(rays),3)).float().cuda()
poses = self.c2w_array[frame_ids]
rays_o_w = (poses@to_homo_torch(rays_o)[...,None])[:,:3,0]
rays_dir = rays[:,self.ray_dir_slice]
rays_dir_w = (poses[...,:3,:3]@rays_dir[...,None])[...,0]
rays_near, rays_far, rays_pid, ray_depths_in_out = self.octree_m.ray_trace(rays_o_w,rays_dir_w,level=level)
return rays_pid
rayA_ids = kpts_to_ray_ids(matches_table[k][:,:2],idA)
rayB_ids = kpts_to_ray_ids(matches_table[k][:,2:4],idB)
key_ray_ids.append(rayA_ids)
key_ray_ids.append(rayB_ids)
match_ray_ids.append(np.stack((rayA_ids,rayB_ids),axis=-1).reshape(-1,2))
key_ray_ids = np.concatenate(key_ray_ids,axis=0).reshape(-1)
key_ray_ids = np.unique(key_ray_ids)
self.key_ray_ids = key_ray_ids
self.match_ray_ids = torch.tensor(np.concatenate(match_ray_ids,axis=0)).long()
def train_BA(self):
for self.global_step in range(200):
rayA = self.rays[self.match_ray_ids[:,0]]
rayB = self.rays[self.match_ray_ids[:,1]]
valid = (rayA[:,self.ray_depth_slice]<=self.cfg['far']*self.cfg['sc_factor']) & (rayB[:,self.ray_depth_slice]<=self.cfg['far']*self.cfg['sc_factor'])
rayA = rayA[valid]
rayB = rayB[valid]
def rays_to_pts_world(rays):
depth = rays[:,self.ray_depth_slice]
dirs = rays[:,self.ray_dir_slice]
frame_ids = rays[:,self.ray_frame_id_slice].long()
rgb = rays[:,self.ray_rgb_slice]
pts = dirs*depth.reshape(-1,1)
tf = torch.eye(4).reshape(1,4,4).expand(len(frame_ids),-1,-1).float().to(rays.device) #(N_ray,4,4)
if self.c2w_array is not None:
tf = self.c2w_array[frame_ids]@tf
if self.models['pose_array'] is not None:
tf = self.models['pose_array'].get_matrices(frame_ids)@tf
pts = (tf@to_homo_torch(pts)[...,None])[:,:3,0]
return pts,rgb
ptsA,rgbA = rays_to_pts_world(rayA)
ptsB,rgbB = rays_to_pts_world(rayB)
loss = (ptsA-ptsB).norm(dim=-1)
loss = loss[loss<0.02*self.cfg['sc_factor']].mean()
print(f'self.global_step: {self.global_step}, loss: {loss.item()}')
self.optimizer.zero_grad()
self.amp_scaler.scale(loss).backward()
self.amp_scaler.step(self.optimizer)
self.amp_scaler.update()
if self.global_step % self.cfg['i_pose'] == 0 and self.global_step > 0:
if self.models['pose_array'] is not None:
optimized_poses,offset = get_optimized_poses_in_real_world(self.poses,self.models['pose_array'],translation=self.cfg['translation'],sc_factor=self.cfg['sc_factor'])
else:
optimized_poses = self.poses
dir = os.path.join(self.cfg['save_dir'], f'step_{self.global_step}_optimized_poses.txt')
np.savetxt(dir,optimized_poses.reshape(-1,4))
if self._run is not None:
self._run.add_artifact(dir)
@torch.no_grad()
def sample_rays_uniform_occupied_voxels(self,ray_ids,rays_d,depths_in_out,lindisp=False,perturb=False, depths=None, N_samples=None):
'''We first connect the discontinuous boxes for each ray and treat it as uniform sample, then we disconnect into correct boxes
@rays_d: (N_ray,3)
@depths_in_out: Padded tensor each has (N_ray,N_intersect,2) tensor, the time travel of each ray
'''
N_rays = rays_d.shape[0]
N_intersect = depths_in_out.shape[1]
dirs = rays_d/rays_d.norm(dim=-1,keepdim=True)
########### Convert the time to Z
z_in_out = depths_in_out.cuda()*torch.abs(dirs[...,2]).reshape(N_rays,1,1).cuda()
if depths is not None:
depths = depths.reshape(-1,1)
trunc = self.get_truncation()
valid = (depths>=self.cfg['near']*self.cfg['sc_factor']) & (depths<=self.cfg['far']*self.cfg['sc_factor']).expand(-1,N_intersect)
valid = valid & (z_in_out>0).all(dim=-1) #(N_ray, N_intersect)
z_in_out[valid] = torch.clip(z_in_out[valid],
min=torch.zeros_like(z_in_out[valid]),
max=torch.ones_like(z_in_out[valid])*(depths.reshape(-1,1,1).expand(-1,N_intersect,2)[valid]+trunc))