-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
2979 lines (2470 loc) · 150 KB
/
main.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
import sys
import os
#os.environ['TCNN_CUDA_ARCHITECTURES'] = '86'
# Package imports
import torch
import torch.optim as optim
import numpy as np
import random
import torch.nn.functional as F
import argparse
import shutil
import json
from torch.utils.data import DataLoader
from tqdm import tqdm
torch.multiprocessing.set_sharing_strategy('file_system')
import imageio
import pypose as pp
# Local imports
import config
from datasets.dataset import get_dataset
from utils import coordinates, extract_mesh, colormap_image
from tools.eval_ate import pose_evaluation, save_pose_as_kitti_evo, align_and_est_scale
from optimization.utils import at_to_transform_matrix, qt_to_transform_matrix, matrix_to_axis_angle, matrix_to_quaternion
# spline
from spline.spline import SE3_to_se3, se3_to_SE3, se3_to_SE3_m44
from datasets.dataset import get_event_chunk
# from gaussian_splatting.arguments import ModelParams, PipelineParams, OptimizationParams
from datasets.utils import get_camera_rays
from datasets.dataset import get_event_chunk
import torchgeometry as tgm
from depth_warper import depth_warp
import cv2
import cv2 as cv
from scipy import stats
from kornia.filters import median_blur
from median_pool import MedianPool2d
from utils import render_ev_accumulation
from spline.spline_functor import linear_interpolation, cubic_bspline_interpolation
from torchvision.transforms import v2
from colormaps import apply_colormap
# from img_evaluation import compute_img_metric
from tikhonov_regularizor import tikhonov_regularization
from loss_utils import compute_white_balance_loss, compute_ssim_loss
# gsplat
from typing import Dict, List, Optional, Tuple
from utils import knn, rgb_to_sh, set_random_seed
import math
from gsplat.rendering import rasterization
from gsplat.strategy import DefaultStrategy, add_new_gs
from dataclasses import dataclass, field
# import tyro
from torch import Tensor
from plyfile import PlyData, PlyElement
from utils import BasicPointCloud
from utils import SH2RGB
import numba
log_eps = 1e-3
log = lambda x: torch.log(x + log_eps)
img2mse = lambda x, y: torch.mean((x - y) ** 2)
@numba.jit()
def accumulate_events(xs, ys, ts, ps, out, resolution_level, polarity_offset):
for i in range(len(xs)):
x, y, t, p = xs[i], ys[i], ts[i], ps[i]
out[y // resolution_level, x // resolution_level] += p+polarity_offset
def get_row_major_sliced_ray_bundle(rays_o, rays_d, start_idx, end_idx):
rays_o = torch.flatten(rays_o, start_dim=0, end_dim=1)[start_idx:end_idx]
rays_d = torch.flatten(rays_d, start_dim=0, end_dim=1)[start_idx:end_idx]
return rays_o, rays_d
to8b = lambda x: (255 * np.clip(x, 0, 1)).astype(np.uint8)
def lin_log(color, linlog_thres=1):
"""
Input:
:color torch.Tensor of (N_rand_events, 1 or 3). 1 if use_luma, else 3 (rgb).
We pass rgb here, if we want to treat r,g,b separately in the loss (each pixel must obey event constraint).
"""
# Compute the required slope for linear region (below luma_thres)
# we need natural log (v2e writes ln and "it comes from exponential relation")
lin_slope = np.log(linlog_thres) / linlog_thres
# Peform linear-map for smaller thres, and log-mapping for above thresh
lin_log_rgb = torch.where(color < linlog_thres, lin_slope * color, torch.log(color))
return lin_log_rgb
def save_np_image(np_image, path_to_save):
np_image = to8b(np_image)
imageio.imwrite(path_to_save, np_image)
def save_event_np_image(event_map, path_to_save):
H = event_map.shape[0]
W = event_map.shape[1]
event_map = render_ev_accumulation(event_map, H, W)
save_np_image(event_map, path_to_save)
@dataclass
class Config:
# Disable viewer
disable_viewer: bool = False
# Path to the .pt file. If provide, it will skip training and render a video
ckpt: Optional[str] = None
# Path to the Mip-NeRF 360 dataset
data_dir: str = "data/360_v2/garden"
# Downsample factor for the dataset
data_factor: int = 4
# How much to scale the camera origins by
scale_factor: float = 1.0
# Directory to save results
result_dir: str = "results/garden"
# Every N images there is a test image
test_every: int = 8
# Random crop size for training (experimental)
patch_size: Optional[int] = None
# A global scaler that applies to the scene size related parameters
global_scale: float = 1.0
# Port for the viewer server
port: int = 8080
# Batch size for training. Learning rates are scaled automatically
batch_size: int = 1
# A global factor to scale the number of training steps
steps_scaler: float = 1.0
# Number of training steps
max_steps: int = 30_000
# Steps to evaluate the model
eval_steps: List[int] = field(default_factory=lambda: [7_000, 30_000])
# Steps to save the model
save_steps: List[int] = field(default_factory=lambda: [7_000, 30_000])
# Initialization strategy
init_type: str = "sfm"
# Initial number of GSs. Ignored if using sfm
init_num_pts: int = 100_000
# Initial extent of GSs as a multiple of the camera extent. Ignored if using sfm
init_extent: float = 3.0
# Degree of spherical harmonics
sh_degree: int = 3
# Turn on another SH degree every this steps
sh_degree_interval: int = 1000
# Initial opacity of GS
init_opa: float = 0.1
# Initial scale of GS
init_scale: float = 1.0
# Weight for SSIM loss
ssim_lambda: float = 0.2
# Near plane clipping distance
near_plane: float = 0.01
# Far plane clipping distance
far_plane: float = 1e10
# GSs with opacity below this value will be pruned
prune_opa: float = 0.005
# GSs with image plane gradient above this value will be split/duplicated
grow_grad2d: float = 0.0002
# GSs with scale below this value will be duplicated. Above will be split
grow_scale3d: float = 0.01
# GSs with scale above this value will be pruned.
prune_scale3d: float = 0.1
# Start refining GSs after this iteration
refine_start_iter: int = 500
# Stop refining GSs after this iteration
refine_stop_iter: int = 15_000
# Reset opacities every this steps
reset_every: int = 3000
# Refine GSs every this steps
refine_every: int = 100
# Use packed mode for rasterization, this leads to less memory usage but slightly slower.
packed: bool = False
# Use sparse gradients for optimization. (experimental)
sparse_grad: bool = False
# Use absolute gradient for pruning. This typically requires larger --grow_grad2d, e.g., 0.0008 or 0.0006
absgrad: bool = False
# Anti-aliasing in rasterization. Might slightly hurt quantitative metrics.
antialiased: bool = False
# Whether to use revised opacity heuristic from arXiv:2404.06109 (experimental)
revised_opacity: bool = False
# Use random background for training to discourage transparency
random_bkgd: bool = False
# Enable camera optimization.
pose_opt: bool = False
# Learning rate for camera optimization
pose_opt_lr: float = 1e-5
# Regularization for camera optimization as weight decay
pose_opt_reg: float = 1e-6
# Add noise to camera extrinsics. This is only to test the camera pose optimization.
pose_noise: float = 0.0
# Enable appearance optimization. (experimental)
app_opt: bool = False
# Appearance embedding dimension
app_embed_dim: int = 16
# Learning rate for appearance optimization
app_opt_lr: float = 1e-3
# Regularization for appearance optimization as weight decay
app_opt_reg: float = 1e-6
# Enable depth loss. (experimental)
depth_loss: bool = False
# Weight for depth loss
depth_lambda: float = 1e-2
# Dump information to tensorboard every this steps
tb_every: int = 100
# Save training images to tensorboard
tb_save_image: bool = False
def adjust_steps(self, factor: float):
self.eval_steps = [int(i * factor) for i in self.eval_steps]
self.save_steps = [int(i * factor) for i in self.save_steps]
self.max_steps = int(self.max_steps * factor)
self.sh_degree_interval = int(self.sh_degree_interval * factor)
self.refine_start_iter = int(self.refine_start_iter * factor)
self.refine_stop_iter = int(self.refine_stop_iter * factor)
self.reset_every = int(self.reset_every * factor)
self.refine_every = int(self.refine_every * factor)
def pcd_2_gs(
points: Tensor = None,
init_opacity: float = 0.1,
init_scale: float = 1.0,
scene_scale: float = 1.0,
sh_degree: int = 3,
feature_dim: Optional[int] = None,
device: str = "cuda",
) -> torch.nn.ParameterDict:
points = points # pcd
pnum = points.shape[0]
rgbs = torch.rand((pnum, 3))
N = points.shape[0]
# Initialize the GS size to be the average dist of the 3 nearest neighbors
dist2_avg = (knn(points, 4)[:, 1:] ** 2).mean(dim=-1) # [N,]
dist_avg = torch.sqrt(dist2_avg)
scales = torch.log(dist_avg * init_scale).unsqueeze(-1).repeat(1, 3) # [N, 3]
quats = torch.rand((N, 4)) # [N, 4]
opacities = torch.logit(torch.full((N,), init_opacity)) # [N,]
params = [
# name, value, lr
("means", torch.nn.Parameter(points), 1.6e-4 * scene_scale),
("scales", torch.nn.Parameter(scales), 5e-3),
("quats", torch.nn.Parameter(quats), 1e-3),
("opacities", torch.nn.Parameter(opacities), 5e-2),
]
if feature_dim is None:
# color is SH coefficients.
colors = torch.zeros((N, (sh_degree + 1) ** 2, 3)) # [N, K, 3]
colors[:, 0, :] = rgb_to_sh(rgbs)
params.append(("sh0", torch.nn.Parameter(colors[:, :1, :]), 2.5e-3))
params.append(("shN", torch.nn.Parameter(colors[:, 1:, :]), 2.5e-3 / 20))
else:
# features will be used for appearance and view-dependent shading
features = torch.rand(N, feature_dim) # [N, feature_dim]
params.append(("features", torch.nn.Parameter(features), 2.5e-3))
colors = torch.logit(rgbs) # [N, 3]
params.append(("colors", torch.nn.Parameter(colors), 2.5e-3))
splats = torch.nn.ParameterDict({n: v for n, v, _ in params}).to(device)
return splats
def create_splats_with_optimizers(
init_type: str = "random",
init_num_pts: int = 100_000,
init_extent: float = 3.0,
init_opacity: float = 0.1,
init_scale: float = 1.0,
scene_scale: float = 1.0,
sh_degree: int = 3,
sparse_grad: bool = False,
batch_size: int = 1,
feature_dim: Optional[int] = None,
device: str = "cuda",
points: Optional[Tensor] = None,
) -> Tuple[torch.nn.ParameterDict, Dict[str, torch.optim.Optimizer]]:
if init_type == "sfm":
print("***** Gaussion init_type: sfm *****")
# points = torch.from_numpy(parser.points).float()
# rgbs = torch.from_numpy(parser.points_rgb / 255.0).float()
points = points
pnum = points.shape[0]
rgbs = torch.rand((pnum, 3))
elif init_type == "random":
print("***** Gaussion init_type: random *****")
points = scene_scale * (torch.rand((init_num_pts, 3)) * 2 - 1)
rgbs = torch.rand((init_num_pts, 3))
else:
raise ValueError("Please specify a correct init_type: sfm or random")
N = points.shape[0]
# Initialize the GS size to be the average dist of the 3 nearest neighbors
dist2_avg = (knn(points, 4)[:, 1:] ** 2).mean(dim=-1) # [N,]
dist_avg = torch.sqrt(dist2_avg)
scales = torch.log(dist_avg * init_scale).unsqueeze(-1).repeat(1, 3) # [N, 3]
quats = torch.rand((N, 4)) # [N, 4]
opacities = torch.logit(torch.full((N,), init_opacity)) # [N,]
params = [
# name, value, lr
("means", torch.nn.Parameter(points), 1.6e-4 * scene_scale),
("scales", torch.nn.Parameter(scales), 5e-3),
("quats", torch.nn.Parameter(quats), 1e-3),
("opacities", torch.nn.Parameter(opacities), 5e-2),
]
if feature_dim is None:
# color is SH coefficients.
colors = torch.zeros((N, (sh_degree + 1) ** 2, 3)) # [N, K, 3]
colors[:, 0, :] = rgb_to_sh(rgbs)
params.append(("sh0", torch.nn.Parameter(colors[:, :1, :]), 2.5e-3))
params.append(("shN", torch.nn.Parameter(colors[:, 1:, :]), 2.5e-3 / 20))
else:
# features will be used for appearance and view-dependent shading
features = torch.rand(N, feature_dim) # [N, feature_dim]
params.append(("features", torch.nn.Parameter(features), 2.5e-3))
colors = torch.logit(rgbs) # [N, 3]
params.append(("colors", torch.nn.Parameter(colors), 2.5e-3))
splats = torch.nn.ParameterDict({n: v for n, v, _ in params}).to(device)
# Scale learning rate based on batch size, reference:
# https://www.cs.princeton.edu/~smalladi/blog/2024/01/22/SDEs-ScalingRules/
# Note that this would not make the training exactly equivalent, see
# https://arxiv.org/pdf/2402.18824v1
optimizers = {
name: (torch.optim.SparseAdam if sparse_grad else torch.optim.Adam)(
[{"params": splats[name], "lr": lr * math.sqrt(batch_size)}],
eps=1e-15 / math.sqrt(batch_size),
betas=(1 - batch_size * (1 - 0.9), 1 - batch_size * (1 - 0.999)),
)
for name, _, lr in params
}
return splats, optimizers
class SLAM():
def __init__(self, config):
self.config = config
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.dataset = get_dataset(config)
self.create_pose_data()
# self.gs_dataset_cfg = gs_dataset_cfg
# self.gs_opt_cfg = gs_opt_cfg
# self.gs_pipe_cfg = gs_pipe_cfg
self.control_knot_poses = None
self.control_knot_ts = None
self.control_knot_delta_t = 0.15 # create control knot every 5 frames
self.events_for_tracking = None
self.events_for_BA = []
self.gs_cfg = Config()
self.scene_scale = self.config["mapping"]["bounding_size"]
print("Scene scale(or size of bounding box):", self.scene_scale)
# Model
feature_dim = 32 if self.gs_cfg.app_opt else None
self.splats, self.optimizers = create_splats_with_optimizers(
"random",
init_num_pts=self.gs_cfg.init_num_pts,
init_extent=self.gs_cfg.init_extent,
init_opacity=self.gs_cfg.init_opa,
init_scale=self.gs_cfg.init_scale,
scene_scale=self.scene_scale,
sh_degree=self.gs_cfg.sh_degree,
sparse_grad=self.gs_cfg.sparse_grad,
batch_size=self.gs_cfg.batch_size,
feature_dim=feature_dim,
device=self.device,
)
print("Model initialized. Number of GS:", len(self.splats["means"]))
# TODO: make this as a configurable parameter
self.median_filter = MedianPool2d(kernel_size=5, same=True)
self.median_filter_dvs = MedianPool2d(kernel_size=5, same=True)
height = 480
width = 640
# mask = np.zeros((height, width), dtype=np.uint8)
# radius = 325
# center = (width // 2-15, height // 2)
# cv2.circle(mask, center, radius, (1), -1)
mask = np.ones((height, width), dtype=np.uint8)
self.vector_mask = torch.from_numpy(mask).float().cuda()
# self.scene_extent = None
self.color_mask = np.zeros((self.dataset.H, self.dataset.W, 3))
if self.config["mapping"]["color_channels"]==3:
self.color_mask[0::2, 0::2, 0] = 1 # r
self.color_mask[0::2, 1::2, 1] = 1 # g
self.color_mask[1::2, 0::2, 1] = 1 # g
self.color_mask[1::2, 1::2, 2] = 1 # b
else:
self.color_mask[...] = 1
# self.color_mask = self.color_mask.reshape((-1, 3))
self.color_mask = torch.from_numpy(self.color_mask).float().cuda()
print('CoSLAM finished initialization...\n')
# Experimental
def construct_list_of_attributes(self):
l = ['x', 'y', 'z', 'nx', 'ny', 'nz']
# All channels except the 3 DC
for i in range(self.splats["sh0"].shape[1]*self.splats["sh0"].shape[2]):
l.append('f_dc_{}'.format(i))
for i in range(self.splats["shN"].shape[1]*self.splats["shN"].shape[2]):
l.append('f_rest_{}'.format(i))
l.append('opacity')
for i in range(self.splats["scales"].shape[1]):
l.append('scale_{}'.format(i))
for i in range(self.splats["quats"].shape[1]):
l.append('rot_{}'.format(i))
return l
# Experimental
@torch.no_grad()
def save_ply(self, path):
os.makedirs(os.path.dirname(path), exist_ok=True)
xyz = self.splats["means"].detach().cpu().numpy()
normals = np.zeros_like(xyz)
# copy sh0 and shN
sh0_cp = self.splats["sh0"].detach()
shN_cp = self.splats["shN"].detach()
sh0_cp[:,:,1] = sh0_cp[:,:,0]
sh0_cp[:,:,2] = sh0_cp[:,:,0]
shN_cp[:,:,1] = shN_cp[:,:,0]
shN_cp[:,:,2] = shN_cp[:,:,0]
f_dc = sh0_cp.transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()
f_rest = shN_cp.transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()
opacities = self.splats["opacities"].detach().unsqueeze(-1).cpu().numpy()
scale = self.splats["scales"].detach().cpu().numpy()
rotation = self.splats["quats"].detach().cpu().numpy()
dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]
elements = np.empty(xyz.shape[0], dtype=dtype_full)
attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)
elements[:] = list(map(tuple, attributes))
el = PlyElement.describe(elements, 'vertex')
PlyData([el]).write(path)
def create_pose_data(self):
'''
Create the pose data
'''
self.est_c2w_data = {}
self.est_c2w_ts = {}
self.ctrl_knot_se3_all = {}
self.ctrl_knot_ts_all = {}
self.load_gt_pose()
def load_gt_pose(self):
'''
Load the ground truth pose
'''
self.pose_gt = {}
for i, pose in enumerate(self.dataset.poses):
self.pose_gt[self.dataset.frame_ids[i]] = pose
# def render_with_gsplat(self, gaussians : GaussianModel, T_cam2wld_se3, bRenderDepth=False, nOutputChannel = 1, render_tumvie_rgb = False):
# if render_tumvie_rgb and self.config["dataset"]=="tum_vie":
# focal_y = self.dataset.fy_rgb
# focal_x = self.dataset.fx_rgb
# cx = self.dataset.cx_rgb
# cy = self.dataset.cy_rgb
# # focal_y = self.dataset.fy
# # focal_x = self.dataset.fx
# # cx = self.dataset.cx
# # cy = self.dataset.cy
# image_width = self.dataset.W_rgb
# image_height = self.dataset.H_rgb
# T_cam2wld_SE3_pp = T_cam2wld_se3.Exp()
# T_evCam_rgbCam_raw = self.dataset.T_evCam_rgbCam[0]
# # estimate the scale
# save_path = os.path.join(self.config["data"]["output"], self.config["data"]["exp_name"])
# scale = align_and_est_scale(self.pose_gt, self.est_c2w_data, 1, save_path, "pose", f"estimate_scale")
# T_evCam_rgbCam_raw[:3, 3] /= scale
# T_evCam_rgbCam = T_evCam_rgbCam_raw.copy()
# T_evCam_rgbCam_SE3_pp = pp.mat2SE3(torch.from_numpy(T_evCam_rgbCam)).float()
# T_rgbcam2wld_SE3_pp = T_evCam_rgbCam_SE3_pp.Inv() * T_cam2wld_SE3_pp
# T_cam2wld_se3 = T_rgbcam2wld_SE3_pp.Log()
# else:
# focal_y = self.dataset.fy
# focal_x = self.dataset.fx
# cx = self.dataset.cx
# cy = self.dataset.cy
# image_width = self.dataset.W
# image_height = self.dataset.H
# # Create zero tensor. We will use it to make pytorch return gradients of the 2D (screen-space) means
# screenspace_points = torch.zeros_like(gaussians.get_xyz, dtype=gaussians.get_xyz.dtype, requires_grad=True, device="cuda") + 0
# try:
# screenspace_points.retain_grad()
# except:
# pass
# T_c2w_Rt = torch.eye(4, device=self.device)
# T_c2w_Rt[:3,:4] = se3_to_SE3(T_cam2wld_se3)
# T_w2c_Rt = torch.linalg.inv(T_c2w_Rt)
# BLOCK_X, BLOCK_Y = 16, 16
# tile_bounds = (
# (image_width + BLOCK_X - 1) // BLOCK_X,
# (image_height + BLOCK_Y - 1) // BLOCK_Y,
# 1,
# )
# xys, depths, radii, conics, _, num_tiles_hit, cov3d = ProjectGaussians.apply(
# gaussians._xyz,
# gaussians.get_scaling,
# 1,
# gaussians._rotation,
# T_w2c_Rt,
# None,
# focal_x,
# focal_y,
# cx,
# cy,
# image_height,
# image_width,
# tile_bounds,
# )
# torch.cuda.synchronize()
# shs_view = gaussians.get_features.transpose(1, 2).view(-1, 3, (gaussians.max_sh_degree+1)**2)
# dir_pp = (gaussians.get_xyz - T_c2w_Rt[:3, 3].unsqueeze(0).repeat(gaussians.get_features.shape[0], 1))
# dir_pp_normalized = dir_pp/dir_pp.norm(dim=1, keepdim=True)
# sh2rgb = eval_sh(gaussians.active_sh_degree, shs_view, dir_pp_normalized)
# colors_precomp = torch.clamp_min(sh2rgb + 0.5, 0.0)
# background = torch.ones(3, device=self.device)
# out_img, out_alpha, out_depth, out_uncertainty = RasterizeGaussians.apply(
# xys,
# depths,
# radii,
# conics,
# num_tiles_hit,
# colors_precomp,
# gaussians.get_opacity,
# image_height,
# image_width,
# background,
# False,
# bRenderDepth)
# torch.cuda.synchronize()
# # convert rgb image to single channel image for event loss
# if nOutputChannel == 1:
# out_img = out_img.mean(dim=2)
# return {'image': out_img,
# 'depth': out_depth,
# "viewspace_points": screenspace_points,
# 'uncertainty': out_uncertainty,
# 'xys': xys,
# 'visibility_filter': radii > 0,
# "radii": radii}
def rasterize_splats(
self,
camtoworlds: Tensor,
**kwargs,
) -> Tuple[Tensor, Tensor, Dict]:
# read the camera parameters
Ks = torch.from_numpy(self.dataset.K).to(self.device).unsqueeze(0) # [1, 3, 3]
width = self.dataset.W
height = self.dataset.H
near_plane=self.gs_cfg.near_plane,
far_plane=self.gs_cfg.far_plane,
means = self.splats["means"] # [N, 3]
# quats = F.normalize(self.splats["quats"], dim=-1) # [N, 4]
# rasterization does normalization internally
quats = self.splats["quats"] # [N, 4]
scales = torch.exp(self.splats["scales"]) # [N, 3]
opacities = torch.sigmoid(self.splats["opacities"]) # [N,]
# image_ids = kwargs.pop("image_ids", None)
# if self.cfg.app_opt:
# colors = self.app_module(
# features=self.splats["features"],
# embed_ids=image_ids,
# dirs=means[None, :, :] - camtoworlds[:, None, :3, 3],
# sh_degree=kwargs.pop("sh_degree", self.cfg.sh_degree),
# )
# colors = colors + self.splats["colors"]
# colors = torch.sigmoid(colors)
# else:
colors = torch.cat([self.splats["sh0"], self.splats["shN"]], 1) # [N, K, 3]
# set the background color
# 0-white, 1-black, 2-grey
if self.config["mapping"]["background"]==0:
backgrounds=torch.ones(Ks.shape[0], colors.shape[-1], device=self.device) # white
elif self.config["mapping"]["background"]==1:
backgrounds=torch.zeros(Ks.shape[0], colors.shape[-1], device=self.device) # black
elif self.config["mapping"]["background"]==2:
backgrounds=(159./255.)*torch.ones(Ks.shape[0], colors.shape[-1], device=self.device) # grey
else:
raise ValueError("Not implemented background color!")
rasterize_mode = "antialiased" if self.gs_cfg.antialiased else "classic"
render_colors, render_alphas, info = rasterization(
means=means,
quats=quats,
scales=scales,
opacities=opacities,
colors=colors,
viewmats=torch.linalg.inv(camtoworlds), # [C, 4, 4]
Ks=Ks, # [C, 3, 3]
width=width,
height=height,
packed=self.gs_cfg.packed,
absgrad=self.gs_cfg.absgrad,
sparse_grad=self.gs_cfg.sparse_grad,
rasterize_mode=rasterize_mode,
backgrounds=backgrounds,
**kwargs,
)
render_pkg = {}
if self.config["mapping"]["color_channels"]==3:
img=render_colors[0][..., 0:3] # [H, W, 3]
else:
img=render_colors[0][..., 0] # [H, W]
if render_colors.shape[-1]==4:
depth_img = render_colors[0][..., 3:4][..., 0] # [H, W]
else:
depth_img = None
return {"image": img,
"depth": depth_img,
"alpha": render_alphas,
"info": info}
def warp_image(self, T_se3_src2wld, T_se3_dst2wld, depth_src, image_dst):
fx = self.dataset.fx
fy = self.dataset.fy
cx = self.dataset.cx
cy = self.dataset.cy
height = self.dataset.H
width = self.dataset.W
assert(depth_src.shape[0] == height) # N1HW
assert(depth_src.shape[1] == width)
assert(image_dst.shape[0] == height) # N1HW
assert(image_dst.shape[1] == width)
depth_src = depth_src.unsqueeze(0).unsqueeze(0)
if image_dst.dim() == 3:
image_dst = image_dst.permute(2,0,1)
image_dst = image_dst.unsqueeze(0)
else:
image_dst = image_dst.unsqueeze(0).unsqueeze(0)
intrinsics = torch.zeros(1, 4, 4).to(self.device)
intrinsics[..., 0, 0] += fx
intrinsics[..., 1, 1] += fy
intrinsics[..., 0, 2] += cx
intrinsics[..., 1, 2] += cy
intrinsics[..., 2, 2] += 1.0
intrinsics[..., 3, 3] += 1.0
T_src2wld_Rt = torch.eye(4).repeat(1, 1, 1).to(self.device)
T_dst2wld_Rt = torch.eye(4).repeat(1, 1, 1).to(self.device)
T_src2wld_Rt[..., :3, :4] = se3_to_SE3(T_se3_src2wld)
T_dst2wld_Rt[..., :3, :4] = se3_to_SE3(T_se3_dst2wld)
# create image hegith and width
height_tmp = torch.zeros(1).to(self.device)
height_tmp[..., 0] += height
width_tmp = torch.zeros(1).to(self.device)
width_tmp[..., 0] += width
# creat pinhole cameras
pinhole_src = tgm.PinholeCamera(intrinsics, T_src2wld_Rt, height_tmp, width_tmp)
pinhole_dst = tgm.PinholeCamera(intrinsics, T_dst2wld_Rt, height_tmp, width_tmp)
#
image_src = depth_warp(pinhole_dst, pinhole_src, depth_src, image_dst, height, width) # NxCxHxW
image_src = image_src.squeeze()
depth_src = depth_src.squeeze()
with torch.no_grad():
if image_src.dim() == 3:
image_src = image_src.permute(1,2,0)
mask_src = torch.bitwise_and(image_src.mean(dim=2) > 0, depth_src > 0).detach().float() # no need to propagate gradients for mask
else:
mask_src = torch.bitwise_and(image_src > 0, depth_src > 0).detach().float() # no need to propagate gradients for mask
mask_src = 1 - mask_src
kernel = np.array([ [1, 1, 1], [1, 1, 1], [1, 1, 1] ], dtype=np.float32)
kernel_tensor = torch.Tensor(np.expand_dims(np.expand_dims(kernel, 0), 0)).to(self.device) # size: (1, 1, 3, 3)
mask_src = 1. - torch.clamp(torch.nn.functional.conv2d(mask_src.unsqueeze(0).unsqueeze(0), kernel_tensor, padding=(1, 1)), 0, 1).squeeze()
return image_src, mask_src
def post_process_event_image(self, events_stream, _sigma=0.001):
#
if self.config["dataset"] == "tum_vie" and self.config["data"]["downsample_factor"]>1:
events_map = self.accumulate_event_to_img(self.dataset.H_old, self.dataset.W_old, events_stream)
else:
events_map = self.accumulate_event_to_img(self.dataset.H, self.dataset.W, events_stream)
if self.config["dataset"] == "tum_vie":
if self.config["mapping"]["use_median_filter"]:
events_map = self.median_filter(events_map.unsqueeze(0).unsqueeze(0)).squeeze()
if self.config["data"]["downsample_factor"]>1:
events_map = events_map.cpu().numpy()
# events_map = cv2.fisheye.undistortImage(events_map, self.dataset.K_old, self.dataset.dist_coeffs, Knew=self.dataset.K_old, new_size=(self.dataset.W_old, self.dataset.H_old))
events_map = cv2.fisheye.undistortImage(events_map, self.dataset.K, self.dataset.dist_coeffs, Knew=self.dataset.K_new, new_size=(self.dataset.W, self.dataset.H))
events_map = cv2.resize(events_map, (self.dataset.W, self.dataset.H), interpolation=cv2.INTER_LINEAR) #cv2.INTER_AREA
events_map = torch.from_numpy(events_map).cuda()
else:
events_map = events_map.cpu().numpy()
# events_map = cv2.fisheye.undistortImage(events_map, self.dataset.K, self.dataset.dist_coeffs, Knew=self.dataset.K, new_size=(self.dataset.W, self.dataset.H))
events_map = cv2.fisheye.undistortImage(events_map, self.dataset.K, self.dataset.dist_coeffs, Knew=self.dataset.K_new, new_size=(self.dataset.W, self.dataset.H))
events_map = torch.from_numpy(events_map).cuda()
# elif self.config["dataset"] == "vector":
# events_map = events_map.cpu().numpy()
# # undisted_img = cv2.undistort(events_map, self.dataset.K_old, self.dataset.dist_coeffs, newCameraMatrix=self.dataset.K_new)
# undisted_img = cv2.undistort(events_map, self.dataset.K_old, self.dataset.dist_coeffs)
# events_map = torch.from_numpy(undisted_img).cuda()
elif self.config["dataset"] == "dev_real" or self.config["dataset"] == "rpg_evo_stereo":
events_map = events_map.cpu().numpy()
# undisted_img = cv2.undistort(events_map, self.dataset.K_old, self.dataset.dist_coeffs, newCameraMatrix=self.dataset.K_new)
undisted_img = cv2.undistort(events_map, self.dataset.K, self.dataset.dist_coeffs)
events_map = torch.from_numpy(undisted_img).cuda()
if self.config["mapping"]["use_median_filter"]:
events_map = self.median_filter_dvs(events_map.unsqueeze(0).unsqueeze(0)).squeeze()
if self.config["blur_event"]:
# blur
blurrer = v2.GaussianBlur(kernel_size=(5,5), sigma=_sigma)
events_map = blurrer(events_map.unsqueeze(0).unsqueeze(0)).squeeze()
return events_map
def initialize_gaussian_scene(self, events_stream, num_pixels_to_sample, T_cam_to_wld, threshold = 0.1, depth_map=None):
if depth_map is not None:
assert(depth_map.dim()==2)
threshold = self.config["event"]["threshold"]
if depth_map is None:
# depth = 100
num_pts = 100_000
print(f"Generating random point cloud ({num_pts})...")
# We create random points inside the bounds of the synthetic Blender scenes
# xyz = np.random.random((num_pts, 3)) * 2.6 - 1.3
# xyz = np.random.random((num_pts, 3)) * 7.0 - 3.5
bounding_size = self.config["bounding_size"]
xyz = np.random.random((num_pts, 3))*bounding_size - 0.5*bounding_size
shs = np.random.random((num_pts, 3)) / 255.0
xyz = torch.from_numpy(xyz).cuda().float()
shs = torch.from_numpy(shs).cuda().float()
pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=torch.zeros_like(xyz).cuda().float())
else:
print('Use provided depth map for scene initialization...')
events_map = self.post_process_event_image(events_stream)
# sample pixels with events
fx = self.dataset.fx
fy = self.dataset.fy
cx = self.dataset.cx
cy = self.dataset.cy
H = self.dataset.H
W = self.dataset.W
min_depth = self.config["mapping"]["min_depth"]
max_depth = self.config["mapping"]["max_depth"]
if self.config["initialization"]["gaussian_init_sfm_mask"]==1: # using event map mask;
pixel_uv_with_event = torch.where(events_map.abs() > threshold)
sampled_event_pixel_idx = torch.randperm(pixel_uv_with_event[0].shape[0])[:num_pixels_to_sample]
indice_h = pixel_uv_with_event[0][sampled_event_pixel_idx].to(self.device)
indice_w = pixel_uv_with_event[1][sampled_event_pixel_idx].to(self.device)
elif self.config["initialization"]["gaussian_init_sfm_mask"]==0: # using depth map mask
pixel_uv_with_event = torch.where((depth_map.abs() > min_depth) & (depth_map.abs() < max_depth))
sampled_event_pixel_idx = torch.randperm(pixel_uv_with_event[0].shape[0])[:num_pixels_to_sample]
indice_h = pixel_uv_with_event[0][sampled_event_pixel_idx].to(self.device)
indice_w = pixel_uv_with_event[1][sampled_event_pixel_idx].to(self.device)
elif self.config["initialization"]["gaussian_init_sfm_mask"]==2: # using both event and depth map mask
pixel_uv_with_event = torch.where((depth_map.abs() > min_depth) & (depth_map.abs() < max_depth))
sampled_event_pixel_idx = torch.randperm(pixel_uv_with_event[0].shape[0])[:int(num_pixels_to_sample*0.5)]
indice_h1 = pixel_uv_with_event[0][sampled_event_pixel_idx].to(self.device)
indice_w1 = pixel_uv_with_event[1][sampled_event_pixel_idx].to(self.device)
pixel_uv_with_event = torch.where(events_map.abs() > threshold)
sampled_event_pixel_idx = torch.randperm(pixel_uv_with_event[0].shape[0])[:int(num_pixels_to_sample*0.5)]
indice_h2 = pixel_uv_with_event[0][sampled_event_pixel_idx].to(self.device)
indice_w2 = pixel_uv_with_event[1][sampled_event_pixel_idx].to(self.device)
indice_h = torch.cat([indice_h1, indice_h2])
indice_w = torch.cat([indice_w1, indice_w2])
else:
raise ValueError("wrong option for gaussian_init_sfm_mask")
#
sampled_rays = get_camera_rays(H, W, fx, fy, cx, cy, type='OpenCV').to(self.device)
sampled_rays = sampled_rays[indice_h, indice_w, :]
depth = depth_map[indice_h, indice_w].unsqueeze(-1).float()
sampled_rays = (sampled_rays * depth).transpose(1,0).to(self.device)
#
sampled_rays = torch.matmul(T_cam_to_wld[:3, :3], sampled_rays) + T_cam_to_wld[:3, 3].unsqueeze(-1)
points = sampled_rays.transpose(1, 0)
# colors
min = events_map.min()
max = events_map.max()
events_map = (events_map - min) / (max - min)
colors = events_map[indice_h, indice_w].unsqueeze(-1).repeat(1, 3)
# normals
normals = torch.zeros_like(colors)
normals[:, 2] = 1.
# create pcd
pcd = BasicPointCloud(points=points, colors=colors, normals=normals)
return pcd
# spline pose and get 7 rays_o/rays_d, then get color and average
def initialization(self, init_batch, niters, traj_mode='cspline', depth_map=None):
traj_mode = 'linear'
num_batch = len(init_batch)
frame_ts_all = []
frame_id_all = []
events_all = []
preSum_event_batch = [0]
for i in range(num_batch):
frame_id = init_batch[i]["frame_id"].item()
frame_ts = init_batch[i]["pose_ts"].item()
frame_id_all.append(frame_id)
frame_ts_all.append(frame_ts)
cur_event = init_batch[i]['events'].squeeze().to(self.device)
preSum_event_batch.append(cur_event.shape[0]+preSum_event_batch[-1])
events_all.append(cur_event)
num_events_to_skip = self.config["num_events_to_skip"]
preSum_event_batch[0] = preSum_event_batch[0]+num_events_to_skip
preSum_event_batch[-1] = preSum_event_batch[-1]-num_events_to_skip
if depth_map is None:
print('######################### random initialization #########################')
else:
# initialize Gaussians with depth_map
print('######################### initialization with depth_map #########################')
# initialize Gaussians
if self.config["initialization"]["retain_pose"]:
assert(len(self.ctrl_knot_se3_all)>0)
idx_ = frame_id_all[-1]
T_cam2wld_Rt = se3_to_SE3_m44(self.ctrl_knot_se3_all[idx_]).cuda()
else:
T_cam2wld_Rt = torch.eye(4).to(self.device)
gaussian_num_sfm = self.config["initialization"]["gaussian_num_sfm"]
pcd = self.initialize_gaussian_scene(events_all[0], gaussian_num_sfm, T_cam2wld_Rt, depth_map=depth_map)
# self.gs_model.create_from_tensor_pcd(pcd, spatial_lr_scale=8.23)
# self.gs_model.training_setup(self.gs_opt_cfg)
feature_dim = 32 if self.gs_cfg.app_opt else None
if self.config["retain_old_gs"]:
print(f"============================= retain old gs ===============================")
new_gs = pcd_2_gs(
points= pcd.points.detach(),
init_opacity=self.gs_cfg.init_opa,
init_scale=self.gs_cfg.init_scale,
scene_scale=self.scene_scale,
sh_degree=self.gs_cfg.sh_degree,
feature_dim=feature_dim,
device=self.device,
)
add_new_gs(self.splats, self.optimizers, new_gs)
else:
feature_dim = 32 if self.gs_cfg.app_opt else None
self.splats, self.optimizers = create_splats_with_optimizers(
"sfm",
init_num_pts=self.gs_cfg.init_num_pts,
init_extent=self.gs_cfg.init_extent,
init_opacity=self.gs_cfg.init_opa,
init_scale=self.gs_cfg.init_scale,
scene_scale=self.scene_scale,
sh_degree=self.gs_cfg.sh_degree,
sparse_grad=self.gs_cfg.sparse_grad,
batch_size=self.gs_cfg.batch_size,
feature_dim=feature_dim,
device=self.device,
points=pcd.points
)
# densification setting
self.gs_cfg.prune_opa = self.config["mapping"]["prune_opa"]
self.gs_cfg.refine_start_iter = self.config["mapping"]["refine_start_iter"]
self.gs_cfg.refine_stop_iter= self.config["mapping"]["refine_stop_iter"]
self.gs_cfg.refine_every = self.config["mapping"]["refine_every"]
self.gs_cfg.grow_grad2d = self.config["mapping"]["grow_grad2d"]
self.gs_cfg.grow_scale3d = self.config["mapping"]["grow_scale3d"]
# prune_scale3d: float = 0.1
self.gs_cfg.prune_scale3d = self.config["mapping"]["prune_scale3d"]
# Densification Strategy
self.strategy = DefaultStrategy(
verbose=True,
scene_scale=self.scene_scale,
prune_opa=self.gs_cfg.prune_opa,
grow_grad2d=self.gs_cfg.grow_grad2d,
grow_scale3d=self.gs_cfg.grow_scale3d,
prune_scale3d=self.gs_cfg.prune_scale3d,
# refine_scale2d_stop_iter=4000, # splatfacto behavior
refine_start_iter=self.gs_cfg.refine_start_iter,
refine_stop_iter=self.gs_cfg.refine_stop_iter,
reset_every=self.gs_cfg.reset_every,
refine_every=self.gs_cfg.refine_every,
absgrad=self.gs_cfg.absgrad,
revised_opacity=self.gs_cfg.revised_opacity,
)
self.strategy.check_sanity(self.splats, self.optimizers)
self.strategy_state = self.strategy.initialize_state()
frame_ts_all_withzero = frame_ts_all.copy()
frame_ts_all_withzero.insert(0, 0.0)
events_all = torch.cat(events_all, dim=0)
ts_all = events_all[:,2].detach().cpu().numpy()
t_data_min = ts_all.min()
t_data_max = ts_all.max()
event_total_num = ts_all.shape[0]
incre_sampling_seg_num_expected = self.config["initialization"]["incre_sampling_seg_num_expected"]
min_n_winsize = self.config["initialization"]["min_n_winsize"]
max_n_winsize = self.config["initialization"]["max_n_winsize"]
incre_sampling_segs_end = np.linspace(10, event_total_num-10, incre_sampling_seg_num_expected).astype(int)
start_tmp_ = np.searchsorted(incre_sampling_segs_end, max_n_winsize)
if(incre_sampling_segs_end[start_tmp_]<=max_n_winsize):
start_tmp_ = start_tmp_+1
incre_sampling_segs_end = incre_sampling_segs_end[start_tmp_:]
assert incre_sampling_segs_end.shape[0]>1
assert incre_sampling_segs_end[0]>max_n_winsize
events_per_seg = incre_sampling_segs_end[1]-incre_sampling_segs_end[0]
incre_sampling_seg_num = incre_sampling_segs_end.shape[0]
print(f"******************************* events_num: {event_total_num} *********************************")
print(f"incremental sampling number: {incre_sampling_seg_num}")
print(f"****events_per_seg={events_per_seg}, min_n_winsize={min_n_winsize},max_n_winsize={max_n_winsize}, ")