shuinb commited on
Commit
428b477
·
verified ·
1 Parent(s): 5de0761

Remove redundant transientnerf code folder

Browse files
Files changed (41) hide show
  1. codes/reconstruction/transientnerf/configs/test/captured/artbuilding3_five_views_quantitative.ini +0 -47
  2. codes/reconstruction/transientnerf/configs/test/captured/artbuilding3_ten_views_quantitative.ini +0 -47
  3. codes/reconstruction/transientnerf/configs/test/captured/balldesk_quantitative_fiveviews.ini +0 -47
  4. codes/reconstruction/transientnerf/configs/test/captured/balldesk_quantitative_tenviews.ini +0 -47
  5. codes/reconstruction/transientnerf/configs/test/captured/balldesk_quantitative_threeviews.ini +0 -47
  6. codes/reconstruction/transientnerf/configs/test/captured/designbuilding1_five_views_quantitative.ini +0 -47
  7. codes/reconstruction/transientnerf/configs/test/captured/designbuilding1_quantitative_tenviews.ini +0 -47
  8. codes/reconstruction/transientnerf/configs/test/captured/parking_five_views_quantitative.ini +0 -48
  9. codes/reconstruction/transientnerf/configs/test/captured/parking_ten_views_quantitative.ini +0 -48
  10. codes/reconstruction/transientnerf/configs/test/captured/physics_building2_ten_views_quantitative.ini +0 -48
  11. codes/reconstruction/transientnerf/configs/test/captured/physics_building2_ten_views_quantitative1.ini +0 -48
  12. codes/reconstruction/transientnerf/configs/train/captured/artbuilding3_five_views.ini +0 -50
  13. codes/reconstruction/transientnerf/configs/train/captured/artbuilding3_ten_views.ini +0 -50
  14. codes/reconstruction/transientnerf/configs/train/captured/designbuilding1_five_views.ini +0 -50
  15. codes/reconstruction/transientnerf/configs/train/captured/designbuilding1_tenviews.ini +0 -50
  16. codes/reconstruction/transientnerf/configs/train/captured/material_building_five_views.ini +0 -51
  17. codes/reconstruction/transientnerf/configs/train/captured/material_building_ten_views.ini +0 -51
  18. codes/reconstruction/transientnerf/configs/train/captured/parking_five_views.ini +0 -51
  19. codes/reconstruction/transientnerf/configs/train/captured/parking_ten_views.ini +0 -51
  20. codes/reconstruction/transientnerf/configs/train/captured/physics_building2_ten_views.ini +0 -51
  21. codes/reconstruction/transientnerf/configs/train/captured/tfnerf_balldesk_fiveviews.ini +0 -50
  22. codes/reconstruction/transientnerf/configs/train/captured/tfnerf_balldesk_tenviews.ini +0 -50
  23. codes/reconstruction/transientnerf/configs/train/captured/tfnerf_balldesk_threeviews.ini +0 -50
  24. codes/reconstruction/transientnerf/eval.py +0 -556
  25. codes/reconstruction/transientnerf/loaders/README.md +0 -57
  26. codes/reconstruction/transientnerf/loaders/__init__.py +0 -0
  27. codes/reconstruction/transientnerf/loaders/loader_captured.py +0 -532
  28. codes/reconstruction/transientnerf/loaders/loader_captured_ours.py +0 -680
  29. codes/reconstruction/transientnerf/loaders/loader_synthetic.py +0 -453
  30. codes/reconstruction/transientnerf/loaders/utils.py +0 -12
  31. codes/reconstruction/transientnerf/misc/__init__.py +0 -0
  32. codes/reconstruction/transientnerf/misc/dataset_utils.py +0 -169
  33. codes/reconstruction/transientnerf/misc/download_dataset.py +0 -67
  34. codes/reconstruction/transientnerf/misc/eval_utils.py +0 -224
  35. codes/reconstruction/transientnerf/misc/summary.py +0 -147
  36. codes/reconstruction/transientnerf/misc/transient_volrend.py +0 -620
  37. codes/reconstruction/transientnerf/radiance_fields/__init__.py +0 -0
  38. codes/reconstruction/transientnerf/radiance_fields/mlp.py +0 -395
  39. codes/reconstruction/transientnerf/radiance_fields/ngp.py +0 -299
  40. codes/reconstruction/transientnerf/train_ours.py +0 -521
  41. codes/reconstruction/transientnerf/utils.py +0 -539
codes/reconstruction/transientnerf/configs/test/captured/artbuilding3_five_views_quantitative.ini DELETED
@@ -1,47 +0,0 @@
1
- # eval job
2
- scene = "artbuilding3_five_views"
3
- step = 290000
4
- rep_number = 30
5
- split = "test"
6
- checkpoint_dir = "results/artbuilding3_five_views"
7
- test_folder_path = "/work/sdim-lemons/wzt/data/spad_3d/artbuilding3/poses/five_views"
8
-
9
- # model / rendering
10
- version = captured
11
- n_bins = 672
12
- aabb = "[-25.379819,-15.216244,-2.908998,29.218790,32.190764,16.977430]"
13
- near_plane = 0.100000
14
- far_plane = 28.000000
15
- alpha_thre = 0
16
- occ_thre = 0.0000001
17
- render_n_samples = 1024
18
- rfilter_sigma = 0.15
19
- sample_as_per_distribution = False
20
- grid_resolution = 128
21
- grid_nlvl = 1
22
-
23
- # timing / sensor
24
- exposure_time = 0.224844343500
25
- bin_width_s_loader = 7.500000000000e-10
26
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
27
- irf_column = "irf"
28
- irf_half_window = 50
29
-
30
- # data
31
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/artbuilding3/poses/five_views"
32
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/artbuilding3/sp"
33
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
34
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
35
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
36
- invalid_mask_invalid_gt = 10.0
37
- meas_peak_min = 100
38
-
39
- # image size
40
- img_height_test = 192
41
- img_width_test = 256
42
- img_shape_test = 256
43
-
44
- # misc
45
- num_views = 10
46
- device = "cuda:0"
47
- seed = 42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/test/captured/artbuilding3_ten_views_quantitative.ini DELETED
@@ -1,47 +0,0 @@
1
- # eval job
2
- scene = "artbuilding3_ten_views"
3
- step = 290000
4
- rep_number = 30
5
- split = "test"
6
- checkpoint_dir = "results/artbuilding3_ten_views"
7
- test_folder_path = "/work/sdim-lemons/wzt/data/spad_3d/artbuilding3/poses/ten_views"
8
-
9
- # model / rendering
10
- version = captured
11
- n_bins = 672
12
- aabb = "[-25.379819,-15.216244,-2.908998,29.218790,32.190764,16.977430]"
13
- near_plane = 0.100000
14
- far_plane = 28.000000
15
- alpha_thre = 0
16
- occ_thre = 0.0000001
17
- render_n_samples = 1024
18
- rfilter_sigma = 0.15
19
- sample_as_per_distribution = False
20
- grid_resolution = 128
21
- grid_nlvl = 1
22
-
23
- # timing / sensor
24
- exposure_time = 0.224844343500
25
- bin_width_s_loader = 7.500000000000e-10
26
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
27
- irf_column = "irf"
28
- irf_half_window = 50
29
-
30
- # data
31
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/artbuilding3/poses/ten_views"
32
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/artbuilding3/sp"
33
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
34
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
35
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
36
- invalid_mask_invalid_gt = 10.0
37
- meas_peak_min = 100
38
-
39
- # image size
40
- img_height_test = 192
41
- img_width_test = 256
42
- img_shape_test = 256
43
-
44
- # misc
45
- num_views = 10
46
- device = "cuda:0"
47
- seed = 42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/test/captured/balldesk_quantitative_fiveviews.ini DELETED
@@ -1,47 +0,0 @@
1
- # eval job
2
- scene = "balldesk_fiveviews"
3
- step = 300000
4
- rep_number = 30
5
- split = "test"
6
- checkpoint_dir = "./results/ours_balldesk_five_views"
7
- test_folder_path = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/poses/five_views"
8
-
9
- # model / rendering
10
- version = captured
11
- n_bins = 672
12
- aabb = "[-20.685711,-15.981851,-1.508756,19.605109,8.297641,5.438520]"
13
- near_plane = 0.100000
14
- far_plane = 28.000000
15
- alpha_thre = 0
16
- occ_thre = 0.0000001
17
- render_n_samples = 1024
18
- rfilter_sigma = 0.15
19
- sample_as_per_distribution = False
20
- grid_resolution = 128
21
- grid_nlvl = 1
22
-
23
- # timing / sensor
24
- exposure_time = 0.224844343500
25
- bin_width_s_loader = 7.500000000000e-10
26
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
27
- irf_column = "irf"
28
- irf_half_window = 50
29
-
30
- # data
31
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/poses/five_views"
32
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/sp"
33
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
34
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
35
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
36
- invalid_mask_invalid_gt = 10.0
37
- meas_peak_min = 100
38
-
39
- # image size
40
- img_height_test = 192
41
- img_width_test = 256
42
- img_shape_test = 256
43
-
44
- # misc
45
- num_views = 10
46
- device = "cuda:0"
47
- seed = 42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/test/captured/balldesk_quantitative_tenviews.ini DELETED
@@ -1,47 +0,0 @@
1
- # eval job
2
- scene = "balldesk_tenviews"
3
- step = 290000
4
- rep_number = 30
5
- split = "test"
6
- checkpoint_dir = "./results/ours_balldesk"
7
- test_folder_path = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/poses/ten_views"
8
-
9
- # model / rendering
10
- version = captured
11
- n_bins = 672
12
- aabb = "[-20.685711,-15.981851,-1.508756,19.605109,8.297641,5.438520]"
13
- near_plane = 0.100000
14
- far_plane = 28.000000
15
- alpha_thre = 0
16
- occ_thre = 0.0000001
17
- render_n_samples = 1024
18
- rfilter_sigma = 0.15
19
- sample_as_per_distribution = False
20
- grid_resolution = 128
21
- grid_nlvl = 1
22
-
23
- # timing / sensor
24
- exposure_time = 0.224844343500
25
- bin_width_s_loader = 7.500000000000e-10
26
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
27
- irf_column = "irf"
28
- irf_half_window = 50
29
-
30
- # data
31
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/poses/ten_views"
32
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/sp"
33
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
34
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
35
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
36
- invalid_mask_invalid_gt = 10.0
37
- meas_peak_min = 100
38
-
39
- # image size
40
- img_height_test = 192
41
- img_width_test = 256
42
- img_shape_test = 256
43
-
44
- # misc
45
- num_views = 10
46
- device = "cuda:0"
47
- seed = 42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/test/captured/balldesk_quantitative_threeviews.ini DELETED
@@ -1,47 +0,0 @@
1
- # eval job
2
- scene = "balldesk_threeviews"
3
- step = 170000
4
- rep_number = 30
5
- split = "test"
6
- checkpoint_dir = "./results/ours_balldesk_three_views"
7
- test_folder_path = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/poses/three_views"
8
-
9
- # model / rendering
10
- version = captured
11
- n_bins = 672
12
- aabb = "[-20.685711,-15.981851,-1.508756,19.605109,8.297641,5.438520]"
13
- near_plane = 0.100000
14
- far_plane = 28.000000
15
- alpha_thre = 0
16
- occ_thre = 0.0000001
17
- render_n_samples = 1024
18
- rfilter_sigma = 0.15
19
- sample_as_per_distribution = False
20
- grid_resolution = 128
21
- grid_nlvl = 1
22
-
23
- # timing / sensor
24
- exposure_time = 0.224844343500
25
- bin_width_s_loader = 7.500000000000e-10
26
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
27
- irf_column = "irf"
28
- irf_half_window = 50
29
-
30
- # data
31
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/poses/three_views"
32
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/sp"
33
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
34
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
35
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
36
- invalid_mask_invalid_gt = 10.0
37
- meas_peak_min = 100
38
-
39
- # image size
40
- img_height_test = 192
41
- img_width_test = 256
42
- img_shape_test = 256
43
-
44
- # misc
45
- num_views = 10
46
- device = "cuda:0"
47
- seed = 42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/test/captured/designbuilding1_five_views_quantitative.ini DELETED
@@ -1,47 +0,0 @@
1
- # eval job
2
- scene = "designbuilding1_five_views"
3
- step = 290000
4
- rep_number = 30
5
- split = "test"
6
- checkpoint_dir = "./results/designbuilding1_five_views"
7
- test_folder_path = "/work/sdim-lemons/wzt/data/spad_3d/designbuilding1/poses/five_views"
8
-
9
- # model / rendering
10
- version = captured
11
- n_bins = 672
12
- aabb = "[-30.723363,-32.531209,-1.819858,30.377352,12.024207,9.260004]"
13
- near_plane = 0.100000
14
- far_plane = 28.000000
15
- alpha_thre = 0
16
- occ_thre = 0.0000001
17
- render_n_samples = 1024
18
- rfilter_sigma = 0.15
19
- sample_as_per_distribution = False
20
- grid_resolution = 128
21
- grid_nlvl = 1
22
-
23
- # timing / sensor
24
- exposure_time = 0.224844343500
25
- bin_width_s_loader = 7.500000000000e-10
26
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
27
- irf_column = "irf"
28
- irf_half_window = 50
29
-
30
- # data
31
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/designbuilding1/poses/five_views"
32
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/designbuilding1/sp"
33
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
34
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
35
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
36
- invalid_mask_invalid_gt = 10.0
37
- meas_peak_min = 100
38
-
39
- # image size
40
- img_height_test = 192
41
- img_width_test = 256
42
- img_shape_test = 256
43
-
44
- # misc
45
- num_views = 10
46
- device = "cuda:0"
47
- seed = 42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/test/captured/designbuilding1_quantitative_tenviews.ini DELETED
@@ -1,47 +0,0 @@
1
- # eval job
2
- scene = "designbuilding1_ten_views"
3
- step = 290000
4
- rep_number = 30
5
- split = "test"
6
- checkpoint_dir = "./results/designbuilding1_ten_views"
7
- test_folder_path = "/work/sdim-lemons/wzt/data/spad_3d/designbuilding1/poses/ten_views"
8
-
9
- # model / rendering
10
- version = captured
11
- n_bins = 672
12
- aabb = "[-30.723363,-32.531209,-1.819858,30.377352,12.024207,9.260004]"
13
- near_plane = 0.100000
14
- far_plane = 28.000000
15
- alpha_thre = 0
16
- occ_thre = 0.0000001
17
- render_n_samples = 1024
18
- rfilter_sigma = 0.15
19
- sample_as_per_distribution = False
20
- grid_resolution = 128
21
- grid_nlvl = 1
22
-
23
- # timing / sensor
24
- exposure_time = 0.224844343500
25
- bin_width_s_loader = 7.500000000000e-10
26
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
27
- irf_column = "irf"
28
- irf_half_window = 50
29
-
30
- # data
31
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/designbuilding1/poses/ten_views"
32
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/designbuilding1/sp"
33
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
34
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
35
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
36
- invalid_mask_invalid_gt = 10.0
37
- meas_peak_min = 100
38
-
39
- # image size
40
- img_height_test = 192
41
- img_width_test = 256
42
- img_shape_test = 256
43
-
44
- # misc
45
- num_views = 10
46
- device = "cuda:0"
47
- seed = 42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/test/captured/parking_five_views_quantitative.ini DELETED
@@ -1,48 +0,0 @@
1
- # eval job
2
- scene = "parking_five_views"
3
- step = 290000
4
- rep_number = 30
5
- split = "test"
6
- checkpoint_dir = "results/parking_five_views"
7
- test_folder_path = "/work/sdim-lemons/wzt/data/spad_3d/360/parking/poses/five_views"
8
-
9
- # model / rendering
10
- version = captured
11
- n_bins = 672
12
- aabb = "[-30.503840,-28.637896,-2.067505,30.827200,12.873783,5.960705]"
13
- near_plane = 0.100000
14
- far_plane = 30.000000
15
- alpha_thre = 0
16
- occ_thre = 0.0000001
17
- render_n_samples = 1024
18
- rfilter_sigma = 0.15
19
- sample_as_per_distribution = False
20
- grid_resolution = 128
21
- grid_nlvl = 1
22
- meas_peak_min = 20
23
-
24
- # timing / sensor
25
- exposure_time = 0.224844343500
26
- bin_width_s_loader = 7.500000000000e-10
27
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
28
- irf_column = "irf"
29
- irf_half_window = 50
30
-
31
- # data
32
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/360/parking/poses/five_views"
33
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/360/parking/sp"
34
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
35
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
36
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
37
- invalid_mask_invalid_gt = 10.0
38
- meas_peak_min = 100
39
-
40
- # image size
41
- img_height_test = 192
42
- img_width_test = 256
43
- img_shape_test = 256
44
-
45
- # misc
46
- num_views = 10
47
- device = "cuda:0"
48
- seed = 42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/test/captured/parking_ten_views_quantitative.ini DELETED
@@ -1,48 +0,0 @@
1
- # eval job
2
- scene = "parking_ten_views"
3
- step = 290000
4
- rep_number = 30
5
- split = "test"
6
- checkpoint_dir = "results/parking_ten_views"
7
- test_folder_path = "/work/sdim-lemons/wzt/data/spad_3d/360/parking/poses/ten_views"
8
-
9
- # model / rendering
10
- version = captured
11
- n_bins = 672
12
- aabb = "[-30.503840,-28.637896,-2.067505,30.827200,12.873783,5.960705]"
13
- near_plane = 0.100000
14
- far_plane = 30.000000
15
- alpha_thre = 0
16
- occ_thre = 0.0000001
17
- render_n_samples = 1024
18
- rfilter_sigma = 0.15
19
- sample_as_per_distribution = False
20
- grid_resolution = 128
21
- grid_nlvl = 1
22
- meas_peak_min = 20
23
-
24
- # timing / sensor
25
- exposure_time = 0.224844343500
26
- bin_width_s_loader = 7.500000000000e-10
27
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
28
- irf_column = "irf"
29
- irf_half_window = 50
30
-
31
- # data
32
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/360/parking/poses/ten_views"
33
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/360/parking/sp"
34
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
35
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
36
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
37
- invalid_mask_invalid_gt = 10.0
38
- meas_peak_min = 100
39
-
40
- # image size
41
- img_height_test = 192
42
- img_width_test = 256
43
- img_shape_test = 256
44
-
45
- # misc
46
- num_views = 10
47
- device = "cuda:0"
48
- seed = 42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/test/captured/physics_building2_ten_views_quantitative.ini DELETED
@@ -1,48 +0,0 @@
1
- # eval job
2
- scene = "physics_building2_ten_views"
3
- step = 290000
4
- rep_number = 30
5
- split = "test"
6
- checkpoint_dir = "results/physics_building2_ten_views"
7
- test_folder_path = "/work/sdim-lemons/wzt/data/spad_3d/360/physics_building2/poses/ten_views"
8
-
9
- # model / rendering
10
- version = captured
11
- n_bins = 672
12
- aabb = "[-30.008253,-20.426221,-1.811843,20.122535,20.849413,10.086755]"
13
- near_plane = 0.100000
14
- far_plane = 38.000000
15
- alpha_thre = 0
16
- occ_thre = 0.0000001
17
- render_n_samples = 1024
18
- rfilter_sigma = 0.15
19
- sample_as_per_distribution = False
20
- grid_resolution = 128
21
- grid_nlvl = 1
22
- meas_peak_min = 10
23
-
24
- # timing / sensor
25
- exposure_time = 0.224844343500
26
- bin_width_s_loader = 7.500000000000e-10
27
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
28
- irf_column = "irf"
29
- irf_half_window = 50
30
-
31
- # data
32
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/360/physics_building2/poses/ten_views"
33
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/360/physics_building2/sp"
34
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
35
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
36
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
37
- invalid_mask_invalid_gt = 10.0
38
- meas_peak_min = 100
39
-
40
- # image size
41
- img_height_test = 192
42
- img_width_test = 256
43
- img_shape_test = 256
44
-
45
- # misc
46
- num_views = 10
47
- device = "cuda:0"
48
- seed = 42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/test/captured/physics_building2_ten_views_quantitative1.ini DELETED
@@ -1,48 +0,0 @@
1
- # eval job
2
- scene = "physics_building2_ten_views"
3
- step = 100000
4
- rep_number = 30
5
- split = "test"
6
- checkpoint_dir = "results/physics_building2_ten_views0"
7
- test_folder_path = "/work/sdim-lemons/wzt/data/spad_3d/360/physics_building2/poses/ten_views"
8
-
9
- # model / rendering
10
- version = captured
11
- n_bins = 672
12
- aabb = "[-30.008253,-20.426221,-1.811843,20.122535,20.849413,10.086755]"
13
- near_plane = 0.100000
14
- far_plane = 38.000000
15
- alpha_thre = 0
16
- occ_thre = 0.0000001
17
- render_n_samples = 1024
18
- rfilter_sigma = 0.15
19
- sample_as_per_distribution = False
20
- grid_resolution = 128
21
- grid_nlvl = 1
22
- meas_peak_min = 10
23
-
24
- # timing / sensor
25
- exposure_time = 0.224844343500
26
- bin_width_s_loader = 7.500000000000e-10
27
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
28
- irf_column = "irf"
29
- irf_half_window = 50
30
-
31
- # data
32
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/360/physics_building2/poses/ten_views"
33
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/360/physics_building2/sp"
34
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
35
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
36
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
37
- invalid_mask_invalid_gt = 10.0
38
- meas_peak_min = 100
39
-
40
- # image size
41
- img_height_test = 192
42
- img_width_test = 256
43
- img_shape_test = 256
44
-
45
- # misc
46
- num_views = 10
47
- device = "cuda:0"
48
- seed = 42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/train/captured/artbuilding3_five_views.ini DELETED
@@ -1,50 +0,0 @@
1
- exp_name = "artbuilding3_five_views"
2
- test_chunk_size = 256
3
- num_rays_per_batch = 512
4
- starting_rays_per_pixel = 1
5
- tfilter_sigma = 3
6
- rfilter_sigma = 0.15
7
- space_carving = 0.0
8
- lr = 0.0001
9
- num_views = 10
10
-
11
- n_bins = 672
12
- aabb = "[-25.379819,-15.216244,-2.908998,29.218790,32.190764,16.977430]"
13
- version = "captured"
14
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/artbuilding3/poses/five_views"
15
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/artbuilding3/sp"
16
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
17
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
18
- irf_column = "irf"
19
- irf_half_window = 50
20
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
21
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
22
- invalid_mask_invalid_gt = 10.0
23
- exposure_time = 0.224844343500
24
- bin_width_s_loader = 7.500000000000e-10
25
-
26
- thold_warmup = 80000
27
- max_steps = 300001
28
- img_height = 192
29
- img_width = 256
30
- img_height_test = 192
31
- img_width_test = 256
32
- img_shape = 256
33
- img_shape_test = 256
34
- near_plane = 0.100000
35
- far_plane = 28.000000
36
- alpha_thre = 0
37
- occ_thre = 0.0000001
38
- sample_as_per_distribution = False
39
- render_n_samples = 1024
40
- exp = True
41
- final = True
42
- steps_til_checkpoint = 10000
43
- grid_resolution = 128
44
- grid_nlvl = 1
45
- outpath = "./results"
46
- pixels_to_plot = ["(40, 60)", "(60, 100)", "(80, 60)"]
47
- img_scale = 100
48
- seed = 42
49
- device = "cuda:0"
50
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/train/captured/artbuilding3_ten_views.ini DELETED
@@ -1,50 +0,0 @@
1
- exp_name = "artbuilding3_ten_views"
2
- test_chunk_size = 256
3
- num_rays_per_batch = 512
4
- starting_rays_per_pixel = 1
5
- tfilter_sigma = 3
6
- rfilter_sigma = 0.15
7
- space_carving = 0.0
8
- lr = 0.0001
9
- num_views = 10
10
-
11
- n_bins = 672
12
- aabb = "[-25.379819,-15.216244,-2.908998,29.218790,32.190764,16.977430]"
13
- version = "captured"
14
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/artbuilding3/poses/ten_views"
15
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/artbuilding3/sp"
16
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
17
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
18
- irf_column = "irf"
19
- irf_half_window = 50
20
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
21
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
22
- invalid_mask_invalid_gt = 10.0
23
- exposure_time = 0.224844343500
24
- bin_width_s_loader = 7.500000000000e-10
25
-
26
- thold_warmup = 80000
27
- max_steps = 300001
28
- img_height = 192
29
- img_width = 256
30
- img_height_test = 192
31
- img_width_test = 256
32
- img_shape = 256
33
- img_shape_test = 256
34
- near_plane = 0.100000
35
- far_plane = 28.000000
36
- alpha_thre = 0
37
- occ_thre = 0.0000001
38
- sample_as_per_distribution = False
39
- render_n_samples = 1024
40
- exp = True
41
- final = True
42
- steps_til_checkpoint = 10000
43
- grid_resolution = 128
44
- grid_nlvl = 1
45
- outpath = "./results"
46
- pixels_to_plot = ["(40, 60)", "(60, 100)", "(80, 60)"]
47
- img_scale = 100
48
- seed = 42
49
- device = "cuda:0"
50
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/train/captured/designbuilding1_five_views.ini DELETED
@@ -1,50 +0,0 @@
1
- exp_name = "designbuilding1_five_views"
2
- test_chunk_size = 256
3
- num_rays_per_batch = 512
4
- starting_rays_per_pixel = 1
5
- tfilter_sigma = 3
6
- rfilter_sigma = 0.15
7
- space_carving = 0.0
8
- lr = 0.0001
9
- num_views = 10
10
-
11
- n_bins = 672
12
- aabb = "[-30.723363,-32.531209,-1.819858,30.377352,12.024207,9.260004]"
13
- version = "captured"
14
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/designbuilding1/poses/five_views"
15
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/designbuilding1/sp"
16
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
17
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
18
- irf_column = "irf"
19
- irf_half_window = 50
20
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
21
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
22
- invalid_mask_invalid_gt = 10.0
23
- exposure_time = 0.224844343500
24
- bin_width_s_loader = 7.500000000000e-10
25
-
26
- thold_warmup = 80000
27
- max_steps = 300001
28
- img_height = 192
29
- img_width = 256
30
- img_height_test = 192
31
- img_width_test = 256
32
- img_shape = 256
33
- img_shape_test = 256
34
- near_plane = 0.100000
35
- far_plane = 28.000000
36
- alpha_thre = 0
37
- occ_thre = 0.0000001
38
- sample_as_per_distribution = False
39
- render_n_samples = 1024
40
- exp = True
41
- final = True
42
- steps_til_checkpoint = 10000
43
- grid_resolution = 128
44
- grid_nlvl = 1
45
- outpath = "./results"
46
- pixels_to_plot = ["(40, 60)", "(60, 100)", "(80, 60)"]
47
- img_scale = 100
48
- seed = 42
49
- device = "cuda:0"
50
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/train/captured/designbuilding1_tenviews.ini DELETED
@@ -1,50 +0,0 @@
1
- exp_name = "designbuilding1_ten_views"
2
- test_chunk_size = 256
3
- num_rays_per_batch = 512
4
- starting_rays_per_pixel = 1
5
- tfilter_sigma = 3
6
- rfilter_sigma = 0.15
7
- space_carving = 0.0
8
- lr = 0.0001
9
- num_views = 10
10
-
11
- n_bins = 672
12
- aabb = "[-30.723363,-32.531209,-1.819858,30.377352,12.024207,9.260004]"
13
- version = "captured"
14
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/designbuilding1/poses/ten_views"
15
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/designbuilding1/sp"
16
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
17
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
18
- irf_column = "irf"
19
- irf_half_window = 50
20
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
21
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
22
- invalid_mask_invalid_gt = 10.0
23
- exposure_time = 0.224844343500
24
- bin_width_s_loader = 7.500000000000e-10
25
-
26
- thold_warmup = 80000
27
- max_steps = 300001
28
- img_height = 192
29
- img_width = 256
30
- img_height_test = 192
31
- img_width_test = 256
32
- img_shape = 256
33
- img_shape_test = 256
34
- near_plane = 0.100000
35
- far_plane = 28.000000
36
- alpha_thre = 0
37
- occ_thre = 0.0000001
38
- sample_as_per_distribution = False
39
- render_n_samples = 1024
40
- exp = True
41
- final = True
42
- steps_til_checkpoint = 10000
43
- grid_resolution = 128
44
- grid_nlvl = 1
45
- outpath = "./results"
46
- pixels_to_plot = ["(40, 60)", "(60, 100)", "(80, 60)"]
47
- img_scale = 100
48
- seed = 42
49
- device = "cuda:0"
50
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/train/captured/material_building_five_views.ini DELETED
@@ -1,51 +0,0 @@
1
- exp_name = "material_building_five_views"
2
- test_chunk_size = 256
3
- num_rays_per_batch = 512
4
- starting_rays_per_pixel = 1
5
- tfilter_sigma = 3
6
- rfilter_sigma = 0.15
7
- space_carving = 0.0
8
- lr = 0.0001
9
- num_views = 10
10
-
11
- n_bins = 672
12
- aabb = "[-14.996998,-4.556170,-3.767088,54.273853,33.048301,29.515029]"
13
- version = "captured"
14
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/360/material_building/poses/five_views"
15
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/360/material_building/sp"
16
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
17
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
18
- irf_column = "irf"
19
- irf_half_window = 50
20
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
21
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
22
- invalid_mask_invalid_gt = 10.0
23
- exposure_time = 0.224844343500
24
- bin_width_s_loader = 7.500000000000e-10
25
- meas_peak_min = 20
26
-
27
- thold_warmup = 80000
28
- max_steps = 300001
29
- img_height = 192
30
- img_width = 256
31
- img_height_test = 192
32
- img_width_test = 256
33
- img_shape = 256
34
- img_shape_test = 256
35
- near_plane = 0.100000
36
- far_plane = 55.000000
37
- alpha_thre = 0
38
- occ_thre = 0.0000001
39
- sample_as_per_distribution = False
40
- render_n_samples = 1024
41
- exp = True
42
- final = True
43
- steps_til_checkpoint = 10000
44
- grid_resolution = 128
45
- grid_nlvl = 1
46
- outpath = "./results"
47
- pixels_to_plot = ["(40, 60)", "(60, 100)", "(80, 60)"]
48
- img_scale = 100
49
- seed = 42
50
- device = "cuda:0"
51
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/train/captured/material_building_ten_views.ini DELETED
@@ -1,51 +0,0 @@
1
- exp_name = "material_building_ten_views"
2
- test_chunk_size = 256
3
- num_rays_per_batch = 512
4
- starting_rays_per_pixel = 1
5
- tfilter_sigma = 3
6
- rfilter_sigma = 0.15
7
- space_carving = 0.0
8
- lr = 0.0001
9
- num_views = 10
10
-
11
- n_bins = 672
12
- aabb = "[-14.996998,-4.556170,-3.767088,54.273853,33.048301,29.515029]"
13
- version = "captured"
14
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/360/material_building/poses/ten_views"
15
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/360/material_building/sp"
16
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
17
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
18
- irf_column = "irf"
19
- irf_half_window = 50
20
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
21
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
22
- invalid_mask_invalid_gt = 10.0
23
- exposure_time = 0.224844343500
24
- bin_width_s_loader = 7.500000000000e-10
25
- meas_peak_min = 20
26
-
27
- thold_warmup = 80000
28
- max_steps = 300001
29
- img_height = 192
30
- img_width = 256
31
- img_height_test = 192
32
- img_width_test = 256
33
- img_shape = 256
34
- img_shape_test = 256
35
- near_plane = 0.100000
36
- far_plane = 55.000000
37
- alpha_thre = 0
38
- occ_thre = 0.0000001
39
- sample_as_per_distribution = False
40
- render_n_samples = 1024
41
- exp = True
42
- final = True
43
- steps_til_checkpoint = 10000
44
- grid_resolution = 128
45
- grid_nlvl = 1
46
- outpath = "./results"
47
- pixels_to_plot = ["(40, 60)", "(60, 100)", "(80, 60)"]
48
- img_scale = 100
49
- seed = 42
50
- device = "cuda:0"
51
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/train/captured/parking_five_views.ini DELETED
@@ -1,51 +0,0 @@
1
- exp_name = "parking_five_views"
2
- test_chunk_size = 256
3
- num_rays_per_batch = 512
4
- starting_rays_per_pixel = 1
5
- tfilter_sigma = 3
6
- rfilter_sigma = 0.15
7
- space_carving = 0.0
8
- lr = 0.0001
9
- num_views = 10
10
-
11
- n_bins = 672
12
- aabb = "[-30.503840,-28.637896,-2.067505,30.827200,12.873783,5.960705]"
13
- version = "captured"
14
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/360/parking/poses/five_views"
15
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/360/parking/sp"
16
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
17
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
18
- irf_column = "irf"
19
- irf_half_window = 50
20
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
21
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
22
- invalid_mask_invalid_gt = 10.0
23
- exposure_time = 0.224844343500
24
- bin_width_s_loader = 7.500000000000e-10
25
- meas_peak_min = 20
26
-
27
- thold_warmup = 80000
28
- max_steps = 300001
29
- img_height = 192
30
- img_width = 256
31
- img_height_test = 192
32
- img_width_test = 256
33
- img_shape = 256
34
- img_shape_test = 256
35
- near_plane = 0.100000
36
- far_plane = 30.000000
37
- alpha_thre = 0
38
- occ_thre = 0.0000001
39
- sample_as_per_distribution = False
40
- render_n_samples = 1024
41
- exp = True
42
- final = True
43
- steps_til_checkpoint = 10000
44
- grid_resolution = 128
45
- grid_nlvl = 1
46
- outpath = "./results"
47
- pixels_to_plot = ["(40, 60)", "(60, 100)", "(80, 60)"]
48
- img_scale = 100
49
- seed = 42
50
- device = "cuda:0"
51
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/train/captured/parking_ten_views.ini DELETED
@@ -1,51 +0,0 @@
1
- exp_name = "parking_ten_views"
2
- test_chunk_size = 256
3
- num_rays_per_batch = 512
4
- starting_rays_per_pixel = 1
5
- tfilter_sigma = 3
6
- rfilter_sigma = 0.15
7
- space_carving = 0.0
8
- lr = 0.0001
9
- num_views = 10
10
-
11
- n_bins = 672
12
- aabb = "[-30.503840,-28.637896,-2.067505,30.827200,12.873783,5.960705]"
13
- version = "captured"
14
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/360/parking/poses/ten_views"
15
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/360/parking/sp"
16
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
17
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
18
- irf_column = "irf"
19
- irf_half_window = 50
20
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
21
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
22
- invalid_mask_invalid_gt = 10.0
23
- exposure_time = 0.224844343500
24
- bin_width_s_loader = 7.500000000000e-10
25
- meas_peak_min = 20
26
-
27
- thold_warmup = 80000
28
- max_steps = 300001
29
- img_height = 192
30
- img_width = 256
31
- img_height_test = 192
32
- img_width_test = 256
33
- img_shape = 256
34
- img_shape_test = 256
35
- near_plane = 0.100000
36
- far_plane = 30.000000
37
- alpha_thre = 0
38
- occ_thre = 0.0000001
39
- sample_as_per_distribution = False
40
- render_n_samples = 1024
41
- exp = True
42
- final = True
43
- steps_til_checkpoint = 10000
44
- grid_resolution = 128
45
- grid_nlvl = 1
46
- outpath = "./results"
47
- pixels_to_plot = ["(40, 60)", "(60, 100)", "(80, 60)"]
48
- img_scale = 100
49
- seed = 42
50
- device = "cuda:0"
51
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/train/captured/physics_building2_ten_views.ini DELETED
@@ -1,51 +0,0 @@
1
- exp_name = "physics_building2_ten_views"
2
- test_chunk_size = 256
3
- num_rays_per_batch = 512
4
- starting_rays_per_pixel = 1
5
- tfilter_sigma = 3
6
- rfilter_sigma = 0.15
7
- space_carving = 0.0
8
- lr = 0.0001
9
- num_views = 10
10
-
11
- n_bins = 672
12
- aabb = "[-30.008253,-20.426221,-1.811843,20.122535,20.849413,10.086755]"
13
- version = "captured"
14
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/360/physics_building2/poses/ten_views"
15
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/360/physics_building2/sp"
16
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
17
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
18
- irf_column = "irf"
19
- irf_half_window = 50
20
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
21
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
22
- invalid_mask_invalid_gt = 10.0
23
- exposure_time = 0.224844343500
24
- bin_width_s_loader = 7.500000000000e-10
25
- meas_peak_min = 10
26
-
27
- thold_warmup = 80000
28
- max_steps = 300001
29
- img_height = 192
30
- img_width = 256
31
- img_height_test = 192
32
- img_width_test = 256
33
- img_shape = 256
34
- img_shape_test = 256
35
- near_plane = 0.100000
36
- far_plane = 38.000000
37
- alpha_thre = 0
38
- occ_thre = 0.0000001
39
- sample_as_per_distribution = False
40
- render_n_samples = 1024
41
- exp = True
42
- final = True
43
- steps_til_checkpoint = 10000
44
- grid_resolution = 128
45
- grid_nlvl = 1
46
- outpath = "./results"
47
- pixels_to_plot = ["(40, 60)", "(60, 100)", "(80, 60)"]
48
- img_scale = 100
49
- seed = 42
50
- device = "cuda:0"
51
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/train/captured/tfnerf_balldesk_fiveviews.ini DELETED
@@ -1,50 +0,0 @@
1
- exp_name = "ours_balldesk_five_views"
2
- test_chunk_size = 256
3
- num_rays_per_batch = 512
4
- starting_rays_per_pixel = 1
5
- tfilter_sigma = 3
6
- rfilter_sigma = 0.15
7
- space_carving = 0.0
8
- lr = 0.0001
9
- num_views = 10
10
-
11
- n_bins = 672
12
- aabb = "[-20.685711,-15.981851,-1.508756,19.605109,8.297641,5.438520]"
13
- version = "captured"
14
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/poses/five_views"
15
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/sp"
16
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
17
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
18
- irf_column = "irf"
19
- irf_half_window = 50
20
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
21
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
22
- invalid_mask_invalid_gt = 10.0
23
- exposure_time = 0.224844343500
24
- bin_width_s_loader = 7.500000000000e-10
25
-
26
- thold_warmup = 80000
27
- max_steps = 300001
28
- img_height = 192
29
- img_width = 256
30
- img_height_test = 192
31
- img_width_test = 256
32
- img_shape = 256
33
- img_shape_test = 256
34
- near_plane = 0.100000
35
- far_plane = 28.000000
36
- alpha_thre = 0
37
- occ_thre = 0.0000001
38
- sample_as_per_distribution = False
39
- render_n_samples = 1024
40
- exp = True
41
- final = True
42
- steps_til_checkpoint = 10000
43
- grid_resolution = 128
44
- grid_nlvl = 1
45
- outpath = "./results"
46
- pixels_to_plot = ["(40, 60)", "(60, 100)", "(80, 60)"]
47
- img_scale = 100
48
- seed = 42
49
- device = "cuda:0"
50
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/train/captured/tfnerf_balldesk_tenviews.ini DELETED
@@ -1,50 +0,0 @@
1
- exp_name = "ours_balldesk"
2
- test_chunk_size = 256
3
- num_rays_per_batch = 512
4
- starting_rays_per_pixel = 1
5
- tfilter_sigma = 3
6
- rfilter_sigma = 0.15
7
- space_carving = 0.0
8
- lr = 0.0001
9
- num_views = 10
10
-
11
- n_bins = 672
12
- aabb = "[-20.685711,-15.981851,-1.508756,19.605109,8.297641,5.438520]"
13
- version = "captured"
14
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/poses/ten_views"
15
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/sp"
16
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
17
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
18
- irf_column = "irf"
19
- irf_half_window = 50
20
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
21
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
22
- invalid_mask_invalid_gt = 10.0
23
- exposure_time = 0.224844343500
24
- bin_width_s_loader = 7.500000000000e-10
25
-
26
- thold_warmup = 80000
27
- max_steps = 300001
28
- img_height = 192
29
- img_width = 256
30
- img_height_test = 192
31
- img_width_test = 256
32
- img_shape = 256
33
- img_shape_test = 256
34
- near_plane = 0.100000
35
- far_plane = 28.000000
36
- alpha_thre = 0
37
- occ_thre = 0.0000001
38
- sample_as_per_distribution = False
39
- render_n_samples = 1024
40
- exp = True
41
- final = True
42
- steps_til_checkpoint = 10000
43
- grid_resolution = 128
44
- grid_nlvl = 1
45
- outpath = "./results"
46
- pixels_to_plot = ["(40, 60)", "(60, 100)", "(80, 60)"]
47
- img_scale = 100
48
- seed = 42
49
- device = "cuda:0"
50
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/configs/train/captured/tfnerf_balldesk_threeviews.ini DELETED
@@ -1,50 +0,0 @@
1
- exp_name = "ours_balldesk_three_views"
2
- test_chunk_size = 256
3
- num_rays_per_batch = 512
4
- starting_rays_per_pixel = 1
5
- tfilter_sigma = 3
6
- rfilter_sigma = 0.15
7
- space_carving = 0.0
8
- lr = 0.0001
9
- num_views = 10
10
-
11
- n_bins = 672
12
- aabb = "[-20.685711,-15.981851,-1.508756,19.605109,8.297641,5.438520]"
13
- version = "captured"
14
- data_root_fp = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/poses/three_views"
15
- measurement_root = "/work/sdim-lemons/wzt/data/spad_3d/balldesk/sp"
16
- data_exts = ".npz,.txt,.pt,.h5,.hdf5"
17
- irf_path = "/work/sdim-lemons/wzt/data/transient_nets/IRF_global.csv"
18
- irf_column = "irf"
19
- irf_half_window = 50
20
- intrinsics = "/work/sdim-lemons/wzt/data/transient_nets/intrinsics.npy"
21
- invalid_mask_path = "/work/sdim-lemons/wzt/data/transient_nets/offset.txt"
22
- invalid_mask_invalid_gt = 10.0
23
- exposure_time = 0.224844343500
24
- bin_width_s_loader = 7.500000000000e-10
25
-
26
- thold_warmup = 80000
27
- max_steps = 300001
28
- img_height = 192
29
- img_width = 256
30
- img_height_test = 192
31
- img_width_test = 256
32
- img_shape = 256
33
- img_shape_test = 256
34
- near_plane = 0.100000
35
- far_plane = 28.000000
36
- alpha_thre = 0
37
- occ_thre = 0.0000001
38
- sample_as_per_distribution = False
39
- render_n_samples = 1024
40
- exp = True
41
- final = True
42
- steps_til_checkpoint = 10000
43
- grid_resolution = 128
44
- grid_nlvl = 1
45
- outpath = "./results"
46
- pixels_to_plot = ["(40, 60)", "(60, 100)", "(80, 60)"]
47
- img_scale = 100
48
- seed = 42
49
- device = "cuda:0"
50
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/eval.py DELETED
@@ -1,556 +0,0 @@
1
- import csv
2
- import json
3
- import math
4
- import os
5
-
6
- import imageio
7
- import lpips
8
- import matplotlib.pyplot as plt
9
- import numpy as np
10
- import pandas as pd
11
- import scipy.io as sio
12
- import torch
13
- import tqdm
14
- from nerfacc import OccGridEstimator
15
- from skimage.metrics import structural_similarity
16
-
17
- from misc.dataset_utils import read_h5
18
- from misc.eval_utils import load_eval_args, read_json
19
- from misc.transient_volrend import torch_laser_kernel
20
- from radiance_fields.ngp import NGPRadianceField
21
- from utils import render_transient
22
-
23
-
24
- def _to_numpy(x):
25
- if isinstance(x, np.ndarray):
26
- return x
27
- if isinstance(x, torch.Tensor):
28
- return x.detach().cpu().numpy()
29
- return np.asarray(x)
30
-
31
-
32
- def get_gt_depth(frame, camtoworld, data_root_fp):
33
- depth_folder = os.path.join(data_root_fp, "test")
34
- number = int(frame["file_path"].split("_")[-1])
35
- ax_flip = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1]])
36
-
37
- try:
38
- fname = os.path.join(depth_folder, f"test_{number:03d}_depth_gt.npy")
39
- pos3d = np.load(fname)
40
- except Exception:
41
- fname = os.path.join(depth_folder, f"test_{number:03d}_depth_gt.h5")
42
- pos3d = read_h5(fname)
43
-
44
- cam_pos = (ax_flip @ camtoworld)[:3, -1]
45
- depth = np.sqrt(((pos3d - cam_pos[None, None, :]) ** 2).sum(-1))
46
- return depth.astype(np.float32)
47
-
48
-
49
- def _safe_psnr(gt, pred, mask=None):
50
- gt = np.asarray(gt, dtype=np.float64)
51
- pred = np.asarray(pred, dtype=np.float64)
52
-
53
- if mask is not None:
54
- mask = np.asarray(mask, dtype=bool)
55
- if gt.ndim == 3:
56
- if not np.any(mask):
57
- return float("nan")
58
- gt_eval = gt[mask]
59
- pred_eval = pred[mask]
60
- else:
61
- if not np.any(mask):
62
- return float("nan")
63
- gt_eval = gt[mask]
64
- pred_eval = pred[mask]
65
- else:
66
- gt_eval = gt.reshape(-1)
67
- pred_eval = pred.reshape(-1)
68
-
69
- if gt_eval.size == 0:
70
- return float("nan")
71
-
72
- mse = np.mean((gt_eval - pred_eval) ** 2)
73
- max_val = max(float(np.max(gt_eval)), float(np.max(pred_eval)), 1e-8)
74
- return float(20.0 * np.log10(max_val / np.sqrt(mse + 1e-12)))
75
-
76
-
77
- def _save_metrics_csv(path, rows):
78
- if not rows:
79
- return
80
- fieldnames = list(rows[0].keys())
81
- with open(path, "w", newline="", encoding="utf-8") as f:
82
- writer = csv.DictWriter(f, fieldnames=fieldnames)
83
- writer.writeheader()
84
- writer.writerows(rows)
85
-
86
-
87
- def _to_lpips_input(img_01):
88
- img_rgb = np.repeat(img_01[..., None], 3, axis=2).astype(np.float32)
89
- ten = torch.from_numpy(img_rgb).permute(2, 0, 1).unsqueeze(0)
90
- ten = ten * 2.0 - 1.0
91
- return ten
92
-
93
-
94
- def _frame_token(frame_dict):
95
- raw = str(frame_dict.get("file_path", frame_dict.get("filepath", "")))
96
- return os.path.splitext(os.path.basename(raw))[0]
97
-
98
-
99
- def _normalize_for_vis(img: np.ndarray, mask: np.ndarray = None, q_low: float = 1.0, q_high: float = 99.5):
100
- arr = np.asarray(img, dtype=np.float32)
101
- if mask is not None:
102
- m = np.asarray(mask, dtype=bool)
103
- vals = arr[m]
104
- else:
105
- vals = arr.reshape(-1)
106
- vals = vals[np.isfinite(vals)]
107
- if vals.size == 0:
108
- return np.zeros_like(arr, dtype=np.float32)
109
-
110
- lo = float(np.percentile(vals, q_low))
111
- hi = float(np.percentile(vals, q_high))
112
- if not np.isfinite(lo) or not np.isfinite(hi) or hi <= lo:
113
- hi = lo + 1e-6
114
- out = (arr - lo) / (hi - lo)
115
- return np.clip(out, 0.0, 1.0)
116
-
117
-
118
- def _extract_intensity_from_hist(hist: np.ndarray) -> np.ndarray:
119
- hist = np.asarray(hist, dtype=np.float32)
120
- if hist.ndim != 4:
121
- raise ValueError(f"Expected histogram with shape [H, W, n_bins, C], got {hist.shape}")
122
-
123
- # Use peak intensity over time bins instead of temporal sum.
124
- peak_rgb = hist.max(axis=-2)
125
- return peak_rgb[..., 0].astype(np.float32)
126
-
127
-
128
- def _to_gamma_domain(img_01: np.ndarray, gamma: float = 2.2) -> np.ndarray:
129
- img_01 = np.asarray(img_01, dtype=np.float32)
130
- return np.clip(img_01, 0.0, 1.0) ** (1.0 / gamma)
131
-
132
-
133
- def _load_irf_series(path: str, column: str) -> np.ndarray:
134
- ext = os.path.splitext(path)[1].lower()
135
- if ext == ".csv":
136
- df = pd.read_csv(path, sep=",")
137
- if column in df.columns:
138
- arr = df[column].to_numpy(dtype=np.float64)
139
- else:
140
- numeric_cols = [c for c in df.columns if np.issubdtype(df[c].dtype, np.number)]
141
- if not numeric_cols:
142
- raise ValueError(f"No numeric columns found in IRF CSV: {path}")
143
- arr = df[numeric_cols[0]].to_numpy(dtype=np.float64)
144
- return arr.squeeze()
145
- if ext == ".npy":
146
- return np.load(path).astype(np.float64).squeeze()
147
- if ext == ".mat":
148
- mat = sio.loadmat(path)
149
- if "out" in mat:
150
- return _to_numpy(mat["out"]).astype(np.float64).squeeze()
151
- for value in mat.values():
152
- if isinstance(value, np.ndarray) and value.ndim >= 1 and value.size > 1:
153
- return _to_numpy(value).astype(np.float64).squeeze()
154
- raise ValueError(f"Cannot find valid IRF series in mat file: {path}")
155
- if ext == ".pt":
156
- return _to_numpy(torch.load(path, map_location="cpu")).astype(np.float64).squeeze()
157
- raise ValueError(f"Unsupported IRF extension: {ext}")
158
-
159
-
160
- def build_irf_kernel(args, device):
161
- irf_path = getattr(args, "irf_path", "") or args.pulse_path
162
- if not irf_path:
163
- raise ValueError("IRF path is empty. Set --irf_path or --pulse_path.")
164
-
165
- irf_column = getattr(args, "irf_column", "irf")
166
- irf_half_window = int(getattr(args, "irf_half_window", 50))
167
- no_irf_reverse = bool(getattr(args, "no_irf_reverse", False))
168
-
169
- irf = _load_irf_series(irf_path, irf_column)
170
- if irf.ndim != 1:
171
- irf = irf.reshape(-1)
172
- if irf.size == 0:
173
- raise ValueError(f"Loaded empty IRF from: {irf_path}")
174
-
175
- peak_idx = int(np.argmax(irf))
176
- if irf_half_window > 0:
177
- lo = max(0, peak_idx - irf_half_window)
178
- hi = min(len(irf), peak_idx + irf_half_window + 1)
179
- irf = irf[lo:hi]
180
-
181
- irf = irf / (irf.sum() + 1e-8)
182
- if not no_irf_reverse:
183
- irf = irf[::-1].copy()
184
-
185
- laser = torch.tensor(irf, dtype=torch.float32, device=device)
186
- return torch_laser_kernel(laser, device=device)
187
-
188
-
189
- @torch.no_grad()
190
- def eval():
191
- args = load_eval_args()
192
- print("version =", args.version)
193
-
194
- device = args.device
195
- scale_int = float(args.scale_int)
196
- if scale_int <= 0:
197
- raise ValueError(f"scale_int must be > 0, got {scale_int}")
198
- print(f"Using fixed intensity scale from config: {scale_int}")
199
-
200
- ckpt_dir = args.checkpoint_dir
201
- outpath = os.path.join(args.checkpoint_dir, "results_revise")
202
- os.makedirs(outpath, exist_ok=True)
203
-
204
- transforms_path = os.path.join(args.test_folder_path, f"transforms_{args.split}.json")
205
- positions = read_json(transforms_path)
206
- frames = positions.get("frames", [])
207
- print(f"Using transforms: {transforms_path} (split={args.split}, frames={len(frames)})")
208
- if args.split == "test":
209
- train_tf_path = os.path.join(args.test_folder_path, "transforms_train.json")
210
- if os.path.isfile(train_tf_path):
211
- train_positions = read_json(train_tf_path)
212
- train_frames = train_positions.get("frames", [])
213
- test_ids = {_frame_token(f) for f in frames}
214
- train_ids = {_frame_token(f) for f in train_frames}
215
- overlap = sorted(test_ids.intersection(train_ids))
216
- if overlap:
217
- print(
218
- f"[WARN] test/train overlap detected: {len(overlap)} shared frame ids. "
219
- f"Examples: {overlap[:10]}"
220
- )
221
- else:
222
- print("Train/test overlap check: no shared frame ids.")
223
- else:
224
- print(f"Train overlap check skipped: not found {train_tf_path}")
225
-
226
- used_views = []
227
- for idx, f in enumerate(frames):
228
- raw = str(f.get("file_path", f.get("filepath", "")))
229
- used_views.append(
230
- {
231
- "index": idx,
232
- "frame_file_path": raw,
233
- "frame_name": os.path.basename(raw),
234
- "frame_stem": _frame_token(f),
235
- }
236
- )
237
- used_views_json_path = os.path.join(outpath, f"{args.scene}_{args.num_views}_{args.step}_used_views.json")
238
- used_views_csv_path = os.path.join(outpath, f"{args.scene}_{args.num_views}_{args.step}_used_views.csv")
239
- used_views_txt_path = os.path.join(outpath, f"{args.scene}_{args.num_views}_{args.step}_used_views.txt")
240
- with open(used_views_json_path, "w", encoding="utf-8") as f:
241
- json.dump(
242
- {
243
- "split": args.split,
244
- "transforms_path": transforms_path,
245
- "num_frames": len(used_views),
246
- "views": used_views,
247
- },
248
- f,
249
- indent=2,
250
- )
251
- _save_metrics_csv(used_views_csv_path, used_views)
252
- with open(used_views_txt_path, "w", encoding="utf-8") as f:
253
- for v in used_views:
254
- f.write(f"{v['index']}\t{v['frame_file_path']}\n")
255
- print(f"Saved used-view list: {used_views_json_path}")
256
-
257
- ckpt_path_rf = os.path.join(ckpt_dir, f"radiance_field_{args.step:04d}.pth")
258
- ckpt_path_oc = os.path.join(ckpt_dir, f"occupancy_grid_{args.step:04d}.pth")
259
-
260
- aabb = torch.tensor(args.aabb, dtype=torch.float32, device=device)
261
- img_h = int(getattr(args, "img_height_test", None) or args.img_shape_test)
262
- img_w = int(getattr(args, "img_width_test", None) or args.img_shape_test)
263
- img_shape = (img_h, img_w)
264
-
265
- if args.version == "simulated":
266
- from loaders.loader_synthetic import SubjectLoaderTransient as SubjectLoader
267
-
268
- test_dataset_kwargs = {
269
- "img_shape": img_shape,
270
- "have_images": True,
271
- "n_bins": args.n_bins,
272
- "color_bkgd_aug": "black",
273
- "rfilter_sigma": args.rfilter_sigma,
274
- }
275
- else:
276
- from loaders.loader_captured_ours import LearnRays, SubjectLoaderTransientRealOurs as SubjectLoader
277
-
278
- params = np.load(args.intrinsics, allow_pickle=True)[()]
279
- shift = _to_numpy(params["shift"])
280
- rays = _to_numpy(params["rays"])
281
- source_img_shape = (int(rays.shape[0]), int(rays.shape[1]))
282
- args.laser_kernel = build_irf_kernel(args, device=device)
283
- measurement_root = getattr(args, "measurement_root", "").strip() or None
284
- invalid_mask_path = getattr(args, "invalid_mask_path", "").strip() or None
285
- data_exts = tuple(
286
- e.strip()
287
- for e in getattr(args, "data_exts", ".npz,.txt,.pt,.h5,.hdf5").split(",")
288
- if e.strip()
289
- )
290
- if getattr(args, "bin_width_s_loader", None) is not None:
291
- bin_width_s_loader = float(args.bin_width_s_loader)
292
- else:
293
- bin_width_s_loader = float(args.exposure_time) / 299792458.0
294
-
295
- test_dataset_kwargs = {
296
- "img_shape": img_shape,
297
- "have_images": True,
298
- "n_bins": args.n_bins,
299
- "color_bkgd_aug": "black",
300
- "rfilter_sigma": args.rfilter_sigma,
301
- "shift": shift,
302
- "measurement_root": measurement_root,
303
- "data_exts": data_exts,
304
- "bin_width_s": bin_width_s_loader,
305
- "source_img_shape": source_img_shape,
306
- "invalid_mask_path": invalid_mask_path,
307
- "invalid_mask_invalid_gt": float(getattr(args, "invalid_mask_invalid_gt", 10.0)),
308
- }
309
-
310
- render_step_size = (((aabb[3:] - aabb[:3]).max() * math.sqrt(3)) / args.render_n_samples).item()
311
-
312
- occupancy_grid = OccGridEstimator(
313
- roi_aabb=aabb,
314
- resolution=args.grid_resolution,
315
- levels=args.grid_nlvl,
316
- ).to(device)
317
-
318
- radiance_field = NGPRadianceField(
319
- use_viewdirs=True,
320
- aabb=aabb,
321
- unbounded=False,
322
- radiance_activation=torch.exp,
323
- args=args,
324
- ).to(device)
325
-
326
- ckpt = torch.load(ckpt_path_rf, map_location=device)
327
- radiance_field.load_state_dict(ckpt)
328
- ckpt = torch.load(ckpt_path_oc, map_location=device)
329
- occupancy_grid.load_state_dict(ckpt)
330
- radiance_field.eval()
331
- occupancy_grid.eval()
332
-
333
- test_dataset = SubjectLoader(
334
- subject_id=f"{args.scene}",
335
- root_fp=args.test_folder_path,
336
- split=args.split,
337
- num_rays=None,
338
- **test_dataset_kwargs,
339
- testing=True,
340
- sample_as_per_distribution=args.sample_as_per_distribution,
341
- )
342
- if args.version == "captured":
343
- test_dataset.K = LearnRays(rays, device=device, img_shape=img_shape).to(device)
344
-
345
- test_dataset.rep = 1
346
- test_dataset.camtoworlds = test_dataset.camtoworlds.to(device)
347
- test_dataset.K = test_dataset.K.to(device)
348
- if args.version == "captured":
349
- eval_dataset_scale = float(_to_numpy(test_dataset.max).reshape(-1)[0])
350
- if eval_dataset_scale <= 0:
351
- eval_dataset_scale = 1.0
352
- else:
353
- eval_dataset_scale = 1.0
354
-
355
- lpips_model = lpips.LPIPS(net="vgg").eval().cpu()
356
-
357
- per_image_metrics = []
358
-
359
- for i in range(len(test_dataset)):
360
- frame_info = positions["frames"][i]
361
- frame_key = frame_info.get("file_path", frame_info.get("filepath", str(i)))
362
- frame_file_path = str(frame_key)
363
- frame_name = os.path.basename(frame_file_path)
364
- try:
365
- ind = int(str(frame_key).split("_")[-1])
366
- except Exception:
367
- ind = i
368
-
369
- print(f"test image {ind} | file={frame_file_path}")
370
-
371
- pred_hist = np.zeros((img_h, img_w, args.n_bins, 3), dtype=np.float32)
372
- pred_depth = np.zeros((img_h, img_w), dtype=np.float32)
373
- pred_depth_viz = np.zeros((img_h, img_w), dtype=np.float32)
374
- weights_sum = np.zeros((img_h, img_w), dtype=np.float32)
375
-
376
- gt_hist = None
377
- valid_mask = None
378
-
379
- for _ in tqdm.tqdm(range(args.rep_number)):
380
- data = test_dataset[i]
381
- pixels = data["pixels"].detach().cpu().numpy().reshape(img_h, img_w, args.n_bins, 3)
382
- if gt_hist is None:
383
- gt_hist = pixels.astype(np.float32)
384
-
385
- if "valid_mask" in data:
386
- valid_mask = data["valid_mask"].detach().cpu().numpy().reshape(img_h, img_w).astype(bool)
387
-
388
- rays = data["rays"]
389
- sample_weights = data["weights"].detach().cpu().numpy().reshape(img_h, img_w)
390
-
391
- out = render_transient(
392
- radiance_field,
393
- occupancy_grid,
394
- rays,
395
- near_plane=args.near_plane,
396
- far_plane=args.far_plane,
397
- render_step_size=render_step_size,
398
- cone_angle=args.cone_angle,
399
- alpha_thre=args.alpha_thre,
400
- use_normals=False,
401
- args=args,
402
- )
403
-
404
- pred_depth += (
405
- out["depths"] * data["weights"][:, None]
406
- ).reshape(img_h, img_w).detach().cpu().numpy()
407
- pred_depth_viz += (
408
- out["depths"] * data["weights"][:, None] * (out["opacities"] > 0)
409
- ).reshape(img_h, img_w).detach().cpu().numpy()
410
- pred_hist += (
411
- out["colors"] * data["weights"][:, None]
412
- ).reshape(img_h, img_w, args.n_bins, 3).detach().cpu().numpy()
413
-
414
- weights_sum += sample_weights
415
- del out
416
-
417
- weights_sum = np.clip(weights_sum, 1e-8, None)
418
- pred_hist /= weights_sum[..., None, None]
419
- pred_depth /= weights_sum
420
- pred_depth_viz /= weights_sum
421
-
422
- if valid_mask is None:
423
- valid_mask = np.ones((img_h, img_w), dtype=bool)
424
-
425
- gt_hist_1 = gt_hist[..., 0].astype(np.float32)
426
- pred_hist_1 = pred_hist[..., 0].astype(np.float32)
427
-
428
- gt_intensity = _extract_intensity_from_hist(gt_hist)
429
- pred_intensity = _extract_intensity_from_hist(pred_hist)
430
-
431
- if args.version == "simulated":
432
- gt_depth = get_gt_depth(frame_info, test_dataset.camtoworlds[i].cpu().numpy(), args.test_folder_path)
433
- else:
434
- gt_depth = np.argmax(gt_hist_1, axis=-1).astype(np.float32) * float(args.exposure_time) / 2.0
435
- # Keep captured depth definition consistent with histogram peak depth.
436
- pred_depth = np.argmax(pred_hist_1, axis=-1).astype(np.float32) * float(args.exposure_time) / 2.0
437
-
438
- signal_mask = gt_intensity > 0
439
- if args.version == "captured" and float(getattr(args, "meas_peak_min", 100.0)) > 0:
440
- peak_thre_norm = float(args.meas_peak_min) / float(eval_dataset_scale)
441
- meas_peak_mask = np.max(gt_hist_1, axis=-1) >= peak_thre_norm
442
- else:
443
- meas_peak_mask = np.ones_like(signal_mask, dtype=bool)
444
- metric_mask = valid_mask & signal_mask & meas_peak_mask
445
- print(
446
- f"mask ratio: valid={valid_mask.mean():.4f}, "
447
- f"peak={meas_peak_mask.mean():.4f}, metric={metric_mask.mean():.4f}"
448
- )
449
-
450
- depth_mask = metric_mask & np.isfinite(gt_depth) & np.isfinite(pred_depth)
451
- if np.any(depth_mask):
452
- depth_l1 = float(np.mean(np.abs(gt_depth[depth_mask] - pred_depth[depth_mask])))
453
- else:
454
- depth_l1 = float("nan")
455
-
456
- gt_intensity_01 = np.clip(gt_intensity / scale_int, 0.0, 1.0)
457
- pred_intensity_01 = np.clip(pred_intensity / scale_int, 0.0, 1.0)
458
- gt_hist_01 = np.clip(gt_hist_1 / scale_int, 0.0, 1.0)
459
- pred_hist_01 = np.clip(pred_hist_1 / scale_int, 0.0, 1.0)
460
-
461
- gt_intensity_gamma = _to_gamma_domain(gt_intensity_01)
462
- pred_intensity_gamma = _to_gamma_domain(pred_intensity_01)
463
-
464
- gt_intensity_eval = gt_intensity_gamma.copy()
465
- pred_intensity_eval = pred_intensity_gamma.copy()
466
- gt_intensity_eval[~metric_mask] = 0.0
467
- pred_intensity_eval[~metric_mask] = 0.0
468
-
469
- intensity_ssim = float(
470
- structural_similarity(gt_intensity_eval, pred_intensity_eval, data_range=1.0)
471
- )
472
-
473
- gt_lpips = _to_lpips_input(gt_intensity_eval)
474
- pred_lpips = _to_lpips_input(pred_intensity_eval)
475
- intensity_lpips = float(lpips_model(gt_lpips, pred_lpips).detach().cpu().item())
476
-
477
- waveform_psnr = _safe_psnr(gt_hist_01, pred_hist_01, mask=metric_mask)
478
-
479
- prefix = os.path.join(outpath, f"{args.scene}_{args.num_views}_{args.step}_test{ind}")
480
-
481
- np.save(prefix + "_hist_gt.npy", gt_hist_1.astype(np.float32))
482
- np.save(prefix + "_hist_pred.npy", pred_hist_1.astype(np.float32))
483
- np.save(prefix + "_depth_gt.npy", gt_depth.astype(np.float32))
484
- np.save(prefix + "_depth_pred.npy", pred_depth.astype(np.float32))
485
- np.save(prefix + "_intensity_gt.npy", gt_intensity.astype(np.float32))
486
- np.save(prefix + "_intensity_pred.npy", pred_intensity.astype(np.float32))
487
- np.save(prefix + "_valid_mask.npy", metric_mask.astype(np.uint8))
488
- np.save(prefix + "_meas_peak_mask.npy", meas_peak_mask.astype(np.uint8))
489
- torch.save(torch.from_numpy(pred_hist_1.astype(np.float32)), prefix + "_conv_pred.pt")
490
-
491
- gt_intensity_vis = _normalize_for_vis(gt_intensity, metric_mask) ** (1.0 / 2.2)
492
- pred_intensity_vis = _normalize_for_vis(pred_intensity, metric_mask) ** (1.0 / 2.2)
493
- imageio.imwrite(prefix + "_intensity_gt.png", (gt_intensity_vis * 255.0).astype(np.uint8))
494
- imageio.imwrite(prefix + "_intensity_pred.png", (pred_intensity_vis * 255.0).astype(np.uint8))
495
-
496
- depth_for_viz = gt_depth[depth_mask] if np.any(depth_mask) else gt_depth[np.isfinite(gt_depth)]
497
- if depth_for_viz.size > 0:
498
- vmin = float(np.percentile(depth_for_viz, 1.0))
499
- vmax = float(np.percentile(depth_for_viz, 99.0))
500
- if vmax <= vmin:
501
- vmax = vmin + 1e-6
502
- else:
503
- vmin, vmax = 0.0, 1.0
504
-
505
- plt.imsave(prefix + "_depth_gt.png", gt_depth, cmap="inferno", vmin=vmin, vmax=vmax)
506
- plt.imsave(prefix + "_depth_pred.png", pred_depth, cmap="inferno", vmin=vmin, vmax=vmax)
507
- plt.imsave(prefix + "_depth_pred_viz.png", pred_depth_viz, cmap="inferno", vmin=vmin, vmax=vmax)
508
-
509
- metrics_row = {
510
- "index": i,
511
- "frame_id": ind,
512
- "frame_file_path": frame_file_path,
513
- "frame_name": frame_name,
514
- "intensity_ssim": intensity_ssim,
515
- "intensity_lpips": intensity_lpips,
516
- "depth_l1": depth_l1,
517
- "waveform_psnr": waveform_psnr,
518
- }
519
- per_image_metrics.append(metrics_row)
520
-
521
- print(
522
- f"SSIM={intensity_ssim:.6f} LPIPS={intensity_lpips:.6f} "
523
- f"DepthL1={depth_l1:.6f} WavePSNR={waveform_psnr:.4f}"
524
- )
525
- print("-----")
526
-
527
- def _nanmean(key):
528
- values = np.array([row[key] for row in per_image_metrics], dtype=np.float64)
529
- return float(np.nanmean(values))
530
-
531
- summary = {
532
- "scene": args.scene,
533
- "num_views": int(args.num_views),
534
- "step": int(args.step),
535
- "num_images": len(per_image_metrics),
536
- "avg_intensity_ssim": _nanmean("intensity_ssim"),
537
- "avg_intensity_lpips": _nanmean("intensity_lpips"),
538
- "avg_depth_l1": _nanmean("depth_l1"),
539
- "avg_waveform_psnr": _nanmean("waveform_psnr"),
540
- }
541
-
542
- print(json.dumps(summary, indent=2))
543
-
544
- csv_path = os.path.join(outpath, f"{args.scene}_{args.num_views}_{args.step}_metrics_per_image.csv")
545
- json_rows_path = os.path.join(outpath, f"{args.scene}_{args.num_views}_{args.step}_metrics_per_image.json")
546
- json_summary_path = os.path.join(outpath, f"{args.scene}_{args.num_views}_{args.step}_metrics_summary.json")
547
-
548
- _save_metrics_csv(csv_path, per_image_metrics)
549
- with open(json_rows_path, "w", encoding="utf-8") as f:
550
- json.dump(per_image_metrics, f, indent=2)
551
- with open(json_summary_path, "w", encoding="utf-8") as f:
552
- json.dump(summary, f, indent=2)
553
-
554
-
555
- if __name__ == "__main__":
556
- eval()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/loaders/README.md DELETED
@@ -1,57 +0,0 @@
1
- 1. The captured scenes include: carving, boots, baskets, cinema, chef.
2
- The simulated scenes include lego, chair, ficus, hotdog, bench.
3
- These have different structures and loaders.
4
-
5
- In the root of the dataset folder you can also find the `intrinsics.npy` which is the set of captured rays and parameters used in training and `pulse_low_flux.mat` which is the calibrated laser pulse.
6
-
7
-
8
- 2. Training transform files.
9
-
10
- For the *captured* scenes the training transforms are all named `transforms_train.json` and can be found under `<scene_name>/final_cams/<num_views>/transforms_train.json`.
11
-
12
- For the *simulated* scenes the training transforms are all named `transforms_train_v{i}.json` where `i` is the number of views (2, 3, 5). and can be found under `<scene_name>/transforms_train_v{i}.json`.
13
-
14
-
15
- 3. Test transform files.
16
-
17
- For the *captured* scenes the test transforms can be found under `<scene_name>/final_cams/test_jsons/transforms_test.json`.
18
-
19
- For the *simulated* scenes the test transforms can be found under `<scene_name>/transforms_test_final.json`.
20
-
21
-
22
- 4. Downloading.
23
-
24
- - You can download the data yourself either through the Dropbox download button, or by right-clicking a folder and selecting copy link address, then
25
- ```
26
- wget "copied link"
27
- ```
28
- will start a download of the folder.
29
-
30
- 5. (!!!) Using the dataset.
31
-
32
- To use the dataset alongside its transforms please look at the loader in `loaders/loader_captured.py` in the [GitHub repository](https://github.com/anaghmalik/TransientNeRF). Most importantly to use the temporal *captured* data, you will have to resample the transient using the shift given in the `intrinsics.npy` file:
33
-
34
- ```
35
- img_shape = (512, 512)
36
- exposure_time= 299792458*4e-12
37
- n_bins = 1500
38
-
39
- x = (torch.arange(img_shape[0], device="cpu")-img_shape[0]//2+0.5)/(img_shape[0]//2-0.5)
40
- y = (torch.arange(img_shape[0], device="cpu")-img_shape[0]//2+0.5)/(img_shape[0]//2-0.5)
41
- z = torch.arange(n_bins*2, device="cpu").float()
42
- X, Y, Z = torch.meshgrid(x, y, z, indexing="xy")
43
- Z = Z*exposure_time/2
44
- Z = Z - shift[0]
45
- Z = Z*2/exposure_time
46
- Z = (Z-n_bins*2//2+0.5)/(n_bins*2//2-0.5)
47
- grid = torch.stack((Z, X, Y), dim=-1)[None, ...]
48
- del X
49
- del Y
50
- del Z
51
-
52
- rgb = torch.Tensor(rgb)[..., :3000].float().cpu()
53
- rgb = torch.nn.functional.grid_sample(rgb[None, None, ...], grid, align_corners=True).squeeze().cpu()
54
-
55
- ```
56
-
57
- where `shift` is the value from the `intrinsics.npy` file and `rgb` is the original loaded transient.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/loaders/__init__.py DELETED
File without changes
codes/reconstruction/transientnerf/loaders/loader_captured.py DELETED
@@ -1,532 +0,0 @@
1
- import collections
2
- import json
3
- import os
4
- import matplotlib.pyplot as plt
5
- import numpy as np
6
- import torch
7
- import scipy
8
- from mat73 import loadmat
9
- from .utils import Rays
10
- from tqdm import tqdm
11
- import sys
12
- sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
13
- from misc.dataset_utils import read_h5
14
-
15
-
16
- def _load_renderings(root_fp: str, subject_id: str, split: str, have_images=True, img_shape=(256, 256)):
17
- """Load images from disk."""
18
- if not root_fp.startswith("/"):
19
- # allow relative path. e.g., "./data/nerf_synthetic/"
20
- root_fp = os.path.join(
21
- os.path.dirname(os.path.abspath(__file__)),
22
- "..",
23
- "..",
24
- root_fp,
25
- )
26
-
27
- data_dir = root_fp
28
- with open(
29
- os.path.join(data_dir, "transforms_{}.json".format(split)), "r"
30
- ) as fp:
31
- meta = json.load(fp)
32
- images = []
33
- camtoworlds = []
34
-
35
- if have_images:
36
- for i in range(len(meta["frames"])):
37
- frame = meta["frames"][i]
38
- number = int(frame["file_path"].split("_")[-1])
39
- fname = os.path.join(data_dir, f"{number:03d}" + ".png")
40
-
41
- # fname = os.path.join(data_dir, frame["file_path"] + ".png")
42
- rgba = imageio.imread(fname)
43
- camtoworlds.append(frame["transform_matrix"])
44
- images.append(rgba)
45
-
46
- images = np.stack(images, axis=0)
47
- camtoworlds = np.stack(camtoworlds, axis=0)
48
-
49
- h, w = images.shape[1:3]
50
- else:
51
- for i in range(len(meta["frames"])):
52
- frame = meta["frames"][i]
53
- camtoworlds.append(frame["transform_matrix"])
54
-
55
- camtoworlds = np.stack(camtoworlds, axis=0)
56
-
57
- h, w = img_shape
58
-
59
- camera_angle_x = float(meta["camera_angle_x"])
60
- focal = 0.5 * w / np.tan(0.5 * camera_angle_x)
61
-
62
- return images, camtoworlds, focal
63
-
64
-
65
- def _parse_shift_for_grid(shift, img_shape):
66
- h, w = int(img_shape[0]), int(img_shape[1])
67
- arr = np.asarray(shift, dtype=np.float32)
68
- if arr.ndim == 0:
69
- return float(arr.item()), None
70
-
71
- arr = arr.squeeze()
72
- if arr.ndim == 0 or arr.size == 1:
73
- return float(arr.reshape(-1)[0]), None
74
-
75
- if arr.ndim == 1 and arr.size == h * w:
76
- return 0.0, torch.from_numpy(arr.reshape(h, w))
77
- if arr.ndim == 2 and arr.shape == (h, w):
78
- return 0.0, torch.from_numpy(arr)
79
-
80
- # Fallback to legacy behavior: use first value only.
81
- return float(arr.reshape(-1)[0]), None
82
-
83
-
84
-
85
- def _load_renderings_transient_real(root_fp: str, subject_id: str, split: str, have_images=True, img_shape=(256, 256), n_bins=4096, shift=0, bin_width_s=4e-12):
86
- """Load images from disk."""
87
-
88
- data_dir = root_fp
89
- with open(
90
- os.path.join(data_dir, "transforms_{}.json".format(split)), "r"
91
- ) as fp:
92
- meta = json.load(fp)
93
-
94
- images = []
95
- camtoworlds = []
96
-
97
- exposure_time = 299792458 * float(bin_width_s)
98
- shift_scalar, shift_map = _parse_shift_for_grid(shift, img_shape)
99
-
100
- x = (torch.arange(img_shape[0], device="cpu")-img_shape[0]//2+0.5)/(img_shape[0]//2-0.5)
101
- y = (torch.arange(img_shape[0], device="cpu")-img_shape[0]//2+0.5)/(img_shape[0]//2-0.5)
102
- z = torch.arange(n_bins*2, device="cpu").float()
103
- X, Y, Z = torch.meshgrid(x, y, z, indexing="xy")
104
- Z = Z*exposure_time/2
105
- if shift_map is not None:
106
- Z = Z - shift_map[..., None]
107
- else:
108
- Z = Z - float(shift_scalar)
109
- Z = Z*2/exposure_time
110
- Z = (Z-n_bins*2//2+0.5)/(n_bins*2//2-0.5)
111
- grid = torch.stack((Z, X, Y), dim=-1)[None, ...]
112
- del X
113
- del Y
114
- del Z
115
-
116
-
117
- if have_images:
118
- tqdm.write('Loading data')
119
- for i in tqdm(range(len(meta["frames"]))):
120
- frame = meta["frames"][i]
121
- number = int(frame["file_path"].split("_")[-1])
122
-
123
- fname = os.path.join(os.path.join(data_dir, "../.."), f"transient{number:03d}.pt")
124
- rgba = torch.load(fname).to_dense()
125
- rgba = torch.Tensor(rgba)[..., :3000].float().cpu()
126
- # if img_shape[0]==256:
127
- # rgba = (rgba[::2, ::2] + rgba[::2, 1::2] + rgba[1::2, ::2]+ rgba[1::2, 1::2] )/4
128
-
129
- rgba = torch.nn.functional.grid_sample(rgba[None, None, ...], grid, align_corners=True).squeeze().cpu()
130
- rgba = (rgba[..., 1::2]+ rgba[..., ::2] )/2
131
-
132
- camtoworlds.append(frame["transform_matrix"])
133
- rgba = torch.clip(rgba, 0, None)
134
- rgba = rgba[..., None].repeat(1, 1, 1, 3)
135
- images.append(rgba)
136
-
137
-
138
-
139
- images = torch.stack(images, axis=0)
140
- max = torch.max(images)
141
- images /= torch.max(images)
142
-
143
- if split == "test":
144
- quotient = images.shape[1]//img_shape[0]
145
- times_downsample = int(np.log2(quotient))
146
-
147
- for i in range(times_downsample):
148
- images = (images[:, 1::2, ::2] + images[:, ::2, ::2] + images[:, 1::2, 1::2] + images[:, ::2, 1::2])/4
149
-
150
- camtoworlds = np.stack(camtoworlds, axis=0)
151
-
152
- h, w = images.shape[1:3]
153
- else:
154
- for i in range(len(meta["frames"])):
155
- frame = meta["frames"][i]
156
- camtoworlds.append(frame["transform_matrix"])
157
-
158
- camtoworlds = np.stack(camtoworlds, axis=0)
159
- max = 1
160
- h, w = img_shape
161
-
162
-
163
- return images, camtoworlds, max
164
-
165
-
166
- class SubjectLoaderTransientReal(torch.utils.data.Dataset):
167
- """Single subject data loader for training and evaluation."""
168
-
169
- SPLITS = ["train", "val", "trainval", "test"]
170
- SUBJECT_IDS = [
171
- "chair",
172
- "drums",
173
- "ficus",
174
- "hotdog",
175
- "lego",
176
- "materials",
177
- "mic",
178
- "ship",
179
- ]
180
-
181
- # WIDTH, HEIGHT = 64, 64
182
- NEAR, FAR = 0, 6
183
- OPENGL_CAMERA = True
184
-
185
- def __init__(
186
- self,
187
- subject_id: str,
188
- root_fp: str,
189
- split: str,
190
- color_bkgd_aug: str = "black",
191
- num_rays: int = None,
192
- near: float = None,
193
- far: float = None,
194
- batch_over_images: bool = True,
195
- have_images=True,
196
- img_shape=(256, 256),
197
- n_bins=10000,
198
- rfilter_sigma=0.15,
199
- sample_as_per_distribution = True,
200
- shift = 0.3,
201
- testing =False
202
- ):
203
- super().__init__()
204
- #assert split in self.SPLITS, "%s" % split
205
- # assert subject_id in self.SUBJECT_IDS, "%s" % subject_id
206
- assert color_bkgd_aug in ["white", "black", "random"]
207
- self.sample_as_per_distribution = sample_as_per_distribution
208
- self.rfilter_sigma = rfilter_sigma
209
- self.HEIGHT, self.WIDTH = img_shape
210
- self.split = split
211
- self.testing = testing
212
- self.num_rays = num_rays
213
- self.near = self.NEAR if near is None else near
214
- self.far = self.FAR if far is None else far
215
- self.training = (num_rays is not None) and (
216
- split in ["train", "trainval"]
217
- )
218
- self.shift = shift
219
- self.testing = testing
220
- self.rep = 1
221
- self.color_bkgd_aug = color_bkgd_aug
222
- self.batch_over_images = batch_over_images
223
- self.have_images = have_images
224
- self.n_bins = n_bins
225
- shift = shift
226
-
227
- if split == "trainval":
228
- _images_train, _camtoworlds_train, _focal_train = _load_renderings_transient_real(
229
- root_fp, subject_id, "train", n_bins=self.n_bins, shift=shift
230
- )
231
- _images_val, _camtoworlds_val, _focal_val = _load_renderings_transient_real(
232
- root_fp, subject_id, "val", n_bins=self.n_bins, shift=shift
233
- )
234
- self.images = np.concatenate([_images_train, _images_val])
235
- self.camtoworlds = np.concatenate(
236
- [_camtoworlds_train, _camtoworlds_val]
237
- )
238
- self.focal = _focal_train
239
- self.images = torch.from_numpy(self.images).to(torch.float32)
240
-
241
- # ste for transient
242
- self.images = torch.reshape(self.images, (-1, self.HEIGHT, self.WIDTH, self.n_bins*3))
243
-
244
-
245
- elif have_images:
246
- self.images, self.camtoworlds, self.focal = _load_renderings_transient_real(
247
- root_fp, subject_id, split, n_bins=self.n_bins, shift=shift, img_shape=img_shape
248
- )
249
- self.images =self.images.to(torch.float32)
250
- assert self.images.shape[1:3] == (self.HEIGHT, self.WIDTH)
251
- else:
252
- _, self.camtoworlds, self.focal = _load_renderings(
253
- root_fp, subject_id, split, have_images=have_images, img_shape=img_shape
254
- )
255
-
256
- self.max = self.focal
257
-
258
- self.camtoworlds = torch.from_numpy(self.camtoworlds).to(torch.float32)
259
- self.camtoworlds[:, :3, 3] = self.camtoworlds[:, :3, 3]
260
- # self.K = LearnRays(params["rays"], img_shape=(self.WIDTH, self.HEIGHT))
261
-
262
-
263
-
264
- def __len__(self):
265
- return len(self.camtoworlds)
266
-
267
- # @torch.no_grad()
268
- def __getitem__(self, index):
269
- data = self.fetch_data(index)
270
- data = self.preprocess(data)
271
- return data
272
-
273
- def preprocess(self, data):
274
- """Process the fetched / cached data with randomness."""
275
- rgba, rays = data["rgba"], data["rays"]
276
- # pixels, alpha = torch.split(rgba, [3, 1], dim=-1)
277
-
278
- if rgba is not None:
279
- pixels = rgba.to(self.camtoworlds.device)
280
- else:
281
- pixels = rgba
282
-
283
-
284
- if self.color_bkgd_aug == "random":
285
- color_bkgd = torch.rand(3, device=self.camtoworlds.device)
286
- elif self.color_bkgd_aug == "white":
287
- color_bkgd = torch.ones(3, device=self.camtoworlds.device)
288
- elif self.color_bkgd_aug == "black":
289
- color_bkgd = torch.zeros(3, device=self.camtoworlds.device)
290
-
291
- # pixels = pixels * alpha + color_bkgd * (1.0 - alpha)
292
- return {
293
- "pixels": pixels, # [n_rays, 3] or [h, w, 3]
294
- "rays": rays, # [n_rays,] or [h, w]
295
- "color_bkgd": color_bkgd, # [3,]
296
- **{k: v for k, v in data.items() if k not in ["rgba", "rays"]},
297
- }
298
-
299
-
300
- def update_num_rays(self, num_rays):
301
- self.num_rays = num_rays
302
-
303
- def fetch_data(self, index, rep=None, num_rays=None):
304
- """Fetch the data (it maybe cached for multiple batches)."""
305
- if num_rays==None:
306
- num_rays = self.num_rays
307
- if rep==None:
308
- rep = self.rep
309
-
310
-
311
-
312
- if self.training:
313
- if self.batch_over_images:
314
- image_id = torch.randint(
315
- 0,
316
- len(self.images),
317
- size=(num_rays,),
318
- device=self.images.device,
319
- )
320
- else:
321
- image_id = [index]
322
- x = torch.randint(
323
- 0, self.WIDTH, size=(num_rays,), device="cpu"
324
- )
325
- y = torch.randint(
326
- 0, self.HEIGHT, size=(num_rays,), device="cpu"
327
- )
328
- x = x.repeat(rep)
329
- y = y.repeat(rep)
330
- image_id = image_id.repeat(rep)
331
-
332
-
333
- rgba = self.images[image_id, y, x] # (num_rays, 4)
334
-
335
- elif self.testing:
336
- image_id = [index]
337
- x, y = torch.meshgrid(
338
- torch.arange(self.WIDTH, device="cpu"),
339
- torch.arange(self.HEIGHT, device="cpu"),
340
- indexing="xy",
341
- )
342
- x = x.flatten()
343
- y = y.flatten()
344
- x = x.repeat(rep)
345
- y = y.repeat(rep)
346
- # image_id = image_id.repeat(rep)
347
- if self.have_images:
348
- rgba = self.images[image_id, y, x] # (num_rays, 4)
349
- else:
350
- rgba = None
351
- elif self.have_images:
352
- image_id = [index]
353
- x, y = torch.meshgrid(
354
- torch.arange(self.WIDTH, device=self.camtoworlds.device),
355
- torch.arange(self.HEIGHT, device=self.camtoworlds.device),
356
- indexing="xy",
357
- )
358
- x = x.flatten()
359
- y = y.flatten()
360
- rgba = self.images[image_id, y, x] # (num_rays, 4)
361
- else:
362
- image_id = [index]
363
- x, y = torch.meshgrid(
364
- torch.arange(self.WIDTH, device=self.camtoworlds.device),
365
- torch.arange(self.HEIGHT, device=self.camtoworlds.device),
366
- indexing="xy",
367
- )
368
- x = x.flatten()
369
- y = y.flatten()
370
-
371
- # generate rays
372
-
373
- scale = self.rfilter_sigma
374
- c2w = self.camtoworlds[image_id]
375
-
376
- bounds_max = [4*scale]*x.shape[0]
377
- loc = 0
378
- if self.training:
379
- s_x, s_y, weights = spatial_filter(x, y, sigma=scale, rep = self.rep, prob_dithering=self.sample_as_per_distribution)
380
- s_x = (torch.clip(x + torch.from_numpy(s_x), 0, self.WIDTH-1).to(self.camtoworlds.device)).to(torch.float32)
381
- s_y = (torch.clip(y + torch.from_numpy(s_y), 0, self.HEIGHT-1).to(self.camtoworlds.device)).to(torch.float32)
382
- weights = torch.Tensor(weights).to(self.camtoworlds.device)
383
-
384
- elif self.testing:
385
- s_x, s_y, weights = spatial_filter(x, y, sigma=scale, rep = self.rep, prob_dithering=self.sample_as_per_distribution)
386
- s_x = (torch.clip(x + torch.from_numpy(s_x), 0, self.WIDTH-1).to(self.camtoworlds.device)).to(torch.float32)
387
- s_y = (torch.clip(y + torch.from_numpy(s_y), 0, self.HEIGHT-1).to(self.camtoworlds.device)).to(torch.float32)
388
- weights = torch.Tensor(weights).to(self.camtoworlds.device)
389
- else:
390
- s_x = x
391
- s_y = y
392
-
393
-
394
-
395
- camera_dirs = self.K(s_x, s_y)
396
-
397
- directions = (camera_dirs[:, None, :] * c2w[:, :3, :3]).sum(dim=-1)
398
- origins = torch.broadcast_to(c2w[:, :3, -1], directions.shape)
399
- viewdirs = directions / torch.linalg.norm(
400
- directions, dim=-1, keepdims=True
401
- )
402
-
403
- if self.training:
404
- origins = torch.reshape(origins, (-1, 3))
405
- viewdirs = torch.reshape(viewdirs, (-1, 3))
406
- # here
407
- rgba = torch.reshape(rgba, (-1,self.n_bins*3))
408
- elif self.testing:
409
- origins = torch.reshape(origins, (-1, 3))
410
- viewdirs = torch.reshape(viewdirs, (-1, 3))
411
- # here
412
- if self.have_images:
413
- rgba = torch.reshape(rgba, (-1,self.n_bins*3))
414
-
415
- elif self.have_images:
416
- origins = torch.reshape(origins, (self.HEIGHT, self.WIDTH, 3))
417
- viewdirs = torch.reshape(viewdirs, (self.HEIGHT, self.WIDTH, 3))
418
- rgba = torch.reshape(rgba, (self.HEIGHT, self.WIDTH, self.n_bins * 3))
419
- else:
420
- origins = torch.reshape(origins, (self.HEIGHT, self.WIDTH, 3))
421
- viewdirs = torch.reshape(viewdirs, (self.HEIGHT, self.WIDTH, 3))
422
- rgba = None
423
-
424
- rays = Rays(origins=origins, viewdirs=viewdirs)
425
- if self.training or self.testing:
426
- return {
427
- "rgba": rgba, # [h, w, 4] or [num_rays, 4]
428
- "rays": rays, # [h, w, 3] or [num_rays, 3]
429
- "weights":weights
430
- }
431
-
432
- return {
433
- "rgba": rgba, # [h, w, 4] or [num_rays, 4]
434
- "rays": rays, # [h, w, 3] or [num_rays, 3]
435
- }
436
-
437
-
438
-
439
-
440
-
441
- class LearnRays(torch.nn.Module):
442
- def __init__(self, rays, device ="cuda:0", img_shape = (256, 256)):
443
- """
444
- :param num_cams:
445
- :param learn_R: True/False
446
- :param learn_t: True/False
447
- :param init_c2w: (N, 4, 4) torch tensor
448
- """
449
- super(LearnRays, self).__init__()
450
- self.device = device
451
- self.init_c2w = None
452
- self.img_shape = img_shape
453
-
454
- x = np.arange(32, 480)
455
- X, Y = np.meshgrid(x, x)
456
-
457
- tar_x = np.arange(0, 512)
458
- tar_X, tar_Y = np.meshgrid(tar_x, tar_x)
459
- # rays = rays.detach().cpu().numpy()
460
-
461
- ray_x = scipy.interpolate.interpn((x, x), rays[32:-32, 32:-32, 0].transpose(1, 0), np.stack([tar_X, tar_Y], axis=-1).squeeze().flatten(), bounds_error = False, fill_value=None).reshape(512, 512)
462
- ray_y = scipy.interpolate.interpn((x, x), rays[32:-32, 32:-32, 1].transpose(1, 0), np.stack([tar_X, tar_Y], axis=-1).squeeze().flatten(), bounds_error = False, fill_value=None).reshape(512, 512)
463
- ray_z = scipy.interpolate.interpn((x, x), rays[32:-32, 32:-32, 2].transpose(1, 0), np.stack([tar_X, tar_Y], axis=-1).squeeze().flatten(), bounds_error = False, fill_value=None).reshape(512, 512)
464
-
465
- rays = torch.from_numpy(np.stack([ray_x, ray_y, ray_z], axis=-1)).to(self.device)
466
-
467
- quotient = rays.shape[1]//img_shape[0]
468
- times_downsample = int(np.log2(quotient))
469
-
470
- for i in range(times_downsample):
471
- rays = (rays[1::2, ::2] + rays[::2, ::2] + rays[1::2, 1::2] + rays[::2, 1::2])/4
472
-
473
- rays = rays/torch.linalg.norm(rays, dim=-1, keepdims=True)
474
- self.rays = rays
475
- # self.rays = torch.nn.Parameter(rays, requires_grad=learn_rays)
476
-
477
- def forward(self, x0, y0):
478
- """input coord = (n, 2)
479
- rays = (512, 512, 3)
480
- """
481
- rays = self.rays
482
- x1, y1 = torch.floor(x0.float()), torch.floor(y0.float())
483
- x2, y2 = x1+1, y1+1
484
- """
485
- Perform bilinear interpolation to estimate the value of the function f(x, y)
486
- at the continuous point (x0, y0), given that f is known at integer values of x, y.
487
- """
488
- # if (y1>self.img_shape[0]-1).any() or (x1>self.img_shape[0]-1).any():
489
- # print("hello")
490
- x1, y1 = torch.clip(x1, 0, self.img_shape[0]-1), torch.clip(y1, 0, self.img_shape[0]-1)
491
-
492
- # x2, y2 = torch.clip(x2, 0, self.img_shape[0]-1), torch.clip(y2, 0, self.img_shape[0]-1)
493
-
494
- # Compute the weights for the interpolation
495
- wx1 = ((x2 - x0) / (x2 - x1 + 1e-8))[:, None]
496
- wx2 = ((x0 - x1) / (x2 - x1 + 1e-8))[:, None]
497
- wy1 = ((y2 - y0) / (y2 - y1 + 1e-8))[:, None]
498
- wy2 = ((y0 - y1) / (y2 - y1 + 1e-8))[:, None]
499
-
500
- x1, y1, x2, y2 = x1.long(), y1.long(), x2.long(), y2.long()
501
- x2, y2 = torch.clip(x2, 0, self.img_shape[0] - 1), torch.clip(y2, 0, self.img_shape[0] - 1)
502
-
503
- # Compute the interpolated value of f(x, y) at (x0, y0)
504
- f_interp = wx1 * wy1 * rays[y1, x1] + \
505
- wx1 * wy2 * rays[y2, x1] + \
506
- wx2 * wy1 * rays[y1, x2] + \
507
- wx2 * wy2 * rays[y2, x2]
508
-
509
- f_interp = f_interp/torch.linalg.norm(f_interp, dim=-1, keepdims=True)
510
- return f_interp.float()
511
-
512
-
513
- def spatial_filter(x, y, sigma, rep, prob_dithering=True):
514
- pdf_fn = lambda x: np.exp(-x/(2*sigma**2)) - np.exp(-16)
515
- if prob_dithering:
516
- bounds_max = [4*sigma]*x.shape[0]
517
- loc = 0
518
- s_x = scipy.stats.truncnorm.rvs((-np.array(bounds_max)-loc)/sigma, (np.array(bounds_max)-loc)/sigma, loc=loc, scale=sigma)
519
- s_y = scipy.stats.truncnorm.rvs((-np.array(bounds_max)-loc)/sigma, (np.array(bounds_max)-loc)/sigma, loc=loc, scale=sigma)
520
- weights = np.ones_like(s_x)*1/rep
521
-
522
- else:
523
- s_x = np.random.uniform(low=-4*sigma, high=4*sigma, size=(rep, x.shape[0]//rep))
524
- s_y = np.random.uniform(low=-4*sigma, high=4*sigma, size=(rep, x.shape[0]//rep))
525
- dists = (s_x**2 + s_y**2)
526
- weights = pdf_fn(dists)
527
- weights = weights/weights.sum(0)[None, :]
528
- s_x = s_x.flatten()
529
- s_y = s_y.flatten()
530
- weights = weights.flatten()
531
-
532
- return s_x, s_y, weights
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/loaders/loader_captured_ours.py DELETED
@@ -1,680 +0,0 @@
1
- import json
2
- import os
3
- from typing import Sequence, Tuple
4
-
5
- # import h5py
6
- import numpy as np
7
- import scipy
8
- import torch
9
- import torch.nn.functional as F
10
- from tqdm import tqdm
11
-
12
- from .utils import Rays
13
-
14
-
15
- C = 299792458.0
16
-
17
-
18
- def _normalize_index(idx: torch.Tensor, size: int) -> torch.Tensor:
19
- if size <= 1:
20
- return torch.zeros_like(idx)
21
- return 2.0 * idx / float(size - 1) - 1.0
22
-
23
-
24
- def _load_numpy_coo_npz(npz_path: str) -> np.ndarray:
25
- pack = np.load(npz_path, allow_pickle=False)
26
- try:
27
- if "format" not in pack:
28
- raise ValueError("missing 'format' key in npz")
29
- fmt = str(np.asarray(pack["format"]).item())
30
- if fmt != "coo_numpy":
31
- raise ValueError(f"unsupported npz format tag: {fmt}")
32
-
33
- shape = tuple(np.asarray(pack["shape"], dtype=np.int64).tolist())
34
- row = np.asarray(pack["row"], dtype=np.int64)
35
- col = np.asarray(pack["col"], dtype=np.int64)
36
- data = np.asarray(pack["data"])
37
-
38
- dense = np.zeros(shape, dtype=data.dtype)
39
- np.add.at(dense, (row, col), data)
40
- return dense
41
- finally:
42
- pack.close()
43
-
44
-
45
- def _load_histogram_2d(path: str, dtype=np.float32) -> np.ndarray:
46
- ext = os.path.splitext(path)[1].lower()
47
- if ext == ".txt":
48
- arr = np.loadtxt(path, dtype=dtype)
49
- elif ext == ".npz":
50
- try:
51
- from scipy import sparse # type: ignore
52
-
53
- arr = sparse.load_npz(path).toarray()
54
- except Exception:
55
- arr = _load_numpy_coo_npz(path)
56
- if dtype is not None:
57
- arr = np.asarray(arr, dtype=dtype)
58
- else:
59
- raise ValueError(f"unsupported histogram extension for 2D loader: {ext}")
60
-
61
- arr = np.asarray(arr, dtype=dtype)
62
- if arr.ndim == 1:
63
- arr = arr.reshape(1, -1)
64
- return arr
65
-
66
-
67
- def _reshape_histogram_to_hwt(arr: np.ndarray, hw: Tuple[int, int]) -> torch.Tensor:
68
- h, w = int(hw[0]), int(hw[1])
69
- if arr.ndim == 3:
70
- if arr.shape[0] == h and arr.shape[1] == w:
71
- out = arr
72
- elif arr.shape[0] == w and arr.shape[1] == h:
73
- out = arr.transpose(1, 0, 2)
74
- else:
75
- raise ValueError(f"3D histogram shape {arr.shape} incompatible with target ({h}, {w}, T)")
76
- return torch.from_numpy(np.asarray(out, dtype=np.float32))
77
-
78
- if arr.ndim != 2:
79
- raise ValueError(f"expected 2D/3D histogram array, got shape={arr.shape}")
80
-
81
- if arr.shape[0] == h * w:
82
- out = arr.reshape(h, w, arr.shape[1])
83
- elif arr.shape[1] == h * w:
84
- out = arr.T.reshape(h, w, arr.shape[0])
85
- else:
86
- raise ValueError(
87
- f"2D histogram shape {arr.shape} does not match H*W={h*w}; "
88
- "expected [H*W, bins] or [bins, H*W]."
89
- )
90
- return torch.from_numpy(np.asarray(out, dtype=np.float32))
91
-
92
-
93
- def _load_valid_mask_from_offset(
94
- offset_path: str,
95
- source_hw: Tuple[int, int],
96
- target_hw: Tuple[int, int],
97
- invalid_gt: float = 10.0,
98
- ) -> torch.Tensor:
99
- ext = os.path.splitext(offset_path)[1].lower()
100
- if ext == ".npy":
101
- arr = np.load(offset_path).astype(np.float32)
102
- else:
103
- arr = np.loadtxt(offset_path, dtype=np.float32)
104
- arr = np.asarray(arr, dtype=np.float32).squeeze()
105
-
106
- src_h, src_w = int(source_hw[0]), int(source_hw[1])
107
- if arr.ndim == 1:
108
- if arr.size != src_h * src_w:
109
- raise ValueError(
110
- f"offset map length {arr.size} does not match source H*W={src_h*src_w}"
111
- )
112
- arr = arr.reshape(src_h, src_w)
113
- elif arr.ndim == 2:
114
- if arr.shape == (src_h, src_w):
115
- pass
116
- elif arr.shape == (src_w, src_h):
117
- arr = arr.T
118
- elif arr.size == src_h * src_w:
119
- arr = arr.reshape(src_h, src_w)
120
- else:
121
- raise ValueError(
122
- f"offset map shape {arr.shape} incompatible with source shape ({src_h}, {src_w})"
123
- )
124
- else:
125
- raise ValueError(f"offset map must be 1D/2D, got shape={arr.shape}")
126
-
127
- valid = (arr <= float(invalid_gt)).astype(np.float32)
128
- valid_t = torch.from_numpy(valid)[None, None, ...]
129
-
130
- dst_h, dst_w = int(target_hw[0]), int(target_hw[1])
131
- if (src_h, src_w) != (dst_h, dst_w):
132
- valid_t = F.interpolate(
133
- valid_t,
134
- size=(dst_h, dst_w),
135
- mode="nearest",
136
- )
137
- return valid_t.squeeze(0).squeeze(0) > 0.5
138
-
139
-
140
- def _load_measurement_histogram(path: str, hw: Tuple[int, int]) -> torch.Tensor:
141
- ext = os.path.splitext(path)[1].lower()
142
- if ext in (".txt", ".npz"):
143
- arr = _load_histogram_2d(path, dtype=np.float32)
144
- hist = _reshape_histogram_to_hwt(arr, hw)
145
- elif ext == ".pt":
146
- raw = torch.load(path, map_location="cpu")
147
- if not isinstance(raw, torch.Tensor):
148
- raise ValueError(f".pt file must contain a tensor: {path}")
149
- hist = raw.to_dense() if raw.is_sparse else raw
150
- hist = hist.to(torch.float32).cpu()
151
- if hist.ndim == 2:
152
- hist = _reshape_histogram_to_hwt(hist.numpy(), hw)
153
- elif hist.ndim == 3:
154
- pass
155
- else:
156
- raise ValueError(f"unsupported tensor shape in {path}: {tuple(hist.shape)}")
157
- # elif ext in (".h5", ".hdf5"):
158
- # with h5py.File(path, "r") as f:
159
- # if "data" not in f:
160
- # raise ValueError(f"h5 file missing key 'data': {path}")
161
- # arr = np.asarray(f["data"])
162
- # hist = _reshape_histogram_to_hwt(arr, hw)
163
- else:
164
- raise ValueError(f"unsupported measurement extension: {ext}")
165
-
166
- if hist.ndim == 4 and hist.shape[-1] == 1:
167
- hist = hist[..., 0]
168
- if hist.ndim == 4 and hist.shape[-1] == 3:
169
- hist = hist[..., 0]
170
- if hist.ndim != 3:
171
- raise ValueError(f"expected histogram shape [H,W,T], got {tuple(hist.shape)} from {path}")
172
- return hist
173
-
174
-
175
- def _parse_shift_for_grid(shift, hw: Tuple[int, int]):
176
- h, w = int(hw[0]), int(hw[1])
177
- arr = np.asarray(shift, dtype=np.float32)
178
- if arr.ndim == 0:
179
- return float(arr.item()), None
180
-
181
- arr = arr.squeeze()
182
- if arr.ndim == 0 or arr.size == 1:
183
- return float(arr.reshape(-1)[0]), None
184
-
185
- if arr.ndim == 1 and arr.size == h * w:
186
- return 0.0, torch.from_numpy(arr.reshape(h, w))
187
-
188
- if arr.ndim == 2:
189
- shift_map = torch.from_numpy(arr.astype(np.float32))
190
- if tuple(shift_map.shape) != (h, w):
191
- shift_map = F.interpolate(
192
- shift_map[None, None, ...],
193
- size=(h, w),
194
- mode="bilinear",
195
- align_corners=True,
196
- ).squeeze(0).squeeze(0)
197
- return 0.0, shift_map
198
-
199
- return float(arr.reshape(-1)[0]), None
200
-
201
-
202
- def _build_shift_grid(
203
- hw: Tuple[int, int],
204
- n_bins: int,
205
- shift,
206
- bin_width_s: float,
207
- device: str = "cpu",
208
- ) -> torch.Tensor:
209
- h, w = int(hw[0]), int(hw[1])
210
- exposure_time = C * float(bin_width_s)
211
- shift_scalar, shift_map = _parse_shift_for_grid(shift, hw)
212
-
213
- z = torch.arange(n_bins, device=device, dtype=torch.float32)[:, None, None]
214
- z = z * exposure_time / 2.0
215
- if shift_map is not None:
216
- z = z - shift_map.to(device)[None, ...]
217
- else:
218
- z = z - float(shift_scalar)
219
- z = z * 2.0 / exposure_time
220
- z = _normalize_index(z, n_bins)
221
-
222
- x = _normalize_index(torch.arange(w, device=device, dtype=torch.float32), w)
223
- y = _normalize_index(torch.arange(h, device=device, dtype=torch.float32), h)
224
-
225
- x = x[None, None, :].expand(n_bins, h, w)
226
- y = y[None, :, None].expand(n_bins, h, w)
227
- z = z.expand(n_bins, h, w)
228
-
229
- # grid_sample 5D grid order is (x, y, z) for input shaped [N,C,D,H,W].
230
- grid = torch.stack((x, y, z), dim=-1)[None, ...]
231
- return grid
232
-
233
-
234
- def _apply_shift(hist: torch.Tensor, shift, bin_width_s: float) -> torch.Tensor:
235
- h, w, t = hist.shape
236
- grid = _build_shift_grid((h, w), t, shift, bin_width_s, device=hist.device)
237
- # [H, W, T] -> [N=1, C=1, D=T, H, W]
238
- hist_dhw = hist.permute(2, 0, 1)[None, None, ...]
239
- shifted = F.grid_sample(hist_dhw, grid, align_corners=True)
240
- # back to [H, W, T]
241
- return shifted.squeeze(0).squeeze(0).permute(1, 2, 0)
242
-
243
-
244
- def _resize_hist_spatial(hist: torch.Tensor, target_hw: Tuple[int, int]) -> torch.Tensor:
245
- target_h, target_w = int(target_hw[0]), int(target_hw[1])
246
- h, w, _ = hist.shape
247
- if (h, w) == (target_h, target_w):
248
- return hist
249
- # [H,W,T] -> [1,T,H,W] for spatial resize only.
250
- hist_chw = hist.permute(2, 0, 1)[None, ...]
251
- resized = F.interpolate(hist_chw, size=(target_h, target_w), mode="area")
252
- return resized.squeeze(0).permute(1, 2, 0)
253
-
254
-
255
- def _resolve_measurement_path(
256
- data_dir: str,
257
- split: str,
258
- frame_file_path: str,
259
- measurement_root: str = None,
260
- data_exts: Sequence[str] = (".npz", ".txt", ".pt", ".h5", ".hdf5"),
261
- ) -> str:
262
- raw = str(frame_file_path)
263
- if os.path.isabs(raw) and os.path.isfile(raw):
264
- return raw
265
-
266
- rel = raw.replace("\\", "/").lstrip("./")
267
- base = os.path.basename(rel)
268
- stem, ext = os.path.splitext(base)
269
- rel_stem = os.path.splitext(rel)[0]
270
-
271
- roots = []
272
- if measurement_root:
273
- roots.extend([measurement_root, os.path.join(measurement_root, split)])
274
- roots.extend([data_dir, os.path.join(data_dir, split)])
275
-
276
- seen_roots = set()
277
- unique_roots = []
278
- for r in roots:
279
- rr = os.path.normpath(r)
280
- if rr not in seen_roots:
281
- unique_roots.append(rr)
282
- seen_roots.add(rr)
283
-
284
- # Prefer exact path if extension already exists.
285
- if ext:
286
- for root in unique_roots:
287
- for rel_name in (rel, base):
288
- cand = os.path.normpath(os.path.join(root, rel_name))
289
- if os.path.isfile(cand):
290
- return cand
291
-
292
- # Then resolve by stem and supported extensions.
293
- for root in unique_roots:
294
- for data_ext in data_exts:
295
- for rel_name in (rel_stem + data_ext, stem + data_ext):
296
- cand = os.path.normpath(os.path.join(root, rel_name))
297
- if os.path.isfile(cand):
298
- return cand
299
-
300
- raise FileNotFoundError(
301
- f"Cannot resolve measurement file for frame '{frame_file_path}'. "
302
- f"Searched roots={unique_roots}, exts={tuple(data_exts)}."
303
- )
304
-
305
-
306
- def _load_renderings_transient_real_ours(
307
- root_fp: str,
308
- split: str,
309
- have_images=True,
310
- img_shape=(256, 256),
311
- source_img_shape=None,
312
- n_bins=4096,
313
- shift=0,
314
- bin_width_s=4e-12,
315
- measurement_root=None,
316
- data_exts=(".npz", ".txt", ".pt", ".h5", ".hdf5"),
317
- ):
318
- data_dir = root_fp
319
- with open(os.path.join(data_dir, f"transforms_{split}.json"), "r", encoding="utf-8") as fp:
320
- meta = json.load(fp)
321
-
322
- images = []
323
- camtoworlds = []
324
-
325
- if have_images:
326
- tqdm.write("Loading data")
327
- reshape_hw = tuple(source_img_shape) if source_img_shape is not None else tuple(img_shape)
328
- for i in tqdm(range(len(meta["frames"]))):
329
- frame = meta["frames"][i]
330
- file_key = frame.get("file_path", frame.get("filepath"))
331
- if file_key is None:
332
- raise KeyError("Each frame in transforms json must contain 'file_path' or 'filepath'.")
333
- measurement_path = _resolve_measurement_path(
334
- data_dir=data_dir,
335
- split=split,
336
- frame_file_path=file_key,
337
- measurement_root=measurement_root,
338
- data_exts=data_exts,
339
- )
340
-
341
- hist = _load_measurement_histogram(measurement_path, reshape_hw).to(torch.float32).cpu()
342
- hist = torch.clip(hist, min=0.0)
343
- hist = _apply_shift(hist, shift=shift, bin_width_s=bin_width_s)
344
-
345
- if hist.shape[-1] != int(n_bins):
346
- raise ValueError(
347
- f"Histogram bin count mismatch for '{measurement_path}': "
348
- f"loaded {hist.shape[-1]} vs config n_bins={n_bins}. "
349
- "This pipeline does not truncate or adjacent-bin average."
350
- )
351
-
352
- hist = _resize_hist_spatial(hist, img_shape)
353
- hist_rgb = hist[..., None].repeat(1, 1, 1, 3)
354
-
355
- camtoworlds.append(frame["transform_matrix"])
356
- images.append(hist_rgb)
357
-
358
- images = torch.stack(images, axis=0)
359
- max_value = torch.max(images).clamp_min(1e-8)
360
- images = images / max_value
361
- camtoworlds = np.stack(camtoworlds, axis=0)
362
- else:
363
- for frame in meta["frames"]:
364
- camtoworlds.append(frame["transform_matrix"])
365
- camtoworlds = np.stack(camtoworlds, axis=0)
366
- max_value = torch.tensor(1.0)
367
-
368
- return images, camtoworlds, max_value
369
-
370
-
371
- class SubjectLoaderTransientRealOurs(torch.utils.data.Dataset):
372
- """Captured-data loader for custom txt/npz/pt histograms without bin truncation/averaging."""
373
-
374
- SPLITS = ["train", "val", "trainval", "test"]
375
- NEAR, FAR = 0, 6
376
- OPENGL_CAMERA = True
377
-
378
- def __init__(
379
- self,
380
- subject_id: str,
381
- root_fp: str,
382
- split: str,
383
- color_bkgd_aug: str = "black",
384
- num_rays: int = None,
385
- near: float = None,
386
- far: float = None,
387
- batch_over_images: bool = True,
388
- have_images=True,
389
- img_shape=(256, 256),
390
- source_img_shape=None,
391
- n_bins=10000,
392
- rfilter_sigma=0.15,
393
- sample_as_per_distribution=True,
394
- shift=0.0,
395
- testing=False,
396
- bin_width_s=4e-12,
397
- measurement_root=None,
398
- data_exts=(".npz", ".txt", ".pt", ".h5", ".hdf5"),
399
- invalid_mask_path=None,
400
- invalid_mask_invalid_gt=10.0,
401
- ):
402
- super().__init__()
403
- assert color_bkgd_aug in ["white", "black", "random"]
404
- self.sample_as_per_distribution = sample_as_per_distribution
405
- self.rfilter_sigma = rfilter_sigma
406
- self.HEIGHT, self.WIDTH = int(img_shape[0]), int(img_shape[1])
407
- self.split = split
408
- self.testing = testing
409
- self.num_rays = num_rays
410
- self.near = self.NEAR if near is None else near
411
- self.far = self.FAR if far is None else far
412
- self.training = (num_rays is not None) and (split in ["train", "trainval"])
413
- self.shift = shift
414
- self.rep = 1
415
- self.color_bkgd_aug = color_bkgd_aug
416
- self.batch_over_images = batch_over_images
417
- self.have_images = have_images
418
- self.n_bins = int(n_bins)
419
- self.bin_width_s = float(bin_width_s)
420
- self.measurement_root = measurement_root
421
- self.data_exts = tuple(data_exts)
422
- self.source_img_shape = tuple(source_img_shape) if source_img_shape is not None else None
423
- self.invalid_mask_path = invalid_mask_path
424
- self.invalid_mask_invalid_gt = float(invalid_mask_invalid_gt)
425
-
426
- if have_images:
427
- self.images, self.camtoworlds, self.max = _load_renderings_transient_real_ours(
428
- root_fp=root_fp,
429
- split=split,
430
- n_bins=self.n_bins,
431
- shift=shift,
432
- img_shape=(self.HEIGHT, self.WIDTH),
433
- source_img_shape=self.source_img_shape,
434
- bin_width_s=self.bin_width_s,
435
- measurement_root=self.measurement_root,
436
- data_exts=self.data_exts,
437
- )
438
- self.images = self.images.to(torch.float32)
439
- assert self.images.shape[1:3] == (self.HEIGHT, self.WIDTH)
440
- else:
441
- raise ValueError("have_images=False is not supported in SubjectLoaderTransientRealOurs.")
442
-
443
- self.camtoworlds = torch.from_numpy(self.camtoworlds).to(torch.float32)
444
- if self.invalid_mask_path:
445
- source_hw = (
446
- tuple(self.source_img_shape)
447
- if self.source_img_shape is not None
448
- else (self.HEIGHT, self.WIDTH)
449
- )
450
- self.valid_mask = _load_valid_mask_from_offset(
451
- self.invalid_mask_path,
452
- source_hw=source_hw,
453
- target_hw=(self.HEIGHT, self.WIDTH),
454
- invalid_gt=self.invalid_mask_invalid_gt,
455
- ).to(torch.bool)
456
- else:
457
- self.valid_mask = torch.ones((self.HEIGHT, self.WIDTH), dtype=torch.bool)
458
-
459
- def __len__(self):
460
- return len(self.camtoworlds)
461
-
462
- def __getitem__(self, index):
463
- data = self.fetch_data(index)
464
- data = self.preprocess(data)
465
- return data
466
-
467
- def preprocess(self, data):
468
- rgba, rays = data["rgba"], data["rays"]
469
-
470
- if rgba is not None:
471
- pixels = rgba.to(self.camtoworlds.device)
472
- else:
473
- pixels = rgba
474
-
475
- if self.color_bkgd_aug == "random":
476
- color_bkgd = torch.rand(3, device=self.camtoworlds.device)
477
- elif self.color_bkgd_aug == "white":
478
- color_bkgd = torch.ones(3, device=self.camtoworlds.device)
479
- else:
480
- color_bkgd = torch.zeros(3, device=self.camtoworlds.device)
481
-
482
- return {
483
- "pixels": pixels,
484
- "rays": rays,
485
- "color_bkgd": color_bkgd,
486
- **{k: v for k, v in data.items() if k not in ["rgba", "rays"]},
487
- }
488
-
489
- def update_num_rays(self, num_rays):
490
- self.num_rays = num_rays
491
-
492
- def fetch_data(self, index, rep=None, num_rays=None):
493
- if num_rays is None:
494
- num_rays = self.num_rays
495
- if rep is None:
496
- rep = self.rep
497
-
498
- if self.training:
499
- if self.batch_over_images:
500
- image_id = torch.randint(
501
- 0,
502
- len(self.images),
503
- size=(num_rays,),
504
- device=self.images.device,
505
- )
506
- else:
507
- image_id = [index]
508
- x = torch.randint(0, self.WIDTH, size=(num_rays,), device="cpu")
509
- y = torch.randint(0, self.HEIGHT, size=(num_rays,), device="cpu")
510
- x = x.repeat(rep)
511
- y = y.repeat(rep)
512
- image_id = image_id.repeat(rep)
513
- rgba = self.images[image_id, y, x]
514
- elif self.testing:
515
- image_id = [index]
516
- x, y = torch.meshgrid(
517
- torch.arange(self.WIDTH, device="cpu"),
518
- torch.arange(self.HEIGHT, device="cpu"),
519
- indexing="xy",
520
- )
521
- x = x.flatten().repeat(rep)
522
- y = y.flatten().repeat(rep)
523
- rgba = self.images[image_id, y, x] if self.have_images else None
524
- else:
525
- image_id = [index]
526
- x, y = torch.meshgrid(
527
- torch.arange(self.WIDTH, device=self.camtoworlds.device),
528
- torch.arange(self.HEIGHT, device=self.camtoworlds.device),
529
- indexing="xy",
530
- )
531
- x = x.flatten()
532
- y = y.flatten()
533
- rgba = self.images[image_id, y, x] if self.have_images else None
534
-
535
- x_cpu_long = x.detach().cpu().long()
536
- y_cpu_long = y.detach().cpu().long()
537
- valid_mask = self.valid_mask[y_cpu_long, x_cpu_long]
538
-
539
- c2w = self.camtoworlds[image_id]
540
- scale = self.rfilter_sigma
541
-
542
- if self.training or self.testing:
543
- s_x, s_y, weights = spatial_filter(
544
- x,
545
- y,
546
- sigma=scale,
547
- rep=self.rep,
548
- prob_dithering=self.sample_as_per_distribution,
549
- )
550
- s_x = torch.clip(x + torch.from_numpy(s_x), 0, self.WIDTH - 1).to(self.camtoworlds.device).to(torch.float32)
551
- s_y = torch.clip(y + torch.from_numpy(s_y), 0, self.HEIGHT - 1).to(self.camtoworlds.device).to(torch.float32)
552
- weights = torch.tensor(weights, device=self.camtoworlds.device, dtype=torch.float32)
553
- else:
554
- s_x = x
555
- s_y = y
556
- weights = None
557
-
558
- camera_dirs = self.K(s_x, s_y)
559
-
560
- directions = (camera_dirs[:, None, :] * c2w[:, :3, :3]).sum(dim=-1)
561
- origins = torch.broadcast_to(c2w[:, :3, -1], directions.shape)
562
- viewdirs = directions / torch.linalg.norm(directions, dim=-1, keepdims=True)
563
-
564
- if self.training:
565
- origins = torch.reshape(origins, (-1, 3))
566
- viewdirs = torch.reshape(viewdirs, (-1, 3))
567
- rgba = torch.reshape(rgba, (-1, self.n_bins * 3))
568
- valid_mask = torch.reshape(valid_mask, (-1,))
569
- elif self.testing:
570
- origins = torch.reshape(origins, (-1, 3))
571
- viewdirs = torch.reshape(viewdirs, (-1, 3))
572
- if self.have_images:
573
- rgba = torch.reshape(rgba, (-1, self.n_bins * 3))
574
- valid_mask = torch.reshape(valid_mask, (-1,))
575
- elif self.have_images:
576
- origins = torch.reshape(origins, (self.HEIGHT, self.WIDTH, 3))
577
- viewdirs = torch.reshape(viewdirs, (self.HEIGHT, self.WIDTH, 3))
578
- rgba = torch.reshape(rgba, (self.HEIGHT, self.WIDTH, self.n_bins * 3))
579
- valid_mask = torch.reshape(valid_mask, (self.HEIGHT, self.WIDTH))
580
- else:
581
- origins = torch.reshape(origins, (self.HEIGHT, self.WIDTH, 3))
582
- viewdirs = torch.reshape(viewdirs, (self.HEIGHT, self.WIDTH, 3))
583
- rgba = None
584
- valid_mask = torch.reshape(valid_mask, (self.HEIGHT, self.WIDTH))
585
-
586
- rays = Rays(origins=origins, viewdirs=viewdirs)
587
- if self.training or self.testing:
588
- return {"rgba": rgba, "rays": rays, "weights": weights, "valid_mask": valid_mask}
589
- return {"rgba": rgba, "rays": rays, "valid_mask": valid_mask}
590
-
591
-
592
- class LearnRays(torch.nn.Module):
593
- """Interpolation-based ray lookup from per-pixel ray table (H,W,3)."""
594
-
595
- def __init__(self, rays, device="cuda:0", img_shape=(256, 256)):
596
- super().__init__()
597
- self.device = device
598
- self.img_shape = (int(img_shape[0]), int(img_shape[1]))
599
- self.height = self.img_shape[0]
600
- self.width = self.img_shape[1]
601
-
602
- rays = np.asarray(rays, dtype=np.float32)
603
- if rays.ndim != 3 or rays.shape[-1] != 3:
604
- raise ValueError(f"rays must be [H,W,3], got shape={rays.shape}")
605
-
606
- rays_t = torch.from_numpy(rays).to(self.device)
607
- if tuple(rays_t.shape[:2]) != self.img_shape:
608
- rays_t = F.interpolate(
609
- rays_t.permute(2, 0, 1)[None, ...],
610
- size=self.img_shape,
611
- mode="bilinear",
612
- align_corners=True,
613
- ).squeeze(0).permute(1, 2, 0)
614
-
615
- rays_t = rays_t / torch.linalg.norm(rays_t, dim=-1, keepdims=True).clamp_min(1e-8)
616
- self.rays = rays_t
617
-
618
- def forward(self, x0, y0):
619
- rays = self.rays
620
- x0 = x0.to(rays.device).float()
621
- y0 = y0.to(rays.device).float()
622
-
623
- x1 = torch.floor(x0)
624
- y1 = torch.floor(y0)
625
- x2 = x1 + 1
626
- y2 = y1 + 1
627
-
628
- x1 = torch.clip(x1, 0, self.width - 1)
629
- y1 = torch.clip(y1, 0, self.height - 1)
630
- x2 = torch.clip(x2, 0, self.width - 1)
631
- y2 = torch.clip(y2, 0, self.height - 1)
632
-
633
- wx2 = ((x0 - x1) / (x2 - x1 + 1e-8))[:, None]
634
- wx1 = 1.0 - wx2
635
- wy2 = ((y0 - y1) / (y2 - y1 + 1e-8))[:, None]
636
- wy1 = 1.0 - wy2
637
-
638
- x1 = x1.long()
639
- y1 = y1.long()
640
- x2 = x2.long()
641
- y2 = y2.long()
642
-
643
- out = (
644
- wx1 * wy1 * rays[y1, x1]
645
- + wx1 * wy2 * rays[y2, x1]
646
- + wx2 * wy1 * rays[y1, x2]
647
- + wx2 * wy2 * rays[y2, x2]
648
- )
649
- out = out / torch.linalg.norm(out, dim=-1, keepdims=True).clamp_min(1e-8)
650
- return out.float()
651
-
652
-
653
- def spatial_filter(x, y, sigma, rep, prob_dithering=True):
654
- pdf_fn = lambda z: np.exp(-z / (2 * sigma**2)) - np.exp(-16)
655
- if prob_dithering:
656
- bounds_max = [4 * sigma] * x.shape[0]
657
- loc = 0
658
- s_x = scipy.stats.truncnorm.rvs(
659
- (-np.array(bounds_max) - loc) / sigma,
660
- (np.array(bounds_max) - loc) / sigma,
661
- loc=loc,
662
- scale=sigma,
663
- )
664
- s_y = scipy.stats.truncnorm.rvs(
665
- (-np.array(bounds_max) - loc) / sigma,
666
- (np.array(bounds_max) - loc) / sigma,
667
- loc=loc,
668
- scale=sigma,
669
- )
670
- weights = np.ones_like(s_x) * 1 / rep
671
- else:
672
- s_x = np.random.uniform(low=-4 * sigma, high=4 * sigma, size=(rep, x.shape[0] // rep))
673
- s_y = np.random.uniform(low=-4 * sigma, high=4 * sigma, size=(rep, x.shape[0] // rep))
674
- dists = s_x**2 + s_y**2
675
- weights = pdf_fn(dists)
676
- weights = weights / weights.sum(0)[None, :]
677
- s_x = s_x.flatten()
678
- s_y = s_y.flatten()
679
- weights = weights.flatten()
680
- return s_x, s_y, weights
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/loaders/loader_synthetic.py DELETED
@@ -1,453 +0,0 @@
1
- import collections
2
- import json
3
- import os
4
-
5
- import imageio.v2 as imageio
6
- import numpy as np
7
- import torch
8
- import torch.nn.functional as F
9
- import scipy
10
- import zipfile
11
- from .utils import Rays
12
- import sys
13
- sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
14
- from misc.dataset_utils import read_h5
15
- from tqdm import tqdm
16
-
17
- def _load_renderings(root_fp: str, subject_id: str, split: str, have_images=True, img_shape=(256, 256)):
18
- """Load images from disk."""
19
- # if not root_fp.startswith("/"):
20
- # # allow relative path. e.g., "./data/nerf_synthetic/"
21
- # root_fp = os.path.join(
22
- # os.path.dirname(os.path.abspath(__file__)),
23
- # "..",
24
- # "..",
25
- # root_fp,
26
- # )
27
-
28
- data_dir = root_fp
29
- with open(
30
- os.path.join(data_dir, "transforms_{}.json".format(split)), "r"
31
- ) as fp:
32
- meta = json.load(fp)
33
- images = []
34
- camtoworlds = []
35
-
36
- if have_images:
37
- for i in range(len(meta["frames"])):
38
- frame = meta["frames"][i]
39
- number = int(frame["file_path"].split("_")[-1])
40
- fname = os.path.join(data_dir, f"{number:03d}" + ".png")
41
-
42
- # fname = os.path.join(data_dir, frame["file_path"] + ".png")
43
- rgba = imageio.imread(fname)
44
- camtoworlds.append(frame["transform_matrix"])
45
- images.append(rgba)
46
-
47
- images = np.stack(images, axis=0)
48
- camtoworlds = np.stack(camtoworlds, axis=0)
49
-
50
- h, w = images.shape[1:3]
51
- else:
52
- for i in range(len(meta["frames"])):
53
- frame = meta["frames"][i]
54
- camtoworlds.append(frame["transform_matrix"])
55
-
56
- camtoworlds = np.stack(camtoworlds, axis=0)
57
-
58
- h, w = img_shape
59
-
60
- camera_angle_x = float(meta["camera_angle_x"])
61
- focal = 0.5 * w / np.tan(0.5 * camera_angle_x)
62
-
63
- return images, camtoworlds, focal
64
-
65
-
66
- def _load_renderings_transient(root_fp: str, subject_id: str, split: str, num_views= None, have_images=True, img_shape=(256, 256), gamma=False):
67
- """Load images from disk."""
68
- # if not root_fp.startswith("/"):
69
- # # allow relative path. e.g., "./data/nerf_synthetic/"
70
- # root_fp = os.path.join(
71
- # os.path.dirname(os.path.abspath(__file__)),
72
- # "..",
73
- # "..",
74
- # root_fp,
75
- # )
76
-
77
- data_dir = root_fp
78
- if split == "train": tname = f"train_v{num_views}"
79
- else: tname = split
80
-
81
- with open(
82
- os.path.join(data_dir, "transforms_{}.json".format(tname)), "r"
83
- ) as fp:
84
- meta = json.load(fp)
85
- images = []
86
- camtoworlds = []
87
-
88
- if have_images:
89
- for i in tqdm(range(len(meta["frames"]))):
90
- frame = meta["frames"][i]
91
- number = int(frame["file_path"].split("_")[-1])
92
-
93
- try:
94
- files_dir = os.path.join(data_dir, split)
95
- fname = os.path.join(files_dir, f"{split}_{number:03d}" + ".h5")
96
- rgba = read_h5(fname)
97
- except:
98
- try:
99
- files_dir = os.path.join(data_dir, "test")
100
- fname = os.path.join(files_dir, f"test_{number:03d}" + ".h5")
101
- rgba = read_h5(fname)
102
- except:
103
- try:
104
- files_dir = os.path.join(data_dir, "test")
105
- fname = os.path.join(files_dir, f"test_{number:03d}" + ".h5")
106
- archive = zipfile.ZipFile(f"{fname}.zip")
107
- file = archive.open(f"test_{number:03d}" + ".h5")
108
- rgba = read_h5(file)
109
- file.close()
110
- except:
111
- pass
112
-
113
-
114
-
115
- rgba = rgba[..., :3]
116
-
117
- if gamma:
118
- print("using gamma")
119
- rgba_sum = rgba.sum(-2)
120
- rgba_sum_normalized = rgba_sum/rgba_sum.max()
121
- rgba_sum_norm_gamma = rgba_sum_normalized**(1/2.2)
122
- rgba = (rgba*rgba_sum_norm_gamma[..., None, :])/(rgba_sum[..., None, :]+1e-10)
123
-
124
- camtoworlds.append(frame["transform_matrix"])
125
- rgba = torch.clip(torch.Tensor(rgba), 0, None)
126
- images.append(torch.Tensor(rgba))
127
-
128
-
129
- images = torch.stack(images, axis=0)
130
-
131
- if split == "test":
132
- quotient = images.shape[1]//img_shape[0]
133
- times_downsample = int(np.log2(quotient))
134
-
135
- for i in range(times_downsample):
136
- images = (images[:, 1::2, ::2] + images[:, ::2, ::2] + images[:, 1::2, 1::2] + images[:, ::2, 1::2])/4
137
-
138
-
139
- if not gamma:
140
- #np.save(os.path.join(data_dir, "max.npy"), torch.max(images).numpy())
141
- max = torch.max(images)
142
- images /= torch.max(images)
143
-
144
- camtoworlds = np.stack(camtoworlds, axis=0)
145
-
146
- h, w = images.shape[1:3]
147
- else:
148
- for i in range(len(meta["frames"])):
149
- frame = meta["frames"][i]
150
- camtoworlds.append(frame["transform_matrix"])
151
-
152
- camtoworlds = np.stack(camtoworlds, axis=0)
153
-
154
- h, w = img_shape
155
-
156
- camera_angle_x = float(meta["camera_angle_x"])
157
- focal = 0.5 * w / np.tan(0.5 * camera_angle_x)
158
-
159
- return images, camtoworlds, focal, max
160
-
161
-
162
-
163
- class SubjectLoaderTransient(torch.utils.data.Dataset):
164
- """Single subject data loader for training and evaluation."""
165
-
166
- SPLITS = ["train", "val", "trainval", "test"]
167
-
168
- # WIDTH, HEIGHT = 64, 64
169
- NEAR, FAR = 0, 6
170
- OPENGL_CAMERA = True
171
-
172
- def __init__(
173
- self,
174
- subject_id: str,
175
- root_fp: str,
176
- split: str,
177
- color_bkgd_aug: str = "black",
178
- num_rays: int = None,
179
- near: float = None,
180
- far: float = None,
181
- batch_over_images: bool = True,
182
- have_images=True,
183
- img_shape=(256, 256),
184
- n_bins=10000,
185
- testing=False,
186
- rfilter_sigma=0.3,
187
- scene=None,
188
- sample_as_per_distribution = True,
189
- gamma=False,
190
- num_views = None
191
- ):
192
- super().__init__()
193
- self.testing = testing
194
- # assert split in self.SPLITS, "%s" % split
195
- assert color_bkgd_aug in ["white", "black", "random"]
196
- self.sample_as_per_distribution = sample_as_per_distribution
197
-
198
- self.HEIGHT, self.WIDTH = img_shape
199
- self.split = split
200
- self.num_rays = num_rays
201
- self.near = self.NEAR if near is None else near
202
- self.far = self.FAR if far is None else far
203
- self.training = (num_rays is not None) and (
204
- split in ["train", "trainval"]
205
- )
206
- self.rep = 0
207
- self.color_bkgd_aug = color_bkgd_aug
208
- self.batch_over_images = batch_over_images
209
- self.have_images = have_images
210
- self.rfilter_sigma = rfilter_sigma
211
- self.n_bins = n_bins
212
- if split == "trainval":
213
- _images_train, _camtoworlds_train, _focal_train = _load_renderings_transient(
214
- root_fp, subject_id, "train", gamma=gamma
215
- )
216
- _images_val, _camtoworlds_val, _focal_val = _load_renderings_transient(
217
- root_fp, subject_id, "val", gamma=gamma
218
- )
219
- self.images = np.concatenate([_images_train, _images_val])
220
- self.camtoworlds = np.concatenate(
221
- [_camtoworlds_train, _camtoworlds_val]
222
- )
223
- self.focal = _focal_train
224
- self.images = torch.from_numpy(self.images).to(torch.float32)
225
-
226
- # ste for transient
227
- self.images = torch.reshape(self.images, (-1, self.HEIGHT, self.WIDTH, self.n_bins*3))
228
- # assert self.images.shape[1:3] == (self.HEIGHT, self.WIDTH)
229
-
230
- elif have_images:
231
- self.images, self.camtoworlds, self.focal, self.max = _load_renderings_transient(
232
- root_fp, subject_id, split, gamma=gamma, img_shape=img_shape, num_views=num_views
233
- )
234
- self.images = self.images.to(torch.float32)
235
- assert self.images.shape[1:3] == (self.HEIGHT, self.WIDTH)
236
- else:
237
- _, self.camtoworlds, self.focal = _load_renderings(
238
- root_fp, subject_id, split, have_images=have_images, img_shape=img_shape, num_views=num_views
239
- )
240
-
241
- self.camtoworlds = torch.from_numpy(self.camtoworlds).to(torch.float32)
242
- self.K = torch.tensor(
243
- [
244
- [self.focal, 0, self.WIDTH / 2.0],
245
- [0, self.focal, self.HEIGHT / 2.0],
246
- [0, 0, 1],
247
- ],
248
- dtype=torch.float32,
249
- ) # (3, 3)
250
-
251
- def __len__(self):
252
- return len(self.camtoworlds)
253
-
254
- @torch.no_grad()
255
- def __getitem__(self, index):
256
- data = self.fetch_data(index)
257
- data = self.preprocess(data)
258
- return data
259
-
260
- def preprocess(self, data):
261
- """Process the fetched / cached data with randomness."""
262
- rgba, rays = data["rgba"], data["rays"]
263
- # pixels, alpha = torch.split(rgba, [3, 1], dim=-1)
264
- if rgba is not None:
265
- pixels = rgba.to(self.camtoworlds.device)
266
- else:
267
- pixels = rgba
268
-
269
- if self.color_bkgd_aug == "random":
270
- color_bkgd = torch.rand(3, device=self.camtoworlds.device)
271
- elif self.color_bkgd_aug == "white":
272
- color_bkgd = torch.ones(3, device=self.camtoworlds.device)
273
- elif self.color_bkgd_aug == "black":
274
- color_bkgd = torch.zeros(3, device=self.camtoworlds.device)
275
-
276
- # pixels = pixels * alpha + color_bkgd * (1.0 - alpha)
277
- return {
278
- "pixels": pixels, # [n_rays, 3] or [h, w, 3]
279
- "rays": rays, # [n_rays,] or [h, w]
280
- "color_bkgd": color_bkgd, # [3,]
281
- **{k: v for k, v in data.items() if k not in ["rgba", "rays"]},
282
- }
283
-
284
- def update_num_rays(self, num_rays):
285
- self.num_rays = num_rays
286
-
287
- def fetch_data(self, index, rep=None, num_rays=None):
288
- """Fetch the data (it maybe cached for multiple batches)."""
289
- if num_rays==None:
290
- num_rays = self.num_rays
291
- if rep==None:
292
- rep = self.rep
293
-
294
- if self.training:
295
- if self.batch_over_images:
296
- image_id = torch.randint(
297
- 0,
298
- len(self.images),
299
- size=(num_rays,),
300
- device=self.images.device,
301
- )
302
- else:
303
- image_id = [index]
304
- x = torch.randint(
305
- 0, self.WIDTH, size=(num_rays,), device=self.images.device
306
- )
307
- y = torch.randint(
308
- 0, self.HEIGHT, size=(num_rays,), device=self.images.device
309
- )
310
- x = x.repeat(rep)
311
- y = y.repeat(rep)
312
- image_id = image_id.repeat(rep)
313
-
314
-
315
- rgba = self.images[image_id, y, x] # (num_rays, 4)
316
-
317
- elif self.testing:
318
- image_id = [index]
319
- x, y = torch.meshgrid(
320
- torch.arange(self.WIDTH, device="cpu"),
321
- torch.arange(self.HEIGHT, device="cpu"),
322
- indexing="xy",
323
- )
324
- x = x.flatten()
325
- y = y.flatten()
326
- x = x.repeat(rep)
327
- y = y.repeat(rep)
328
- # image_id = image_id.repeat(rep)
329
- try:
330
- rgba = self.images[image_id, y, x] # (num_rays, 4)
331
- except: rgba=None
332
-
333
- elif self.have_images:
334
- image_id = [index]
335
- x, y = torch.meshgrid(
336
- torch.arange(self.WIDTH, device=self.camtoworlds.device),
337
- torch.arange(self.HEIGHT, device=self.camtoworlds.device),
338
- indexing="xy",
339
- )
340
- x = x.flatten()
341
- y = y.flatten()
342
- rgba = self.images[image_id, y, x] # (num_rays, 4)
343
- else:
344
- image_id = [index]
345
- x, y = torch.meshgrid(
346
- torch.arange(self.WIDTH, device=self.camtoworlds.device),
347
- torch.arange(self.HEIGHT, device=self.camtoworlds.device),
348
- indexing="xy",
349
- )
350
- x = x.flatten()
351
- y = y.flatten()
352
-
353
- # generate rays
354
-
355
- scale = self.rfilter_sigma
356
- c2w = self.camtoworlds[image_id] # (num_rays, 3, 4)
357
- bounds_max = [4*scale]*x.shape[0]
358
- loc = 0
359
- if self.training:
360
- s_x, s_y, weights = spatial_filter(x, y, sigma=scale, rep = self.rep, prob_dithering=self.sample_as_per_distribution)
361
- s_x = (torch.clip(x + torch.from_numpy(s_x), 0, self.WIDTH).to(self.camtoworlds.device)).to(torch.float32)
362
- s_y = (torch.clip(y + torch.from_numpy(s_y), 0, self.HEIGHT).to(self.camtoworlds.device)).to(torch.float32)
363
- weights = torch.Tensor(weights).to(self.camtoworlds.device)
364
- #s_x = x.to(self.camtoworlds.device).to(torch.float32)
365
- #s_y = y.to(self.camtoworlds.device).to(torch.float32)
366
-
367
- elif self.testing:
368
- s_x, s_y, weights = spatial_filter(x, y, sigma=scale, rep = self.rep, prob_dithering=self.sample_as_per_distribution, normalize=False)
369
- s_x = (torch.clip(x + torch.from_numpy(s_x), 0, self.WIDTH).to(self.camtoworlds.device)).to(torch.float32)
370
- s_y = (torch.clip(y + torch.from_numpy(s_y), 0, self.HEIGHT).to(self.camtoworlds.device)).to(torch.float32)
371
- weights = torch.Tensor(weights).to(self.camtoworlds.device)
372
- #s_x = x.to(self.camtoworlds.device).to(torch.float32)
373
- #s_y = y.to(self.camtoworlds.device).to(torch.float32)
374
- else:
375
- s_x = x
376
- s_y = y
377
-
378
- camera_dirs = F.pad(
379
- torch.stack(
380
- [
381
- (s_x - self.K[0, 2] + 0.5) / self.K[0, 0],
382
- (s_y - self.K[1, 2] + 0.5)
383
- / self.K[1, 1]
384
- * (-1.0 if self.OPENGL_CAMERA else 1.0),
385
- ],
386
- dim=-1,
387
- ),
388
- (0, 1),
389
- value=(-1.0 if self.OPENGL_CAMERA else 1.0),
390
- )
391
-
392
- directions = (camera_dirs[:, None, :] * c2w[:, :3, :3]).sum(dim=-1)
393
- origins = torch.broadcast_to(c2w[:, :3, -1], directions.shape)
394
- viewdirs = directions / torch.linalg.norm(
395
- directions, dim=-1, keepdims=True
396
- )
397
-
398
- if self.training:
399
- origins = torch.reshape(origins, (-1, 3))
400
- viewdirs = torch.reshape(viewdirs, (-1, 3))
401
- # here
402
- rgba = torch.reshape(rgba, (-1,self.n_bins*3))
403
- elif self.testing:
404
- origins = torch.reshape(origins, (-1, 3))
405
- viewdirs = torch.reshape(viewdirs, (-1, 3))
406
- # here
407
- try: rgba = torch.reshape(rgba, (-1,self.n_bins*3))
408
- except: rgba = None
409
-
410
- elif self.have_images:
411
- origins = torch.reshape(origins, (self.HEIGHT, self.WIDTH, 3))
412
- viewdirs = torch.reshape(viewdirs, (self.HEIGHT, self.WIDTH, 3))
413
- rgba = torch.reshape(rgba, (self.HEIGHT, self.WIDTH, self.n_bins * 3))
414
- else:
415
- origins = torch.reshape(origins, (self.HEIGHT, self.WIDTH, 3))
416
- viewdirs = torch.reshape(viewdirs, (self.HEIGHT, self.WIDTH, 3))
417
- rgba = None
418
-
419
- rays = Rays(origins=origins, viewdirs=viewdirs)
420
- if self.training or self.testing:
421
- return {
422
- "rgba": rgba, # [h, w, 4] or [num_rays, 4]
423
- "rays": rays, # [h, w, 3] or [num_rays, 3]
424
- "weights":weights
425
- }
426
-
427
- return {
428
- "rgba": rgba, # [h, w, 4] or [num_rays, 4]
429
- "rays": rays, # [h, w, 3] or [num_rays, 3]
430
- }
431
-
432
-
433
- def spatial_filter(x, y, sigma, rep, prob_dithering=True, normalize=True):
434
- pdf_fn = lambda x: np.exp(-x/(2*sigma**2)) - np.exp(-16)
435
- if prob_dithering:
436
- bounds_max = [4*sigma]*x.shape[0]
437
- loc = 0
438
- s_x = scipy.stats.truncnorm.rvs((-np.array(bounds_max)-loc)/sigma, (np.array(bounds_max)-loc)/sigma, loc=loc, scale=sigma)
439
- s_y = scipy.stats.truncnorm.rvs((-np.array(bounds_max)-loc)/sigma, (np.array(bounds_max)-loc)/sigma, loc=loc, scale=sigma)
440
- weights = np.ones_like(s_x)*1/rep
441
-
442
- else:
443
- s_x = np.random.uniform(low=-4*sigma, high=4*sigma, size=(rep, x.shape[0]//rep))
444
- s_y = np.random.uniform(low=-4*sigma, high=4*sigma, size=(rep, x.shape[0]//rep))
445
- dists = (s_x**2 + s_y**2)
446
- weights = pdf_fn(dists)
447
- if normalize:
448
- weights = weights/weights.sum(0)[None, :]
449
- s_x = s_x.flatten()
450
- s_y = s_y.flatten()
451
- weights = weights.flatten()
452
-
453
- return s_x, s_y, weights
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/loaders/utils.py DELETED
@@ -1,12 +0,0 @@
1
- """
2
- Copyright (c) 2022 Ruilong Li, UC Berkeley.
3
- """
4
-
5
- import collections
6
-
7
- Rays = collections.namedtuple("Rays", ("origins", "viewdirs"))
8
-
9
-
10
- def namedtuple_map(fn, tup):
11
- """Apply `fn` to each element of `tup` and cast to `tup`'s namedtuple."""
12
- return type(tup)(*(None if x is None else fn(x) for x in tup))
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/misc/__init__.py DELETED
File without changes
codes/reconstruction/transientnerf/misc/dataset_utils.py DELETED
@@ -1,169 +0,0 @@
1
- import os
2
- import mat73
3
- import torch
4
- import numpy as np
5
- import json
6
- import h5py
7
-
8
- def read_h5(path):
9
- with h5py.File(path, 'r') as f:
10
- frames = np.array(f['data'])
11
- return frames
12
-
13
- def process_captured_data(files_path, savepath):
14
- for file in os.listdir(files_path):
15
- if file[-3:] == "mat" and (file[:-3]+"pt") not in os.listdir(savepath):
16
- filepath = os.path.join(files_path, file)
17
- rgba = mat73.loadmat(filepath)["transient"].transpose(1, 2, 0)[..., :][..., None]
18
- rgba = np.flip(np.flip(rgba, 0), 1)
19
- for i in range(3):
20
- rgba = (rgba[1::2, ::2] + rgba[::2, ::2] + rgba[1::2, 1::2] + rgba[::2, 1::2])/4
21
- torch.save(rgba, os.path.join(savepath, file[:-3]+"pt"))
22
-
23
- def bundle_rays(pathToH5s, outputPath, trainJsonPath):
24
- with open(trainJsonPath, "r") as fp:
25
- meta = json.load(fp)
26
- train_fnames = []
27
- for i in range(len(meta["frames"])):
28
- frame = meta["frames"][i]
29
- fname = frame["filepath"][:-2]+"h5"
30
- train_fnames.append(fname)
31
-
32
- frames = read_h5(os.path.join(pathToH5s, train_fnames[0]))
33
- w = frames.shape[0]
34
- h = frames.shape[1]
35
- bins = frames.shape[2]
36
-
37
- x = np.linspace(0, h-1, h)
38
- y = np.linspace(0, w-1, w)
39
- X, Y = np.meshgrid(x, y)
40
-
41
- if len(frames.shape) == 4:
42
- channels = 3
43
- else:
44
- channels = 1
45
- num_train_files = len(train_fnames)
46
-
47
- data_array = np.zeros((w*h*num_train_files, bins, channels), dtype=np.float32)
48
- x_array = np.zeros(w*h*num_train_files)
49
- y_array = np.zeros(w*h*num_train_files)
50
- file_prefix_array = np.zeros(w*h*num_train_files)
51
-
52
- for ind, file in enumerate(train_fnames):
53
- print("Opening: " + file)
54
- frames = read_h5(os.path.join(pathToH5s, file))
55
- frames = frames.reshape(-1, frames.shape[2], frames.shape[3])
56
-
57
- data_array[ind*w*h:(ind+1)*w*h] = frames[..., :3]
58
- x_array[ind*w*h:(ind+1)*w*h] = X.flatten()
59
- y_array[ind*w*h:(ind+1)*w*h] = Y.flatten()
60
- file_prefix_array[ind*w*h:(ind+1)*w*h] = ind
61
-
62
- p = np.random.permutation(data_array.shape[0])
63
- data_array = data_array[p]
64
- x_array = x_array[p]
65
- y_array = y_array[p]
66
- file_prefix_array = file_prefix_array[p]
67
-
68
-
69
- print("Outputting to files")
70
- file = h5py.File(os.path.join(outputPath, "samples.h5"), 'w')
71
- dataset = file.create_dataset(
72
- "dataset", data_array.shape, dtype='f', data=data_array
73
- )
74
- file.close()
75
-
76
- file = h5py.File(os.path.join(outputPath, "x.h5"), 'w')
77
- dataset = file.create_dataset(
78
- "dataset", x_array.shape, dtype='f', data=x_array
79
- )
80
- file.close()
81
-
82
- file = h5py.File(os.path.join(outputPath, "y.h5"), 'w')
83
- dataset = file.create_dataset(
84
- "dataset", y_array.shape, dtype='f', data=y_array
85
- )
86
- file.close()
87
- file = h5py.File(os.path.join(outputPath, "file_indices.h5"), 'w')
88
- dataset = file.create_dataset(
89
- "dataset", file_prefix_array.shape, dtype='f', data=file_prefix_array
90
- )
91
- file.close()
92
-
93
-
94
- def bundle_rays_cap(pathToH5s, outputPath, trainJsonPath):
95
- with open(trainJsonPath, "r") as fp:
96
- meta = json.load(fp)
97
- train_fnames = []
98
- for i in range(len(meta["frames"])):
99
- frame = meta["frames"][i]
100
- fname = frame["filepath"][:-2].split("/")[-1]+"mat"
101
- train_fnames.append(fname)
102
-
103
- # frames = read_h5_dataset(os.path.join(pathToH5s, train_fnames[0]))
104
- frames = mat73.loadmat(os.path.join(pathToH5s, train_fnames[0]))["transient"].transpose(1, 2, 0)
105
- w = frames.shape[0]
106
- h = frames.shape[1]
107
- # bins = frames.shape[2]
108
- bins = 3000
109
-
110
- x = np.linspace(0, h-1, h)
111
- y = np.linspace(0, w-1, w)
112
- X, Y = np.meshgrid(x, y)
113
-
114
- # if len(frames.shape) == 4:
115
- # channels = 3
116
- # else:
117
- channels = 1
118
- num_train_files = len(train_fnames)
119
-
120
- data_array = np.zeros((w*h*num_train_files, bins, channels), dtype=np.float32)
121
- x_array = np.zeros(w*h*num_train_files)
122
- y_array = np.zeros(w*h*num_train_files)
123
- file_prefix_array = np.zeros(w*h*num_train_files)
124
-
125
- for ind, file in enumerate(train_fnames):
126
- print("Opening: " + file)
127
- # frames = read_h5_dataset(os.path.join(pathToH5s, file))
128
- frames = mat73.loadmat(os.path.join(pathToH5s, file))["transient"].transpose(1, 2, 0)
129
- frames = frames.reshape(-1, frames.shape[2])
130
-
131
- data_array[ind*w*h:(ind+1)*w*h] = frames[..., :bins, None]
132
- # del frames
133
- x_array[ind*w*h:(ind+1)*w*h] = X.flatten()
134
- y_array[ind*w*h:(ind+1)*w*h] = Y.flatten()
135
- file_prefix_array[ind*w*h:(ind+1)*w*h] = ind
136
-
137
- p = np.random.permutation(data_array.shape[0])
138
- data_array = data_array[p]
139
- x_array = x_array[p]
140
- y_array = y_array[p]
141
- file_prefix_array = file_prefix_array[p]
142
-
143
-
144
- print("Outputting to files")
145
- file = h5py.File(os.path.join(outputPath, "samples.h5"), 'w')
146
- dataset = file.create_dataset(
147
- "dataset", data_array.shape, dtype='f', data=data_array
148
- )
149
- file.close()
150
-
151
- file = h5py.File(os.path.join(outputPath, "x.h5"), 'w')
152
- dataset = file.create_dataset(
153
- "dataset", x_array.shape, dtype='f', data=x_array
154
- )
155
- file.close()
156
-
157
- file = h5py.File(os.path.join(outputPath, "y.h5"), 'w')
158
- dataset = file.create_dataset(
159
- "dataset", y_array.shape, dtype='f', data=y_array
160
- )
161
- file.close()
162
- file = h5py.File(os.path.join(outputPath, "file_indices.h5"), 'w')
163
- dataset = file.create_dataset(
164
- "dataset", file_prefix_array.shape, dtype='f', data=file_prefix_array
165
- )
166
- file.close()
167
-
168
- if __name__=="__main__":
169
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/misc/download_dataset.py DELETED
@@ -1,67 +0,0 @@
1
- import subprocess
2
- import configargparse
3
- import os
4
-
5
- def download_dataset(scenes):
6
- link_dict = {
7
- "bench":"https://www.dropbox.com/scl/fo/a7c6ej2zj5julibmi0oe7/AOzgkS7_PkMNzg4ybZBTTZ8?rlkey=jjkqqz6ifi2ib3g01yf03j12h&st=v02sztb4&dl=0",
8
- "lego":"https://www.dropbox.com/scl/fo/xrvnu5i7cwg6ng4iveerd/APXNbHRR2IJqP6q384ZrsTY?rlkey=qag95l1xn3hgebxqcqb4grdbw&st=1xjm5ob9&dl=0",
9
- "chair":"https://www.dropbox.com/scl/fo/rw1kx28apf2nj9nmmankn/AAXBD63yuU-TcaKJRh2WlUQ?rlkey=58tb99g1d41ml4asqxdp5lrxg&st=og6clu8k&dl=0",
10
- "ficus":"https://www.dropbox.com/scl/fo/ash43k5stxykgu82y0rty/AJM0R8PdduoE4BMl31BI7xY?rlkey=ad1uacytq2mr5e0hc4tpmm7xp&st=uwm356c4&dl=0",
11
- "hotdog":"https://www.dropbox.com/scl/fo/lrbe9b8tsmpu6m3e25s7q/ANANvfFhEdoib9rHv5QmPwo?rlkey=bea0k5zi6ahgts88mlpvs4mta&st=8itg14zh&dl=0",
12
- "boots":"https://www.dropbox.com/scl/fo/cx5tl37qjytcv8v652q00/ADOzXV5AbW0_y_wpptIk8PY?rlkey=ne75mf8kc3hg6wg7coak74ww5&st=hklnyi76&dl=0",
13
- "carving":"https://www.dropbox.com/scl/fo/962tg8nqtx42m7lasqo7s/AIAl3BFPt7U1xD8eanwZnP8?rlkey=qm3r7d52dnvroac8lwsbq93pb&st=58hvm91y&dl=0",
14
- "baskets":"https://www.dropbox.com/scl/fo/jxvcp63h0z7u0hptk2b0f/AOvcyi2RB0R-999nzQZtwvk?rlkey=ce229qfku8brdfznzl62fi792&st=yf4aii6e&dl=0",
15
- "chef":"https://www.dropbox.com/scl/fo/15mcemsypabotbsr07gf0/AIdsXG0GHVp_FLf7i95Orr4?rlkey=abugupv7fo1gtjue73h0jm8uf&st=omb14j7c&dl=0",
16
- "cinema":"https://www.dropbox.com/scl/fo/hdytz9zw73jq2f3hxp44b/ACQvEjYApQ6hDfhpf2vvoSw?rlkey=caeizu4zklzziyzt3wlcb4pgg&st=nherw66u&dl=0",
17
- "food":"https://www.dropbox.com/scl/fo/brg2po03txm7nftnljhyb/AFfgHP1517nCEfY1oVGhfYo?rlkey=znxzp37wao2y9bydq8ceapimr&st=8kfsaiob&dl=0",
18
- "intrinsics.npy":"https://www.dropbox.com/scl/fi/s4whgdajo5jy5wmdtlhwf/intrinsics.npy?rlkey=s247t4pvtubn726dzpnwmnlrv&st=0hnobsb9&dl=0",
19
- "pulse_low_flux.mat":"https://www.dropbox.com/scl/fi/x63omsjecjijpg5q5dpiw/pulse_low_flux.mat?rlkey=1dm9d8jrdrogtw2xbgg2x8x17&st=4gll02on&dl=0",
20
- }
21
- os.makedirs("dataset", exist_ok = True)
22
- for file in ["pulse_low_flux.mat", "intrinsics.npy"]:
23
- command = f'wget "{link_dict[file]}" -O ./dataset/{file}'
24
- subprocess.run(command, shell=True)
25
-
26
-
27
- for folder in scenes:
28
- os.makedirs(f"dataset/{folder}", exist_ok = True)
29
-
30
- command = f'wget "{link_dict[folder]}" -O dataset/{folder}.zip'
31
- subprocess.run(command, shell=True)
32
-
33
- command = f"unzip dataset/{folder}.zip -d dataset/{folder}"
34
- subprocess.run(command, shell=True)
35
-
36
- command = f"rm dataset/{folder}.zip"
37
- subprocess.run(command, shell=True)
38
-
39
-
40
-
41
-
42
- if __name__=="__main__":
43
- parser = configargparse.ArgumentParser()
44
- parser.add_argument('--scenes', nargs='+', help='list of files to download')
45
- args = parser.parse_args()
46
-
47
- final_scenes = []
48
- all_scenes = ["cinema", "carving", "boots", "food", "chef", "baskets", "lego", "chair", "ficus", "hotdog", "bench"]
49
-
50
- if "all" in args.scenes:
51
- final_scenes = all_scenes.copy()
52
-
53
- if "captured" in args.scenes:
54
- scenes = ["cinema", "carving", "boots", "food", "chef", "baskets"]
55
- if "simulated" in args.scenes:
56
- scenes = ["lego", "chair", "ficus", "hotdog", "bench"]
57
-
58
- for scene in all_scenes:
59
- if scene in args.scenes:
60
- final_scenes += [scene]
61
- # final_scenes += ["pulse", "intrinsics"]
62
-
63
- final_scenes = list(set(final_scenes))
64
- download_dataset(final_scenes)
65
-
66
-
67
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/misc/eval_utils.py DELETED
@@ -1,224 +0,0 @@
1
- import numpy as np
2
- import imageio
3
- import json
4
- import torch
5
- import sys
6
- import os
7
- import configargparse
8
- import ast
9
- sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
10
- from loaders.utils import Rays
11
- from utils import str2bool, load_args
12
-
13
- def calc_psnr(img1, img2):
14
- # Calculate the mean squared error
15
- mse = np.mean((img1 - img2) ** 2)
16
- # Calculate the maximum possible pixel value (for data scaled between 0 and 1)
17
- max_pixel = 1.0
18
- # Calculate the PSNR
19
- psnr_value = 20 * np.log10(max_pixel / np.sqrt(mse))
20
- return psnr_value
21
-
22
- def get_rays(img_shape, c2w, K, device):
23
- OPENGL_CAMERA = True
24
- x, y = torch.meshgrid(
25
- torch.arange(img_shape, device=device),
26
- torch.arange(img_shape, device=device),
27
- indexing="xy",
28
- )
29
- x = x.flatten()
30
- y = y.flatten()
31
-
32
- c2w = c2w.repeat(img_shape**2, 1, 1)
33
- camera_dirs = torch.nn.functional.pad(
34
- torch.stack(
35
- [
36
- (x - K[0, 2] + 0.5) / K[0, 0],
37
- (y - K[1, 2] + 0.5)
38
- / K[1, 1]
39
- * (-1.0 if OPENGL_CAMERA else 1.0),
40
- ],
41
- dim=-1,
42
- ),
43
- (0, 1),
44
- value=(-1.0 if OPENGL_CAMERA else 1.0),
45
- ) # [num_rays, 3]
46
-
47
- # [n_cams, height, width, 3]
48
- directions = (camera_dirs[:, None, :] * c2w[:, :3, :3]).sum(dim=-1)
49
- origins = torch.broadcast_to(c2w[:, :3, -1], directions.shape)
50
- viewdirs = directions / torch.linalg.norm(
51
- directions, dim=-1, keepdims=True
52
- )
53
- origins = torch.reshape(origins, (img_shape, img_shape, 3))
54
- viewdirs = torch.reshape(viewdirs, (img_shape, img_shape, 3))
55
-
56
-
57
- rays = Rays(origins=origins, viewdirs=viewdirs)
58
-
59
- return rays
60
-
61
-
62
- def read_json(json_path):
63
- f = open(json_path)
64
- positions = json.load(f)
65
- f.close()
66
- return positions
67
-
68
- def generate_video(images, output_path, fps):
69
- # Determine the width and height of the images
70
- writer = imageio.get_writer(output_path, fps=fps)
71
- for image in images:
72
- writer.append_data(image)
73
- writer.close()
74
-
75
- def calc_iou(rgb, gt_tran):
76
- intersection = np.minimum(rgb, gt_tran)
77
- union = np.maximum(rgb, gt_tran)
78
- iou = np.sum(intersection) / np.sum(union)
79
- return iou
80
-
81
- def load_eval_args():
82
- parser = configargparse.ArgumentParser()
83
- parser.add('-tc', '--test_config',
84
- is_config_file=True,
85
- default="./configs/test/captured/cinema_quantitative.ini",
86
- help='Path to config file.'
87
- )
88
- parser.add_argument(
89
- "--scene",
90
- type=str,
91
- default="cinema",
92
- # choices=[
93
- # # nerf transient
94
- # "lego",
95
- # "chair",
96
- # "drums",
97
- # "ficus",
98
- # "hotdog",
99
- # "bench",
100
- # "boar",
101
- # "benches"
102
- # ],
103
- help="scene to evaluate the models on",
104
- )
105
- parser.add_argument(
106
- "--rep_number",
107
- type=int,
108
- default=30,
109
- )
110
- parser.add_argument(
111
- "--step",
112
- type=int,
113
- default=290000,
114
- )
115
- parser.add_argument(
116
- "--split",
117
- type=str,
118
- default="test",
119
- )
120
- parser.add_argument(
121
- "--test_folder_path",
122
- type=str,
123
- default="test2",
124
- )
125
- parser.add_argument(
126
- "--checkpoint_dir",
127
- type=str,
128
- default="/scratch/ondemand28/anagh/tnerf_release/multiview_transient/results/cinema_two_views_04-18_02:10:32",
129
- )
130
- parser.add_argument(
131
- "--data_folder_path",
132
- type=str,
133
- default="./data",
134
- )
135
- parser.add_argument(
136
- "--irf_path",
137
- type=str,
138
- default="",
139
- help="Path to IRF file (.csv/.npy/.mat/.pt). If empty, fallback to --pulse_path.",
140
- )
141
- parser.add_argument(
142
- "--irf_column",
143
- type=str,
144
- default="irf",
145
- help="CSV column name for IRF values.",
146
- )
147
- parser.add_argument(
148
- "--irf_half_window",
149
- type=int,
150
- default=50,
151
- help="Half window around IRF peak. Set <=0 to disable cropping.",
152
- )
153
- parser.add_argument(
154
- "--no_irf_reverse",
155
- action="store_true",
156
- help="Disable reverse before Conv1d kernel creation.",
157
- )
158
- parser.add_argument(
159
- "--measurement_root",
160
- type=str,
161
- default="",
162
- help="Optional measurement root for captured-ours loader.",
163
- )
164
- parser.add_argument(
165
- "--data_exts",
166
- type=str,
167
- default=".npz,.txt,.pt,.h5,.hdf5",
168
- help="Comma-separated measurement extension lookup order.",
169
- )
170
- parser.add_argument(
171
- "--bin_width_s_loader",
172
- type=float,
173
- default=None,
174
- help="Optional bin width in seconds for shift resampling.",
175
- )
176
- parser.add_argument(
177
- "--img_height_test",
178
- type=int,
179
- default=None,
180
- help="Test image height. If empty, use --img_shape_test.",
181
- )
182
- parser.add_argument(
183
- "--img_width_test",
184
- type=int,
185
- default=None,
186
- help="Test image width. If empty, use --img_shape_test.",
187
- )
188
- parser.add_argument(
189
- "--invalid_mask_path",
190
- type=str,
191
- default="",
192
- help="Optional offset map path for valid-pixel mask.",
193
- )
194
- parser.add_argument(
195
- "--invalid_mask_invalid_gt",
196
- type=float,
197
- default=10.0,
198
- help="Offset threshold: pixels with offset > threshold are invalid.",
199
- )
200
- parser.add_argument(
201
- "--meas_peak_min",
202
- type=float,
203
- default=100.0,
204
- help=(
205
- "Minimum raw histogram peak per pixel to keep it in evaluation metrics. "
206
- "<=0 disables this mask."
207
- ),
208
- )
209
- parser.add_argument(
210
- "--scale_int",
211
- type=float,
212
- default=1.0,
213
- help="Fixed scale for intensity normalisation (replaces per-image dynamic max).",
214
- )
215
- args = load_args(eval=True, parser=parser)
216
- return args
217
-
218
- num2words = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
219
- 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
220
- 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen',
221
- 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen'}
222
-
223
- if __name__=="__main__":
224
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/misc/summary.py DELETED
@@ -1,147 +0,0 @@
1
- import imgviz
2
- import numpy as np
3
- from utils import render_transient
4
- import matplotlib.pyplot as plt
5
- import torchvision
6
- import torch
7
- import os
8
-
9
-
10
- def _atomic_torch_save(obj, path):
11
- folder = os.path.dirname(path) or "."
12
- os.makedirs(folder, exist_ok=True)
13
- tmp_path = os.path.join(folder, "." + os.path.basename(path) + ".tmp")
14
- torch.save(obj, tmp_path)
15
- os.replace(tmp_path, path)
16
-
17
-
18
- @torch.no_grad()
19
- def write_summary_histogram(radiance_field, occupancy_grid, writer, test_dataset, step, render_step_size, args):
20
- img_scale = args.img_scale
21
- radiance_field.eval()
22
- occupancy_grid.eval()
23
- rgb_images = []
24
- depth_images = []
25
- gt_imgs = []
26
- accs = []
27
-
28
- pixels_to_plot = args.pixels_to_plot
29
- plotting_transients = []
30
- plotting_transients_depth = []
31
-
32
- plotting_transients_gt = []
33
- mse_list = []
34
-
35
- test_list = list(range(len(test_dataset)))
36
- # if args.version == "simulated":
37
- # color_channels = 3
38
- # else:
39
- # color_channels = 1
40
- # n_output_dim = args.n_bins*(color_channels)
41
- with torch.no_grad():
42
-
43
- # sample transients from network
44
- for ind, i in enumerate(test_list):
45
- data = test_dataset[i]
46
- render_bkgd = data["color_bkgd"]
47
- rays = data["rays"]
48
- pixels = data["pixels"]
49
- pixels = pixels.reshape(rays.origins.shape[0], rays.origins.shape[1], -1, 3)
50
- valid_mask = data.get("valid_mask", None)
51
- if valid_mask is not None:
52
- valid_mask = valid_mask.to(torch.bool).cpu()
53
- if valid_mask.ndim == 1:
54
- valid_mask = valid_mask.reshape(rays.origins.shape[0], rays.origins.shape[1])
55
-
56
-
57
- # # rendering
58
- out = render_transient(
59
- radiance_field,
60
- occupancy_grid,
61
- rays,
62
- near_plane=args.near_plane,
63
- far_plane=args.far_plane,
64
- render_step_size=render_step_size,
65
- cone_angle=args.cone_angle,
66
- alpha_thre=args.alpha_thre,
67
- use_normals = False,
68
- args = args
69
- )
70
-
71
- rgb, acc, n_rendering_samples, comp_weights, depth = [out[key] for key in ['colors', 'opacities', 'n_rendering_samples', "comp_weights", "depths"]]
72
- del out
73
-
74
- rgb = rgb.reshape(rays.origins.shape[0], rays.origins.shape[1], -1, 3)
75
-
76
- _atomic_torch_save(rgb, os.path.join(args.outpath, f"test_{ind}_conv.pt"))
77
- _atomic_torch_save(depth, os.path.join(args.outpath, f"test_{ind}_depth.pt"))
78
-
79
- # if color_channels ==1:
80
- # gt_imgs.append(torch.clip(pixels.sum(-2).cpu().repeat(1, 1, 3).permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2))
81
- # rgb_images.append(torch.clip(rgb.sum(-2).cpu().repeat(1, 1, 3).permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2))
82
- # else:
83
- gt_img = torch.clip(pixels.sum(-2).cpu().permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2)
84
- rgb_img = torch.clip(rgb.sum(-2).cpu().permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2)
85
- if valid_mask is not None:
86
- valid3 = valid_mask[None, ...].expand_as(gt_img)
87
- gt_imgs.append(gt_img * valid3.to(gt_img.dtype))
88
- rgb_images.append(rgb_img * valid3.to(rgb_img.dtype))
89
- if valid3.any():
90
- mse_list.append(((gt_img - rgb_img) ** 2)[valid3].mean())
91
- else:
92
- mse_list.append(torch.tensor(float("nan")))
93
- else:
94
- gt_imgs.append(gt_img)
95
- rgb_images.append(rgb_img)
96
- mse_list.append(torch.mean((gt_img - rgb_img) ** 2))
97
- accs.append(acc.repeat(1, 1, 3).permute(2, 0, 1).cpu())
98
- dp = imgviz.depth2rgb(depth.cpu().squeeze().numpy(), colormap="inferno")
99
- depth_images.append(torch.from_numpy(dp).permute(2, 0, 1))
100
-
101
- if ind == 0:
102
- for pixel in pixels_to_plot:
103
- plotting_transients.append(rgb[pixel[0], pixel[1], :, 0])
104
- plotting_transients_gt.append(pixels[pixel[0], pixel[1], :, 0])
105
- plotting_transients_depth.append(depth[pixel[0], pixel[1]])
106
-
107
-
108
- images = torchvision.utils.make_grid(torch.stack(gt_imgs + rgb_images + depth_images + accs), nrow=len(test_list), normalize=False)
109
- mse = torch.stack(mse_list)
110
- valid_mse = torch.isfinite(mse)
111
- if valid_mse.any():
112
- psnr = -10.0 * torch.log10(torch.clamp(mse[valid_mse], min=1e-12))
113
- print(f"image psnr (masked): {psnr.mean():.2f}\n")
114
- writer.add_scalar("Metric/psnr_masked", psnr.mean().item(), step)
115
- else:
116
- print("image psnr (masked): nan (no valid pixels)\n")
117
- writer.add_image('rgbdn', images, step)
118
-
119
- figure = plt.figure(figsize=((len(pixels_to_plot)+1), 4), dpi=250)
120
-
121
- # plot the predicted intensity
122
- plt.subplot(2, (len(pixels_to_plot)+1)//2, 1)
123
- plt.imshow(gt_imgs[0].permute(1, 2, 0))
124
- for i, pixel in enumerate(pixels_to_plot):
125
- plt.plot(pixel[1], pixel[0], '.', markersize=10, color='red')
126
- plt.text(pixel[1], pixel[0], str(i), color="yellow", fontsize=10)
127
- plt.gca().set_aspect(1.0/plt.gca().get_data_ratio(), adjustable='box')
128
- plt.title('gt intensity')
129
-
130
- for i, pixel in enumerate(pixels_to_plot):
131
- # plot transients
132
- plt.subplot(2, (len(pixels_to_plot)+1)//2, i+2)
133
- plt.plot(np.arange(args.n_bins), plotting_transients[i].detach().cpu(), label='pred', linewidth=0.5)
134
- plt.plot(np.arange(args.n_bins), plotting_transients_gt[i].detach().cpu(), label='gt', linewidth=0.5)
135
- plt.axvline(x = (plotting_transients_depth[i]/args.exposure_time).detach().cpu().numpy(), color = 'y')
136
- plt.title(f"pixel {i}")
137
- plt.ylabel('intensity')
138
- plt.legend(borderpad=0, labelspacing=0)
139
- plt.gca().set_aspect(1.0 / plt.gca().get_data_ratio(), adjustable='box')
140
-
141
- plt.tight_layout()
142
- writer.add_figure("transient_plots", figure, step)
143
-
144
-
145
- radiance_field.train()
146
- occupancy_grid.train()
147
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/misc/transient_volrend.py DELETED
@@ -1,620 +0,0 @@
1
- from typing import Callable, Dict, Optional, Tuple
2
- import torch
3
- from torch import Tensor
4
- from nerfacc.pack import pack_info
5
- from nerfacc.scan import exclusive_prod, exclusive_sum
6
- from torch_scatter import scatter_max
7
- import math
8
-
9
-
10
- def rendering_transient_single_path(
11
- # ray marching results
12
- t_starts: Tensor,
13
- t_ends: Tensor,
14
- ray_indices: Optional[Tensor] = None,
15
- n_rays: Optional[int] = None,
16
- # radiance field
17
- rgb_sigma_fn: Optional[Callable] = None,
18
- # rendering options
19
- render_bkgd: Optional[Tensor] = None,
20
- args = None
21
- ):
22
-
23
- # Query sigma and color with gradients
24
- data = rgb_sigma_fn(t_starts, t_ends, ray_indices.long())
25
- rgbs, sigmas = data
26
- dists = (t_starts + t_ends)/2
27
-
28
- if args.exp:
29
- rgbs = torch.exp(rgbs)-1
30
-
31
-
32
- # Rendering: compute weights and ray indices.
33
- weights_non_squared, transmittance, alphas = render_weight_from_density(
34
- t_starts,
35
- t_ends,
36
- sigmas,
37
- ray_indices=ray_indices,
38
- n_rays=n_rays
39
- )
40
-
41
- # modelling squared transmittance
42
- # alphas = 1 - torch.exp(-sigmas * (t_ends - t_starts))
43
- weights = (weights_non_squared ** 2 / (alphas.squeeze() + 1e-9))
44
- # Some iterations can have no alive samples after occupancy sampling.
45
- # Return zero buffers directly to avoid downstream shape edge-cases.
46
- if t_starts.numel() == 0:
47
- device = weights.device
48
- dtype = weights.dtype
49
- colors = torch.zeros((n_rays, args.n_bins, 3), device=device, dtype=dtype)
50
- opacities = torch.zeros((n_rays, 1), device=device, dtype=dtype)
51
- depths = torch.zeros((n_rays, 1), device=device, dtype=dtype)
52
- depths_variance = torch.zeros((n_rays, 1), device=device, dtype=dtype)
53
- comp_weights = torch.zeros((n_rays, args.n_bins), device=device, dtype=dtype)
54
- return colors, opacities, depths, depths_variance, comp_weights, rgbs
55
- weights_non_squared = weights_non_squared.reshape(-1)
56
- weights = weights.reshape(-1)
57
- ray_indices = ray_indices.reshape(-1).long()
58
- t_starts = t_starts.reshape(-1)
59
- t_ends = t_ends.reshape(-1)
60
- dists = dists.reshape(-1)
61
- rgbs = rgbs.reshape(-1, rgbs.shape[-1])
62
-
63
- # Safety guard for occasional invalid indices from upstream CUDA kernels.
64
- valid = (ray_indices >= 0) & (ray_indices < int(n_rays))
65
- if not torch.all(valid):
66
- weights_non_squared = weights_non_squared[valid]
67
- weights = weights[valid]
68
- ray_indices = ray_indices[valid]
69
- t_starts = t_starts[valid]
70
- t_ends = t_ends[valid]
71
- dists = dists[valid]
72
- rgbs = rgbs[valid]
73
- if ray_indices.numel() == 0:
74
- device = weights.device
75
- dtype = weights.dtype
76
- colors = torch.zeros((n_rays, args.n_bins, 3), device=device, dtype=dtype)
77
- opacities = torch.zeros((n_rays, 1), device=device, dtype=dtype)
78
- depths = torch.zeros((n_rays, 1), device=device, dtype=dtype)
79
- depths_variance = torch.zeros((n_rays, 1), device=device, dtype=dtype)
80
- comp_weights = torch.zeros((n_rays, args.n_bins), device=device, dtype=dtype)
81
- return colors, opacities, depths, depths_variance, comp_weights, rgbs
82
-
83
- # r**2 fall off
84
- src = weights[:, None] * rgbs
85
- src = src/(dists[:, None].detach()**2 + 1e-10)
86
-
87
- if args.version == "simulated":
88
- # this code bins the output samples into a tensor of size [n_rays, n_bins, 3]
89
- tfilter_sigma = args.tfilter_sigma
90
- bin_mapping, dist_weights = mapping_dist_to_bin_mitsuba(dists, args.n_bins, args.exposure_time, c=1, sigma=tfilter_sigma)
91
- src = (dist_weights[..., None] * src[:, None, :]).flatten(0, 1)
92
- colors = torch.zeros((n_rays * args.n_bins, 3), device=weights.device)
93
- index = ((torch.repeat_interleave(ray_indices, 8*tfilter_sigma) * args.n_bins) + bin_mapping.flatten().long())[:, None].expand(-1, 3).long()
94
- colors.scatter_add_(0, index, src)
95
- colors = colors.view(n_rays, args.n_bins, 3)
96
- bin_numbers_floor, bin_numbers_ceil, alpha = mapping_dist_to_bin(dists, args.n_bins, args.exposure_time)
97
- index_f = ((ray_indices * args.n_bins) + bin_numbers_floor.long())[:, None].expand(-1, 3).long()
98
- index = index_f
99
-
100
-
101
- if args.version == "captured":
102
- bin_numbers_floor, bin_numbers_ceil, _ = mapping_dist_to_bin(dists, args.n_bins, args.exposure_time)
103
- colors = torch.zeros((n_rays * args.n_bins, 3), device=weights.device)
104
- index = ((ray_indices * args.n_bins) + bin_numbers_floor.long())[:, None].expand(-1, 3).long()
105
- colors.scatter_add_(0, index, src)
106
- colors = colors.view(n_rays, args.n_bins, 3)
107
- colors = convolve_colour(colors, args.laser_kernel, n_bins=args.n_bins)
108
-
109
-
110
-
111
- # do the same for the sigmas
112
- comp_weights = torch.zeros((n_rays * args.n_bins, 1), device=weights.device)
113
- comp_weights.scatter_add_(0, index[:, [0]], weights_non_squared[:, None])
114
- comp_weights = comp_weights.reshape(n_rays, args.n_bins)
115
-
116
-
117
- opacities = accumulate_along_rays(
118
- weights, values=None, ray_indices=ray_indices, n_rays=n_rays
119
- )
120
-
121
-
122
- out, argmax = scatter_max(weights_non_squared, ray_indices, out=torch.zeros(n_rays, device=ray_indices.device))
123
-
124
- if t_starts.shape[0]!=0:
125
- argmax[argmax==weights.shape[0]] = weights.shape[0]-1
126
- depths = (t_starts+t_ends)[argmax]/2
127
- else:
128
- depths = out[:, None]
129
-
130
- to_accum_var = ((t_ends + t_starts) / 2 - depths.reshape(-1)[ray_indices]) ** 2
131
- depths_variance = accumulate_along_rays(
132
- weights_non_squared.reshape(-1),
133
- ray_indices=ray_indices,
134
- values=to_accum_var.reshape(-1, 1),
135
- n_rays=n_rays,
136
- )
137
- depths_variance = depths_variance/(opacities+1e-10)
138
-
139
-
140
- return colors, opacities, depths, depths_variance, comp_weights, rgbs
141
-
142
-
143
- def mapping_dist_to_bin_mitsuba(dists, n_bins, exposure_time, c=1, sigma=5):
144
- times = 2 * dists / c
145
- ratio = times / exposure_time
146
- ranges = torch.arange(0, 8 * sigma, device=dists.device)[None, :].repeat(ratio.shape[0], 1)
147
- bin_mapping = (torch.ceil(ratio-4*sigma))[:, None]+ranges
148
- ranges = bin_mapping - ratio[:, None]
149
- dist_weights = torch.exp(-ranges**2/(2*sigma**2))-math.exp(-8)
150
-
151
- dist_weights[(bin_mapping<0) ] = 0
152
- dist_weights[(bin_mapping>n_bins) ] = 0
153
-
154
- bin_mapping = torch.clip(bin_mapping, 0, n_bins-1)
155
- dist_weights = (dist_weights.T/(dist_weights.sum(-1)[: None]+1e-10)).T
156
- return bin_mapping, dist_weights
157
-
158
-
159
- def mapping_dist_to_bin(dists, n_bins, exposure_time, c=1):
160
- times = 2 * dists / c
161
- # (torch.randn(times.shape[0])*7).to("cuda")
162
- ratio = times / exposure_time
163
- alpha = (torch.ceil(ratio) - ratio) / (torch.ceil(ratio) - torch.floor(ratio) + 1e-10)
164
-
165
- bin_numbers_floor = torch.floor(ratio)
166
- bin_numbers_ceil = torch.ceil(ratio)
167
- # if torch.max(bin_numbers)>bin_length:
168
- # print("hello")
169
- bin_numbers_floor = torch.clip(bin_numbers_floor, 0, n_bins - 1)
170
- bin_numbers_ceil = torch.clip(bin_numbers_ceil, 0, n_bins - 1)
171
-
172
- return bin_numbers_floor, bin_numbers_ceil, alpha
173
-
174
-
175
- def render_transmittance_from_alpha(
176
- alphas: Tensor,
177
- packed_info: Optional[Tensor] = None,
178
- ray_indices: Optional[Tensor] = None,
179
- n_rays: Optional[int] = None,
180
- prefix_trans: Optional[Tensor] = None,
181
- ) -> Tensor:
182
- """Compute transmittance :math:`T_i` from alpha :math:`\\alpha_i`.
183
-
184
- .. math::
185
- T_i = \\prod_{j=1}^{i-1}(1-\\alpha_j)
186
-
187
- This function supports both batched and flattened input tensor. For flattened input tensor, either
188
- (`packed_info`) or (`ray_indices` and `n_rays`) should be provided.
189
-
190
- Args:
191
- alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
192
- packed_info: A tensor of shape (n_rays, 2) that specifies the start and count
193
- of each chunk in the flattened samples, with in total n_rays chunks.
194
- Useful for flattened input.
195
- ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples).
196
- n_rays: Number of rays. Only useful when `ray_indices` is provided.
197
- prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,).
198
-
199
- Returns:
200
- The rendering transmittance with the same shape as `alphas`.
201
-
202
- Examples:
203
-
204
- .. code-block:: python
205
-
206
- >>> alphas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda")
207
- >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda")
208
- >>> transmittance = render_transmittance_from_alpha(alphas, ray_indices=ray_indices)
209
- tensor([1.0, 0.6, 0.12, 1.0, 0.2, 1.0, 1.0])
210
- """
211
- if ray_indices is not None and packed_info is None:
212
- packed_info = pack_info(ray_indices, n_rays)
213
-
214
- trans = exclusive_prod(1 - alphas, packed_info)
215
- if prefix_trans is not None:
216
- trans *= prefix_trans
217
- return trans
218
-
219
- def convolve_colour(color, kernel, n_bins):
220
- color = color.transpose(1, 2).reshape(-1, n_bins)
221
- color = kernel(color[:, None, :]).squeeze()
222
- color = color.reshape(-1, 3, n_bins).transpose(1, 2)
223
- return color
224
-
225
- def torch_laser_kernel(laser, device='cuda'):
226
- m = torch.nn.Conv1d(1, 1, laser.shape[0], padding=(laser.shape[0] - 1) // 2, padding_mode="zeros", device=device)
227
- m.weight.requires_grad = False
228
- m.bias.requires_grad = False
229
- m.bias *= 0
230
- m.weight = torch.nn.Parameter(laser[None, None, ...])
231
- return m
232
-
233
- def render_transmittance_from_density(
234
- t_starts: Tensor,
235
- t_ends: Tensor,
236
- sigmas: Tensor,
237
- packed_info: Optional[Tensor] = None,
238
- ray_indices: Optional[Tensor] = None,
239
- n_rays: Optional[int] = None,
240
- prefix_trans: Optional[Tensor] = None,
241
- ) -> Tuple[Tensor, Tensor]:
242
- """Compute transmittance :math:`T_i` from density :math:`\\sigma_i`.
243
-
244
- .. math::
245
- T_i = exp(-\\sum_{j=1}^{i-1}\\sigma_j\delta_j)
246
-
247
- This function supports both batched and flattened input tensor. For flattened input tensor, either
248
- (`packed_info`) or (`ray_indices` and `n_rays`) should be provided.
249
-
250
- Args:
251
- t_starts: Where the frustum-shape sample starts along a ray. Tensor with \
252
- shape (all_samples,) or (n_rays, n_samples).
253
- t_ends: Where the frustum-shape sample ends along a ray. Tensor with \
254
- shape (all_samples,) or (n_rays, n_samples).
255
- sigmas: The density values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
256
- packed_info: A tensor of shape (n_rays, 2) that specifies the start and count
257
- of each chunk in the flattened samples, with in total n_rays chunks.
258
- Useful for flattened input.
259
- ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples).
260
- n_rays: Number of rays. Only useful when `ray_indices` is provided.
261
- prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,).
262
-
263
- Returns:
264
- The rendering transmittance and opacities, both with the same shape as `sigmas`.
265
-
266
- Examples:
267
-
268
- .. code-block:: python
269
-
270
- >>> t_starts = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], device="cuda")
271
- >>> t_ends = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], device="cuda")
272
- >>> sigmas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda")
273
- >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda")
274
- >>> transmittance, alphas = render_transmittance_from_density(
275
- >>> t_starts, t_ends, sigmas, ray_indices=ray_indices)
276
- transmittance: [1.00, 0.67, 0.30, 1.00, 0.45, 1.00, 1.00]
277
- alphas: [0.33, 0.55, 0.095, 0.55, 0.095, 0.00, 0.59]
278
-
279
- """
280
- if ray_indices is not None and packed_info is None:
281
- packed_info = pack_info(ray_indices, n_rays)
282
-
283
- sigmas_dt = sigmas * (t_ends - t_starts)
284
- alphas = 1.0 - torch.exp(-sigmas_dt)
285
- trans = torch.exp(-exclusive_sum(sigmas_dt, packed_info))
286
- if prefix_trans is not None:
287
- trans *= prefix_trans
288
- return trans, alphas
289
-
290
-
291
- def render_weight_from_alpha(
292
- alphas: Tensor,
293
- packed_info: Optional[Tensor] = None,
294
- ray_indices: Optional[Tensor] = None,
295
- n_rays: Optional[int] = None,
296
- prefix_trans: Optional[Tensor] = None,
297
- ) -> Tuple[Tensor, Tensor]:
298
- """Compute rendering weights :math:`w_i` from opacity :math:`\\alpha_i`.
299
-
300
- .. math::
301
- w_i = T_i\\alpha_i, \\quad\\textrm{where}\\quad T_i = \\prod_{j=1}^{i-1}(1-\\alpha_j)
302
-
303
- This function supports both batched and flattened input tensor. For flattened input tensor, either
304
- (`packed_info`) or (`ray_indices` and `n_rays`) should be provided.
305
-
306
- Args:
307
- alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
308
- packed_info: A tensor of shape (n_rays, 2) that specifies the start and count
309
- of each chunk in the flattened samples, with in total n_rays chunks.
310
- Useful for flattened input.
311
- ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples).
312
- n_rays: Number of rays. Only useful when `ray_indices` is provided.
313
- prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,).
314
-
315
- Returns:
316
- The rendering weights and transmittance, both with the same shape as `alphas`.
317
-
318
- Examples:
319
-
320
- .. code-block:: python
321
-
322
- >>> alphas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda")
323
- >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda")
324
- >>> weights, transmittance = render_weight_from_alpha(alphas, ray_indices=ray_indices)
325
- weights: [0.4, 0.48, 0.012, 0.8, 0.02, 0.0, 0.9])
326
- transmittance: [1.00, 0.60, 0.12, 1.00, 0.20, 1.00, 1.00]
327
-
328
- """
329
- trans = render_transmittance_from_alpha(
330
- alphas, packed_info, ray_indices, n_rays, prefix_trans
331
- )
332
- weights = trans * alphas
333
- return weights, trans
334
-
335
-
336
- def render_weight_from_density(
337
- t_starts: Tensor,
338
- t_ends: Tensor,
339
- sigmas: Tensor,
340
- packed_info: Optional[Tensor] = None,
341
- ray_indices: Optional[Tensor] = None,
342
- n_rays: Optional[int] = None,
343
- prefix_trans: Optional[Tensor] = None,
344
- ) -> Tuple[Tensor, Tensor, Tensor]:
345
- """Compute rendering weights :math:`w_i` from density :math:`\\sigma_i` and interval :math:`\\delta_i`.
346
-
347
- .. math::
348
- w_i = T_i(1 - exp(-\\sigma_i\delta_i)), \\quad\\textrm{where}\\quad T_i = exp(-\\sum_{j=1}^{i-1}\\sigma_j\delta_j)
349
-
350
- This function supports both batched and flattened input tensor. For flattened input tensor, either
351
- (`packed_info`) or (`ray_indices` and `n_rays`) should be provided.
352
-
353
- Args:
354
- t_starts: The start time of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
355
- t_ends: The end time of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
356
- sigmas: The density values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
357
- packed_info: A tensor of shape (n_rays, 2) that specifies the start and count
358
- of each chunk in the flattened samples, with in total n_rays chunks.
359
- Useful for flattened input.
360
- ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples).
361
- n_rays: Number of rays. Only useful when `ray_indices` is provided.
362
- prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,).
363
-
364
- Returns:
365
- The rendering weights, transmittance and opacities, both with the same shape as `sigmas`.
366
-
367
- Examples:
368
-
369
- .. code-block:: python
370
-
371
- >>> t_starts = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], device="cuda")
372
- >>> t_ends = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], device="cuda")
373
- >>> sigmas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda")
374
- >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda")
375
- >>> weights, transmittance, alphas = render_weight_from_density(
376
- >>> t_starts, t_ends, sigmas, ray_indices=ray_indices)
377
- weights: [0.33, 0.37, 0.03, 0.55, 0.04, 0.00, 0.59]
378
- transmittance: [1.00, 0.67, 0.30, 1.00, 0.45, 1.00, 1.00]
379
- alphas: [0.33, 0.55, 0.095, 0.55, 0.095, 0.00, 0.59]
380
-
381
- """
382
- trans, alphas = render_transmittance_from_density(
383
- t_starts, t_ends, sigmas, packed_info, ray_indices, n_rays, prefix_trans
384
- )
385
- weights = trans * alphas
386
- return weights, trans, alphas
387
-
388
-
389
- @torch.no_grad()
390
- def render_visibility_from_alpha(
391
- alphas: Tensor,
392
- packed_info: Optional[Tensor] = None,
393
- ray_indices: Optional[Tensor] = None,
394
- n_rays: Optional[int] = None,
395
- early_stop_eps: float = 1e-4,
396
- alpha_thre: float = 0.0,
397
- prefix_trans: Optional[Tensor] = None,
398
- ) -> Tensor:
399
- """Compute visibility from opacity :math:`\\alpha_i`.
400
-
401
- In this function, we first compute the transmittance from the sample opacity. The
402
- transmittance is then used to filter out occluded samples. And opacity is used to
403
- filter out transparent samples. The function returns a boolean tensor indicating
404
- which samples are visible (`transmittance > early_stop_eps` and `opacity > alpha_thre`).
405
-
406
- This function supports both batched and flattened input tensor. For flattened input tensor, either
407
- (`packed_info`) or (`ray_indices` and `n_rays`) should be provided.
408
-
409
- Args:
410
- alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
411
- packed_info: A tensor of shape (n_rays, 2) that specifies the start and count
412
- of each chunk in the flattened samples, with in total n_rays chunks.
413
- Useful for flattened input.
414
- ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples).
415
- n_rays: Number of rays. Only useful when `ray_indices` is provided.
416
- early_stop_eps: The early stopping threshold on transmittance.
417
- alpha_thre: The threshold on opacity.
418
- prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,).
419
-
420
- Returns:
421
- A boolean tensor indicating which samples are visible. Same shape as `alphas`.
422
-
423
- Examples:
424
-
425
- .. code-block:: python
426
-
427
- >>> alphas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda")
428
- >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda")
429
- >>> transmittance = render_transmittance_from_alpha(alphas, ray_indices=ray_indices)
430
- tensor([1.0, 0.6, 0.12, 1.0, 0.2, 1.0, 1.0])
431
- >>> visibility = render_visibility_from_alpha(
432
- >>> alphas, ray_indices=ray_indices, early_stop_eps=0.3, alpha_thre=0.2)
433
- tensor([True, True, False, True, False, False, True])
434
-
435
- """
436
- trans = render_transmittance_from_alpha(
437
- alphas, packed_info, ray_indices, n_rays, prefix_trans
438
- )
439
- vis = trans >= early_stop_eps
440
- if alpha_thre > 0:
441
- vis = vis & (alphas >= alpha_thre)
442
- return vis
443
-
444
-
445
- @torch.no_grad()
446
- def render_visibility_from_density(
447
- t_starts: Tensor,
448
- t_ends: Tensor,
449
- sigmas: Tensor,
450
- packed_info: Optional[Tensor] = None,
451
- ray_indices: Optional[Tensor] = None,
452
- n_rays: Optional[int] = None,
453
- early_stop_eps: float = 1e-4,
454
- alpha_thre: float = 0.0,
455
- prefix_trans: Optional[Tensor] = None,
456
- ) -> Tensor:
457
- """Compute visibility from density :math:`\\sigma_i` and interval :math:`\\delta_i`.
458
-
459
- In this function, we first compute the transmittance and opacity from the sample density. The
460
- transmittance is then used to filter out occluded samples. And opacity is used to
461
- filter out transparent samples. The function returns a boolean tensor indicating
462
- which samples are visible (`transmittance > early_stop_eps` and `opacity > alpha_thre`).
463
-
464
- This function supports both batched and flattened input tensor. For flattened input tensor, either
465
- (`packed_info`) or (`ray_indices` and `n_rays`) should be provided.
466
-
467
- Args:
468
- alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
469
- packed_info: A tensor of shape (n_rays, 2) that specifies the start and count
470
- of each chunk in the flattened samples, with in total n_rays chunks.
471
- Useful for flattened input.
472
- ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples).
473
- n_rays: Number of rays. Only useful when `ray_indices` is provided.
474
- early_stop_eps: The early stopping threshold on transmittance.
475
- alpha_thre: The threshold on opacity.
476
- prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,).
477
-
478
- Returns:
479
- A boolean tensor indicating which samples are visible. Same shape as `alphas`.
480
-
481
- Examples:
482
-
483
- .. code-block:: python
484
-
485
- >>> t_starts = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], device="cuda")
486
- >>> t_ends = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], device="cuda")
487
- >>> sigmas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda")
488
- >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda")
489
- >>> transmittance, alphas = render_transmittance_from_density(
490
- >>> t_starts, t_ends, sigmas, ray_indices=ray_indices)
491
- transmittance: [1.00, 0.67, 0.30, 1.00, 0.45, 1.00, 1.00]
492
- alphas: [0.33, 0.55, 0.095, 0.55, 0.095, 0.00, 0.59]
493
- >>> visibility = render_visibility_from_density(
494
- >>> t_starts, t_ends, sigmas, ray_indices=ray_indices, early_stop_eps=0.3, alpha_thre=0.2)
495
- tensor([True, True, False, True, False, False, True])
496
-
497
- """
498
- trans, alphas = render_transmittance_from_density(
499
- t_starts, t_ends, sigmas, packed_info, ray_indices, n_rays, prefix_trans
500
- )
501
- vis = trans >= early_stop_eps
502
- if alpha_thre > 0:
503
- vis = vis & (alphas >= alpha_thre)
504
- return vis
505
-
506
-
507
- def accumulate_along_rays(
508
- weights: Tensor,
509
- values: Optional[Tensor] = None,
510
- ray_indices: Optional[Tensor] = None,
511
- n_rays: Optional[int] = None,
512
- ) -> Tensor:
513
- """Accumulate volumetric values along the ray.
514
-
515
- This function supports both batched inputs and flattened inputs with
516
- `ray_indices` and `n_rays` provided.
517
-
518
- Note:
519
- This function is differentiable to `weights` and `values`.
520
-
521
- Args:
522
- weights: Weights to be accumulated. If `ray_indices` not provided,
523
- `weights` must be batched with shape (n_rays, n_samples). Else it
524
- must be flattened with shape (all_samples,).
525
- values: Values to be accumulated. If `ray_indices` not provided,
526
- `values` must be batched with shape (n_rays, n_samples, D). Else it
527
- must be flattened with shape (all_samples, D). None means
528
- we accumulate weights along rays. Default: None.
529
- ray_indices: Ray indices of the samples with shape (all_samples,).
530
- If provided, `weights` must be a flattened tensor with shape (all_samples,)
531
- and values (if not None) must be a flattened tensor with shape (all_samples, D).
532
- Default: None.
533
- n_rays: Number of rays. Should be provided together with `ray_indices`. Default: None.
534
-
535
- Returns:
536
- Accumulated values with shape (n_rays, D). If `values` is not given we return
537
- the accumulated weights, in which case D == 1.
538
-
539
- Examples:
540
-
541
- .. code-block:: python
542
-
543
- # Rendering: accumulate rgbs, opacities, and depths along the rays.
544
- colors = accumulate_along_rays(weights, rgbs, ray_indices, n_rays)
545
- opacities = accumulate_along_rays(weights, None, ray_indices, n_rays)
546
- depths = accumulate_along_rays(
547
- weights,
548
- (t_starts + t_ends)[:, None] / 2.0,
549
- ray_indices,
550
- n_rays,
551
- )
552
- # (n_rays, 3), (n_rays, 1), (n_rays, 1)
553
- print(colors.shape, opacities.shape, depths.shape)
554
-
555
- """
556
- if values is None:
557
- src = weights[..., None]
558
- else:
559
- assert values.dim() == weights.dim() + 1
560
- assert weights.shape == values.shape[:-1]
561
- src = weights[..., None] * values
562
- if ray_indices is not None:
563
- assert n_rays is not None, "n_rays must be provided"
564
- assert weights.dim() == 1, "weights must be flattened"
565
- outputs = torch.zeros(
566
- (n_rays, src.shape[-1]), device=src.device, dtype=src.dtype
567
- )
568
- outputs.index_add_(0, ray_indices, src)
569
- else:
570
- outputs = torch.sum(src, dim=-2)
571
- return outputs
572
-
573
-
574
- def accumulate_along_rays_(
575
- weights: Tensor,
576
- values: Optional[Tensor] = None,
577
- ray_indices: Optional[Tensor] = None,
578
- outputs: Optional[Tensor] = None,
579
- ) -> None:
580
- """Accumulate volumetric values along the ray.
581
-
582
- Inplace version of :func:`accumulate_along_rays`.
583
- """
584
- if weights.shape[0] == 0:
585
- return 0
586
- if values is None:
587
- src = weights[..., None]
588
- else:
589
- assert values.dim() == weights.dim() + 1
590
- assert weights.shape == values.shape[:-1]
591
- src = weights[..., None] * values
592
- if ray_indices is not None:
593
- # assert weights.dim() == 1, "weights must be flattened"
594
- # assert (
595
- # outputs.dim() == 2 and outputs.shape[-1] == src.shape[-1]
596
- # ), "outputs must be of shape (n_rays, D)"
597
- outputs.index_add_(0, ray_indices, src)
598
- else:
599
- outputs.add_(src.sum(dim=-2))
600
-
601
-
602
- def shift_transient_grid_sample_3d(transient, depth, exposure_time, n_bins):
603
- x_dim = transient.shape[0]
604
- bins_move = depth/exposure_time
605
- if x_dim%2 == 0:
606
- x = (torch.arange(x_dim, device=transient.device)-x_dim//2+0.5)/(x_dim//2-0.5)
607
- else:
608
- x = (torch.arange(x_dim, device=transient.device)-x_dim//2)/(x_dim//2)
609
-
610
- if x_dim == 1:
611
- x = torch.zeros_like(x)
612
-
613
- z = torch.arange(n_bins, device=transient.device).float()
614
- X, Z = torch.meshgrid(x, z, indexing="ij")
615
- Z = Z - bins_move
616
- Z[Z<0] = n_bins+1
617
- Z = (Z-n_bins//2+0.5)/(n_bins//2-0.5)
618
- grid = torch.stack((Z, X), dim=-1)[None, ...]
619
- shifted_transient = torch.nn.functional.grid_sample(transient.permute(2, 0, 1)[None], grid, align_corners=True).squeeze(0).permute(1, 2, 0)
620
- return shifted_transient
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/radiance_fields/__init__.py DELETED
File without changes
codes/reconstruction/transientnerf/radiance_fields/mlp.py DELETED
@@ -1,395 +0,0 @@
1
- """
2
- Copyright (c) 2022 Ruilong Li, UC Berkeley.
3
- """
4
-
5
- import functools
6
- import math
7
- from typing import Callable, Optional
8
-
9
- import torch
10
- import torch.nn as nn
11
- import torch.nn.functional as F
12
-
13
-
14
- class MLP(nn.Module):
15
- def __init__(
16
- self,
17
- input_dim: int, # The number of input tensor channels.
18
- output_dim: int = None, # The number of output tensor channels.
19
- net_depth: int = 8, # The depth of the MLP.
20
- net_width: int = 256, # The width of the MLP.
21
- skip_layer: int = 4, # The layer to add skip layers to.
22
- hidden_init: Callable = nn.init.xavier_uniform_,
23
- hidden_activation: Callable = nn.ReLU(),
24
- output_enabled: bool = True,
25
- output_init: Optional[Callable] = nn.init.xavier_uniform_,
26
- output_activation: Optional[Callable] = nn.Identity(),
27
- bias_enabled: bool = True,
28
- bias_init: Callable = nn.init.zeros_,
29
- ):
30
- super().__init__()
31
- self.input_dim = input_dim
32
- self.output_dim = output_dim
33
- self.net_depth = net_depth
34
- self.net_width = net_width
35
- self.skip_layer = skip_layer
36
- self.hidden_init = hidden_init
37
- self.hidden_activation = hidden_activation
38
- self.output_enabled = output_enabled
39
- self.output_init = output_init
40
- self.output_activation = output_activation
41
- self.bias_enabled = bias_enabled
42
- self.bias_init = bias_init
43
-
44
- self.hidden_layers = nn.ModuleList()
45
- in_features = self.input_dim
46
- for i in range(self.net_depth):
47
- self.hidden_layers.append(
48
- nn.Linear(in_features, self.net_width, bias=bias_enabled)
49
- )
50
- if (
51
- (self.skip_layer is not None)
52
- and (i % self.skip_layer == 0)
53
- and (i > 0)
54
- ):
55
- in_features = self.net_width + self.input_dim
56
- else:
57
- in_features = self.net_width
58
- if self.output_enabled:
59
- self.output_layer = nn.Linear(
60
- in_features, self.output_dim, bias=bias_enabled
61
- )
62
- else:
63
- self.output_dim = in_features
64
-
65
- self.initialize()
66
-
67
- def initialize(self):
68
- def init_func_hidden(m):
69
- if isinstance(m, nn.Linear):
70
- if self.hidden_init is not None:
71
- self.hidden_init(m.weight)
72
- if self.bias_enabled and self.bias_init is not None:
73
- self.bias_init(m.bias)
74
-
75
- self.hidden_layers.apply(init_func_hidden)
76
- if self.output_enabled:
77
-
78
- def init_func_output(m):
79
- if isinstance(m, nn.Linear):
80
- if self.output_init is not None:
81
- self.output_init(m.weight)
82
- if self.bias_enabled and self.bias_init is not None:
83
- self.bias_init(m.bias)
84
-
85
- self.output_layer.apply(init_func_output)
86
-
87
- def forward(self, x):
88
- inputs = x
89
- for i in range(self.net_depth):
90
- x = self.hidden_layers[i](x)
91
- x = self.hidden_activation(x)
92
- if (
93
- (self.skip_layer is not None)
94
- and (i % self.skip_layer == 0)
95
- and (i > 0)
96
- ):
97
- x = torch.cat([x, inputs], dim=-1)
98
- if self.output_enabled:
99
- x = self.output_layer(x)
100
- x = self.output_activation(x)
101
- return x
102
-
103
-
104
- class DenseLayer(MLP):
105
- def __init__(self, input_dim, output_dim, **kwargs):
106
- super().__init__(
107
- input_dim=input_dim,
108
- output_dim=output_dim,
109
- net_depth=0, # no hidden layers
110
- **kwargs,
111
- )
112
-
113
-
114
- class NerfMLP(nn.Module):
115
- def __init__(
116
- self,
117
- input_dim: int, # The number of input tensor channels.
118
- condition_dim: int, # The number of condition tensor channels.
119
- net_depth: int = 8, # The depth of the MLP.
120
- net_width: int = 256, # The width of the MLP.
121
- skip_layer: int = 4, # The layer to add skip layers to.
122
- net_depth_condition: int = 1, # The depth of the second part of MLP.
123
- net_width_condition: int = 128, # The width of the second part of MLP.
124
- ):
125
- super().__init__()
126
- self.base = MLP(
127
- input_dim=input_dim,
128
- net_depth=net_depth,
129
- net_width=net_width,
130
- skip_layer=skip_layer,
131
- output_enabled=False,
132
- )
133
- hidden_features = self.base.output_dim
134
- self.sigma_layer = DenseLayer(hidden_features, 1)
135
-
136
- if condition_dim > 0:
137
- self.bottleneck_layer = DenseLayer(hidden_features, net_width)
138
- self.rgb_layer = MLP(
139
- input_dim=net_width + condition_dim,
140
- output_dim=3,
141
- net_depth=net_depth_condition,
142
- net_width=net_width_condition,
143
- skip_layer=None,
144
- )
145
- else:
146
- self.rgb_layer = DenseLayer(hidden_features, 3)
147
-
148
- def query_density(self, x):
149
- x = self.base(x)
150
- raw_sigma = self.sigma_layer(x)
151
- return raw_sigma
152
-
153
- def forward(self, x, condition=None):
154
- x = self.base(x)
155
- raw_sigma = self.sigma_layer(x)
156
- if condition is not None:
157
- if condition.shape[:-1] != x.shape[:-1]:
158
- num_rays, n_dim = condition.shape
159
- condition = condition.view(
160
- [num_rays] + [1] * (x.dim() - condition.dim()) + [n_dim]
161
- ).expand(list(x.shape[:-1]) + [n_dim])
162
- bottleneck = self.bottleneck_layer(x)
163
- x = torch.cat([bottleneck, condition], dim=-1)
164
- raw_rgb = self.rgb_layer(x)
165
- return raw_rgb, raw_sigma
166
-
167
-
168
- class SinusoidalEncoder(nn.Module):
169
- """Sinusoidal Positional Encoder used in Nerf."""
170
-
171
- def __init__(self, x_dim, min_deg, max_deg, use_identity: bool = True):
172
- super().__init__()
173
- self.x_dim = x_dim
174
- self.min_deg = min_deg
175
- self.max_deg = max_deg
176
- self.use_identity = use_identity
177
- self.register_buffer(
178
- "scales", torch.tensor([2**i for i in range(min_deg, max_deg)])
179
- )
180
-
181
- @property
182
- def latent_dim(self) -> int:
183
- return (
184
- int(self.use_identity) + (self.max_deg - self.min_deg) * 2
185
- ) * self.x_dim
186
-
187
- def forward(self, x: torch.Tensor) -> torch.Tensor:
188
- """
189
- Args:
190
- x: [..., x_dim]
191
- Returns:
192
- latent: [..., latent_dim]
193
- """
194
- if self.max_deg == self.min_deg:
195
- return x
196
- xb = torch.reshape(
197
- (x[Ellipsis, None, :] * self.scales[:, None]),
198
- list(x.shape[:-1]) + [(self.max_deg - self.min_deg) * self.x_dim],
199
- )
200
- latent = torch.sin(torch.cat([xb, xb + 0.5 * math.pi], dim=-1))
201
- if self.use_identity:
202
- latent = torch.cat([x] + [latent], dim=-1)
203
- return latent
204
-
205
-
206
- class VanillaNeRFRadianceField(nn.Module):
207
- def __init__(
208
- self,
209
- net_depth: int = 8, # The depth of the MLP.
210
- net_width: int = 256, # The width of the MLP.
211
- skip_layer: int = 4, # The layer to add skip layers to.
212
- net_depth_condition: int = 1, # The depth of the second part of MLP.
213
- net_width_condition: int = 128, # The width of the second part of MLP.
214
- ) -> None:
215
- super().__init__()
216
- self.posi_encoder = SinusoidalEncoder(3, 0, 10, True)
217
- self.view_encoder = SinusoidalEncoder(3, 0, 4, True)
218
- self.mlp = NerfMLP(
219
- input_dim=self.posi_encoder.latent_dim,
220
- condition_dim=self.view_encoder.latent_dim,
221
- net_depth=net_depth,
222
- net_width=net_width,
223
- skip_layer=skip_layer,
224
- net_depth_condition=net_depth_condition,
225
- net_width_condition=net_width_condition,
226
- )
227
-
228
- def query_opacity(self, x, step_size):
229
- density = self.query_density(x)
230
- # if the density is small enough those two are the same.
231
- # opacity = 1.0 - torch.exp(-density * step_size)
232
- opacity = density * step_size
233
- return opacity
234
-
235
- def query_density(self, x):
236
- x = self.posi_encoder(x)
237
- sigma = self.mlp.query_density(x)
238
- return F.relu(sigma)
239
-
240
- def forward(self, x, condition=None):
241
- x = self.posi_encoder(x)
242
- if condition is not None:
243
- condition = self.view_encoder(condition)
244
- rgb, sigma = self.mlp(x, condition=condition)
245
- return torch.sigmoid(rgb), F.relu(sigma)
246
-
247
-
248
- class TNeRFRadianceField(nn.Module):
249
- def __init__(self) -> None:
250
- super().__init__()
251
- self.posi_encoder = SinusoidalEncoder(3, 0, 4, True)
252
- self.time_encoder = SinusoidalEncoder(1, 0, 4, True)
253
- self.warp = MLP(
254
- input_dim=self.posi_encoder.latent_dim
255
- + self.time_encoder.latent_dim,
256
- output_dim=3,
257
- net_depth=4,
258
- net_width=64,
259
- skip_layer=2,
260
- output_init=functools.partial(torch.nn.init.uniform_, b=1e-4),
261
- )
262
- self.nerf = VanillaNeRFRadianceField()
263
-
264
- def query_opacity(self, x, timestamps, step_size):
265
- idxs = torch.randint(0, len(timestamps), (x.shape[0],), device=x.device)
266
- t = timestamps[idxs]
267
- density = self.query_density(x, t)
268
- # if the density is small enough those two are the same.
269
- # opacity = 1.0 - torch.exp(-density * step_size)
270
- opacity = density * step_size
271
- return opacity
272
-
273
- def query_density(self, x, t):
274
- x = x + self.warp(
275
- torch.cat([self.posi_encoder(x), self.time_encoder(t)], dim=-1)
276
- )
277
- return self.nerf.query_density(x)
278
-
279
- def forward(self, x, t, condition=None):
280
- x = x + self.warp(
281
- torch.cat([self.posi_encoder(x), self.time_encoder(t)], dim=-1)
282
- )
283
- return self.nerf(x, condition=condition)
284
-
285
-
286
- class NDRTNeRFRadianceField(nn.Module):
287
-
288
- """Invertble NN from https://arxiv.org/pdf/2206.15258.pdf"""
289
-
290
- def __init__(self) -> None:
291
- super().__init__()
292
- self.time_encoder = SinusoidalEncoder(1, 0, 4, True)
293
- self.warp_layers_1 = nn.ModuleList()
294
- self.time_layers_1 = nn.ModuleList()
295
- self.warp_layers_2 = nn.ModuleList()
296
- self.time_layers_2 = nn.ModuleList()
297
- self.posi_encoder_1 = SinusoidalEncoder(2, 0, 4, True)
298
- self.posi_encoder_2 = SinusoidalEncoder(1, 0, 4, True)
299
- for _ in range(3):
300
- self.warp_layers_1.append(
301
- MLP(
302
- input_dim=self.posi_encoder_1.latent_dim + 64,
303
- output_dim=1,
304
- net_depth=2,
305
- net_width=128,
306
- skip_layer=None,
307
- output_init=functools.partial(
308
- torch.nn.init.uniform_, b=1e-4
309
- ),
310
- )
311
- )
312
- self.warp_layers_2.append(
313
- MLP(
314
- input_dim=self.posi_encoder_2.latent_dim + 64,
315
- output_dim=1 + 2,
316
- net_depth=1,
317
- net_width=128,
318
- skip_layer=None,
319
- output_init=functools.partial(
320
- torch.nn.init.uniform_, b=1e-4
321
- ),
322
- )
323
- )
324
- self.time_layers_1.append(
325
- DenseLayer(
326
- input_dim=self.time_encoder.latent_dim,
327
- output_dim=64,
328
- )
329
- )
330
- self.time_layers_2.append(
331
- DenseLayer(
332
- input_dim=self.time_encoder.latent_dim,
333
- output_dim=64,
334
- )
335
- )
336
-
337
- self.nerf = VanillaNeRFRadianceField()
338
-
339
- def _warp(self, x, t_enc, i_layer):
340
- uv, w = x[:, :2], x[:, 2:]
341
- dw = self.warp_layers_1[i_layer](
342
- torch.cat(
343
- [self.posi_encoder_1(uv), self.time_layers_1[i_layer](t_enc)],
344
- dim=-1,
345
- )
346
- )
347
- w = w + dw
348
- rt = self.warp_layers_2[i_layer](
349
- torch.cat(
350
- [self.posi_encoder_2(w), self.time_layers_2[i_layer](t_enc)],
351
- dim=-1,
352
- )
353
- )
354
- r = self._euler2rot_2dinv(rt[:, :1])
355
- t = rt[:, 1:]
356
- uv = torch.bmm(r, (uv - t)[..., None]).squeeze(-1)
357
- return torch.cat([uv, w], dim=-1)
358
-
359
- def warp(self, x, t):
360
- t_enc = self.time_encoder(t)
361
- x = self._warp(x, t_enc, 0)
362
- x = x[..., [1, 2, 0]]
363
- x = self._warp(x, t_enc, 1)
364
- x = x[..., [2, 0, 1]]
365
- x = self._warp(x, t_enc, 2)
366
- return x
367
-
368
- def query_opacity(self, x, timestamps, step_size):
369
- idxs = torch.randint(0, len(timestamps), (x.shape[0],), device=x.device)
370
- t = timestamps[idxs]
371
- density = self.query_density(x, t)
372
- # if the density is small enough those two are the same.
373
- # opacity = 1.0 - torch.exp(-density * step_size)
374
- opacity = density * step_size
375
- return opacity
376
-
377
- def query_density(self, x, t):
378
- x = self.warp(x, t)
379
- return self.nerf.query_density(x)
380
-
381
- def forward(self, x, t, condition=None):
382
- x = self.warp(x, t)
383
- return self.nerf(x, condition=condition)
384
-
385
- def _euler2rot_2dinv(self, euler_angle):
386
- # (B, 1) -> (B, 2, 2)
387
- theta = euler_angle.reshape(-1, 1, 1)
388
- rot = torch.cat(
389
- (
390
- torch.cat((theta.cos(), -theta.sin()), 1),
391
- torch.cat((theta.sin(), theta.cos()), 1),
392
- ),
393
- 2,
394
- )
395
- return rot
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/radiance_fields/ngp.py DELETED
@@ -1,299 +0,0 @@
1
- """
2
- Copyright (c) 2022 Ruilong Li, UC Berkeley.
3
- """
4
-
5
- from typing import Callable, List, Union
6
-
7
- import numpy as np
8
- import torch
9
- from torch.autograd import Function
10
- from torch.cuda.amp import custom_bwd, custom_fwd
11
- import torch.nn.functional as F
12
-
13
- try:
14
- import tinycudann as tcnn
15
- except ImportError as e:
16
- print(
17
- f"Error: {e}! "
18
- "Please install tinycudann by: "
19
- "pip install git+https://github.com/NVlabs/tiny-cuda-nn/#subdirectory=bindings/torch"
20
- )
21
- exit()
22
-
23
-
24
- class _TruncExp(Function): # pylint: disable=abstract-method
25
- # Implementation from torch-ngp:
26
- # https://github.com/ashawkey/torch-ngp/blob/93b08a0d4ec1cc6e69d85df7f0acdfb99603b628/activation.py
27
- @staticmethod
28
- @custom_fwd(cast_inputs=torch.float32)
29
- def forward(ctx, x): # pylint: disable=arguments-differ
30
- ctx.save_for_backward(x)
31
- return torch.exp(x)
32
-
33
- @staticmethod
34
- @custom_bwd
35
- def backward(ctx, g): # pylint: disable=arguments-differ
36
- x = ctx.saved_tensors[0]
37
- return g * torch.exp(torch.clamp(x, max=15))
38
-
39
-
40
- trunc_exp = _TruncExp.apply
41
-
42
-
43
- def contract_to_unisphere(
44
- x: torch.Tensor,
45
- aabb: torch.Tensor,
46
- ord: Union[str, int] = 2,
47
- # ord: Union[float, int] = float("inf"),
48
- eps: float = 1e-6,
49
- derivative: bool = False,
50
- ):
51
- aabb_min, aabb_max = torch.split(aabb, 3, dim=-1)
52
- x = (x - aabb_min) / (aabb_max - aabb_min)
53
- x = x * 2 - 1 # aabb is at [-1, 1]
54
- mag = torch.linalg.norm(x, ord=ord, dim=-1, keepdim=True)
55
- mask = mag.squeeze(-1) > 1
56
-
57
- if derivative:
58
- dev = (2 * mag - 1) / mag**2 + 2 * x**2 * (
59
- 1 / mag**3 - (2 * mag - 1) / mag**4
60
- )
61
- dev[~mask] = 1.0
62
- dev = torch.clamp(dev, min=eps)
63
- return dev
64
- else:
65
- x[mask] = (2 - 1 / mag[mask]) * (x[mask] / mag[mask])
66
- x = x / 4 + 0.5 # [-inf, inf] is at [0, 1]
67
- return x
68
-
69
-
70
- class NGPRadianceField(torch.nn.Module):
71
- """Instance-NGP Radiance Field"""
72
-
73
- def __init__(
74
- self,
75
- aabb: Union[torch.Tensor, List[float]],
76
- num_dim: int = 3,
77
- use_viewdirs: bool = True,
78
- density_activation: Callable = lambda x: trunc_exp(x - 1),
79
- radiance_activation: Callable = lambda x: F.sigmoid(x),
80
- unbounded: bool = False,
81
- base_resolution: int = 16,
82
- max_resolution: int = 4096,
83
- geo_feat_dim: int = 15,
84
- n_levels: int = 16,
85
- log2_hashmap_size: int = 19,
86
- args = None
87
- ) -> None:
88
- super().__init__()
89
- if not isinstance(aabb, torch.Tensor):
90
- aabb = torch.tensor(aabb, dtype=torch.float32)
91
- self.register_buffer("aabb", aabb)
92
- self.num_dim = num_dim
93
- self.radiance_activation = radiance_activation
94
- self.use_viewdirs = use_viewdirs
95
- self.density_activation = density_activation
96
- self.unbounded = unbounded
97
- self.base_resolution = base_resolution
98
- self.max_resolution = max_resolution
99
- self.geo_feat_dim = geo_feat_dim
100
- self.n_levels = n_levels
101
- self.log2_hashmap_size = log2_hashmap_size
102
- self.version = args.version
103
- self.radiance_activation = radiance_activation
104
- self.n_output_dim = 3
105
-
106
-
107
-
108
-
109
- per_level_scale = np.exp(
110
- (np.log(max_resolution) - np.log(base_resolution)) / (n_levels - 1)
111
- ).tolist()
112
-
113
- if self.use_viewdirs:
114
- self.direction_encoding = tcnn.Encoding(
115
- n_input_dims=num_dim,
116
- encoding_config={
117
- "otype": "Composite",
118
- "nested": [
119
- {
120
- "n_dims_to_encode": 3,
121
- "otype": "SphericalHarmonics",
122
- "degree": 4,
123
- },
124
- # {"otype": "Identity", "n_bins": 4, "degree": 4},
125
- ],
126
- },
127
- )
128
-
129
- self.mlp_base = tcnn.NetworkWithInputEncoding(
130
- n_input_dims=num_dim,
131
- n_output_dims=1 + self.geo_feat_dim,
132
- encoding_config={
133
- "otype": "HashGrid",
134
- "n_levels": n_levels,
135
- "n_features_per_level": 2,
136
- "log2_hashmap_size": log2_hashmap_size,
137
- "base_resolution": base_resolution,
138
- "per_level_scale": per_level_scale,
139
- },
140
- network_config={
141
- "otype": "FullyFusedMLP",
142
- "activation": "ReLU",
143
- "output_activation": "None",
144
- "n_neurons": 64,
145
- "n_hidden_layers": 1,
146
- },
147
- )
148
- if self.geo_feat_dim > 0:
149
- self.mlp_head = tcnn.Network(
150
- n_input_dims=(
151
- (
152
- self.direction_encoding.n_output_dims
153
- if self.use_viewdirs
154
- else 0
155
- )
156
- + self.geo_feat_dim
157
- ),
158
- n_output_dims=self.n_output_dim,
159
- network_config={
160
- "otype": "FullyFusedMLP",
161
- "activation": "ReLU",
162
- "output_activation": "None",
163
- "n_neurons": 64,
164
- "n_hidden_layers": 2,
165
- },
166
- )
167
-
168
- def query_density(self, x, return_feat: bool = False):
169
- if self.unbounded:
170
- x = contract_to_unisphere(x, self.aabb)
171
- else:
172
- aabb_min, aabb_max = torch.split(self.aabb, self.num_dim, dim=-1)
173
- x = (x - aabb_min) / (aabb_max - aabb_min)
174
- selector = ((x > 0.0) & (x < 1.0)).all(dim=-1)
175
- x = (
176
- self.mlp_base(x.view(-1, self.num_dim))
177
- .view(list(x.shape[:-1]) + [1 + self.geo_feat_dim])
178
- .to(x)
179
- )
180
- density_before_activation, base_mlp_out = torch.split(
181
- x, [1, self.geo_feat_dim], dim=-1
182
- )
183
- density = (
184
- self.density_activation(density_before_activation)
185
- * selector[..., None]
186
- )
187
- if return_feat:
188
- return density, base_mlp_out
189
- else:
190
- return density
191
-
192
- def _query_rgb(self, dir, embedding, apply_act: bool = True):
193
- # tcnn requires directions in the range [0, 1]
194
- if self.use_viewdirs:
195
- dir = (dir + 1.0) / 2.0
196
- d = self.direction_encoding(dir.reshape(-1, dir.shape[-1]))
197
- h = torch.cat([d, embedding.reshape(-1, self.geo_feat_dim)], dim=-1)
198
- else:
199
- h = embedding.reshape(-1, self.geo_feat_dim)
200
- rgb = (
201
- self.mlp_head(h)
202
- .reshape(list(embedding.shape[:-1]) + [self.n_output_dim])
203
- .to(embedding)
204
- )
205
- if apply_act:
206
- rgb = self.radiance_activation(rgb)
207
-
208
- return rgb
209
-
210
- def forward(
211
- self,
212
- positions: torch.Tensor,
213
- directions: torch.Tensor = None,
214
- ):
215
- if positions.shape[0] == 0:
216
- density = torch.zeros(0, device=positions.device)
217
- color = torch.zeros(0, 1200, device=positions.device)
218
- return color, density
219
-
220
- if self.use_viewdirs and (directions is not None):
221
- assert (
222
- positions.shape == directions.shape
223
- ), f"{positions.shape} v.s. {directions.shape}"
224
- density, embedding = self.query_density(positions, return_feat=True)
225
- rgb = self._query_rgb(directions, embedding=embedding)
226
- else:
227
- density, embedding = self.query_density(positions, return_feat=True)
228
- rgb = self._query_rgb(directions, embedding=embedding)
229
- return rgb, density # type: ignore
230
-
231
-
232
- class NGPDensityField(torch.nn.Module):
233
- """Instance-NGP Density Field used for resampling"""
234
-
235
- def __init__(
236
- self,
237
- aabb: Union[torch.Tensor, List[float]],
238
- num_dim: int = 3,
239
- density_activation: Callable = lambda x: trunc_exp(x - 1),
240
- unbounded: bool = False,
241
- base_resolution: int = 16,
242
- max_resolution: int = 128,
243
- n_levels: int = 5,
244
- log2_hashmap_size: int = 17,
245
- ) -> None:
246
- super().__init__()
247
- if not isinstance(aabb, torch.Tensor):
248
- aabb = torch.tensor(aabb, dtype=torch.float32)
249
- self.register_buffer("aabb", aabb)
250
- self.num_dim = num_dim
251
- self.density_activation = density_activation
252
- self.unbounded = unbounded
253
- self.base_resolution = base_resolution
254
- self.max_resolution = max_resolution
255
- self.n_levels = n_levels
256
- self.log2_hashmap_size = log2_hashmap_size
257
-
258
- per_level_scale = np.exp(
259
- (np.log(max_resolution) - np.log(base_resolution)) / (n_levels - 1)
260
- ).tolist()
261
-
262
- self.mlp_base = tcnn.NetworkWithInputEncoding(
263
- n_input_dims=num_dim,
264
- n_output_dims=1,
265
- encoding_config={
266
- "otype": "HashGrid",
267
- "n_levels": n_levels,
268
- "n_features_per_level": 2,
269
- "log2_hashmap_size": log2_hashmap_size,
270
- "base_resolution": base_resolution,
271
- "per_level_scale": per_level_scale,
272
- },
273
- network_config={
274
- "otype": "FullyFusedMLP",
275
- "activation": "ReLU",
276
- "output_activation": "None",
277
- "n_neurons": 64,
278
- "n_hidden_layers": 1,
279
- },
280
- )
281
-
282
- def forward(self, positions: torch.Tensor):
283
- if self.unbounded:
284
- positions = contract_to_unisphere(positions, self.aabb)
285
- else:
286
- aabb_min, aabb_max = torch.split(self.aabb, self.num_dim, dim=-1)
287
- positions = (positions - aabb_min) / (aabb_max - aabb_min)
288
- selector = ((positions > 0.0) & (positions < 1.0)).all(dim=-1)
289
- density_before_activation = (
290
- self.mlp_base(positions.view(-1, self.num_dim))
291
- .view(list(positions.shape[:-1]) + [1])
292
- .to(positions)
293
- )
294
- density = (
295
- self.density_activation(density_before_activation)
296
- * selector[..., None]
297
- )
298
- return density
299
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/train_ours.py DELETED
@@ -1,521 +0,0 @@
1
- import math
2
- import os
3
-
4
- import configargparse
5
- import numpy as np
6
- import pandas as pd
7
- import scipy.io as sio
8
- import torch
9
- import torch.multiprocessing as mp
10
- import tqdm
11
- from nerfacc.estimators.occ_grid import OccGridEstimator
12
- from torch.utils.tensorboard import SummaryWriter
13
-
14
- from misc.summary import write_summary_histogram
15
- from misc.transient_volrend import torch_laser_kernel
16
- from radiance_fields.ngp import NGPRadianceField
17
- from utils import (
18
- load_args,
19
- make_save_folder,
20
- make_save_folder_final,
21
- render_transient,
22
- set_random_seed,
23
- )
24
-
25
- if mp.get_start_method(allow_none=True) is None:
26
- mp.set_start_method("spawn")
27
-
28
-
29
- def load_args_ours():
30
- parser = configargparse.ArgumentParser()
31
- parser.add_argument(
32
- "--irf_path",
33
- type=str,
34
- default="",
35
- help="Path to IRF file. Supports .csv/.npy/.mat/.pt. If empty, fallback to --pulse_path.",
36
- )
37
- parser.add_argument(
38
- "--irf_column",
39
- type=str,
40
- default="irf",
41
- help="CSV column name for IRF values.",
42
- )
43
- parser.add_argument(
44
- "--irf_half_window",
45
- type=int,
46
- default=50,
47
- help="Half window size for cropping around IRF peak. Set <=0 to disable crop.",
48
- )
49
- parser.add_argument(
50
- "--no_irf_reverse",
51
- action="store_true",
52
- help="Disable reverse before Conv1d kernel creation.",
53
- )
54
- parser.add_argument(
55
- "--measurement_root",
56
- type=str,
57
- default="",
58
- help="Optional root directory of measurement files (.npz/.txt/.pt/.h5).",
59
- )
60
- parser.add_argument(
61
- "--data_exts",
62
- type=str,
63
- default=".npz,.txt,.pt,.h5,.hdf5",
64
- help="Comma-separated measurement extensions lookup order.",
65
- )
66
- parser.add_argument(
67
- "--bin_width_s_loader",
68
- type=float,
69
- default=None,
70
- help="Bin width in seconds for shift resampling. If empty, derived from exposure_time / c.",
71
- )
72
- parser.add_argument(
73
- "--img_height",
74
- type=int,
75
- default=None,
76
- help="Training image height. If empty, use --img_shape.",
77
- )
78
- parser.add_argument(
79
- "--img_width",
80
- type=int,
81
- default=None,
82
- help="Training image width. If empty, use --img_shape.",
83
- )
84
- parser.add_argument(
85
- "--img_height_test",
86
- type=int,
87
- default=None,
88
- help="Test image height. If empty, use --img_shape_test.",
89
- )
90
- parser.add_argument(
91
- "--img_width_test",
92
- type=int,
93
- default=None,
94
- help="Test image width. If empty, use --img_shape_test.",
95
- )
96
- parser.add_argument(
97
- "--meas_peak_min",
98
- type=float,
99
- default=100.0,
100
- help=(
101
- "Minimum raw histogram peak per pixel to keep it in photometric loss. "
102
- "<=0 disables this mask. Threshold is interpreted in pre-normalization measurement scale."
103
- ),
104
- )
105
- parser.add_argument(
106
- "--invalid_mask_path",
107
- type=str,
108
- default="",
109
- help=(
110
- "Path to offset map used to build valid-pixel mask. "
111
- "Pixels with offset > invalid_mask_invalid_gt are excluded from training/eval."
112
- ),
113
- )
114
- parser.add_argument(
115
- "--invalid_mask_invalid_gt",
116
- type=float,
117
- default=10.0,
118
- help="Offset threshold for invalid pixels in invalid_mask_path.",
119
- )
120
- return load_args(eval=True, parser=parser)
121
-
122
-
123
- def _to_numpy(x):
124
- if isinstance(x, np.ndarray):
125
- return x
126
- if isinstance(x, torch.Tensor):
127
- return x.detach().cpu().numpy()
128
- return np.asarray(x)
129
-
130
-
131
- def _load_irf_series(path: str, column: str) -> np.ndarray:
132
- ext = os.path.splitext(path)[1].lower()
133
- if ext == ".csv":
134
- df = pd.read_csv(path, sep=",")
135
- if column in df.columns:
136
- arr = df[column].to_numpy(dtype=np.float64)
137
- else:
138
- numeric_cols = [c for c in df.columns if np.issubdtype(df[c].dtype, np.number)]
139
- if not numeric_cols:
140
- raise ValueError(f"No numeric columns found in IRF CSV: {path}")
141
- arr = df[numeric_cols[0]].to_numpy(dtype=np.float64)
142
- return arr.squeeze()
143
- if ext == ".npy":
144
- return np.load(path).astype(np.float64).squeeze()
145
- if ext == ".mat":
146
- mat = sio.loadmat(path)
147
- if "out" in mat:
148
- return _to_numpy(mat["out"]).astype(np.float64).squeeze()
149
- for value in mat.values():
150
- if isinstance(value, np.ndarray) and value.ndim >= 1 and value.size > 1:
151
- return _to_numpy(value).astype(np.float64).squeeze()
152
- raise ValueError(f"Cannot find valid IRF series in mat file: {path}")
153
- if ext == ".pt":
154
- return _to_numpy(torch.load(path, map_location="cpu")).astype(np.float64).squeeze()
155
- raise ValueError(f"Unsupported IRF extension: {ext}")
156
-
157
-
158
- def build_irf_kernel(args, device):
159
- irf_path = args.irf_path if args.irf_path else args.pulse_path
160
- if not irf_path:
161
- raise ValueError("IRF path is empty. Set --irf_path or --pulse_path.")
162
-
163
- irf = _load_irf_series(irf_path, args.irf_column)
164
- if irf.ndim != 1:
165
- irf = irf.reshape(-1)
166
- if irf.size == 0:
167
- raise ValueError(f"Loaded empty IRF from: {irf_path}")
168
-
169
- peak_idx = int(np.argmax(irf))
170
- if args.irf_half_window and args.irf_half_window > 0:
171
- lo = max(0, peak_idx - int(args.irf_half_window))
172
- hi = min(len(irf), peak_idx + int(args.irf_half_window) + 1)
173
- irf = irf[lo:hi]
174
-
175
- irf = irf / (irf.sum() + 1e-8)
176
- if not args.no_irf_reverse:
177
- irf = irf[::-1].copy()
178
-
179
- laser = torch.tensor(irf, dtype=torch.float32, device=device)
180
- return torch_laser_kernel(laser, device=device)
181
-
182
-
183
- def run():
184
- args = load_args_ours()
185
- device = torch.device(args.device)
186
- args.device = str(device)
187
- if device.type == "cuda":
188
- if not torch.cuda.is_available():
189
- raise RuntimeError(f"CUDA device requested but CUDA is unavailable: {device}")
190
- torch.cuda.set_device(device)
191
- torch.cuda.empty_cache()
192
- set_random_seed(args.seed)
193
-
194
- train_h = int(args.img_height) if args.img_height is not None else int(args.img_shape)
195
- train_w = int(args.img_width) if args.img_width is not None else int(args.img_shape)
196
- test_h = int(args.img_height_test) if args.img_height_test is not None else int(args.img_shape_test)
197
- test_w = int(args.img_width_test) if args.img_width_test is not None else int(args.img_shape_test)
198
- img_shape = (train_h, train_w)
199
- img_shape_test = (test_h, test_w)
200
-
201
- aabb = torch.tensor(args.aabb, dtype=torch.float32, device=device)
202
- train_dataset_kwargs = {}
203
- test_dataset_kwargs = {}
204
-
205
- rfilter_sigma = args.rfilter_sigma
206
- max_steps = args.max_steps
207
- sample_as_per_distribution = args.sample_as_per_distribution
208
- target_sample_batch_size = 1 << 16
209
-
210
- if args.version == "simulated":
211
- from loaders.loader_synthetic import SubjectLoaderTransient as SubjectLoader
212
-
213
- test_dataset_kwargs = {
214
- "img_shape": img_shape_test,
215
- "have_images": True,
216
- "n_bins": args.n_bins,
217
- "color_bkgd_aug": "black",
218
- "rfilter_sigma": rfilter_sigma,
219
- "sample_as_per_distribution": sample_as_per_distribution,
220
- }
221
- train_dataset_kwargs = {
222
- "img_shape": img_shape,
223
- "n_bins": args.n_bins,
224
- "color_bkgd_aug": "black",
225
- "rfilter_sigma": rfilter_sigma,
226
- "sample_as_per_distribution": sample_as_per_distribution,
227
- }
228
-
229
- train_dataset = SubjectLoader(
230
- root_fp=args.data_root_fp,
231
- subject_id=args.exp_name,
232
- split="train",
233
- num_rays=target_sample_batch_size // args.render_n_samples,
234
- **train_dataset_kwargs,
235
- num_views=args.num_views,
236
- )
237
- train_dataset.camtoworlds = train_dataset.camtoworlds.to(device)
238
- train_dataset.K = train_dataset.K.to(device)
239
-
240
- test_dataset = SubjectLoader(
241
- root_fp=args.data_root_fp,
242
- subject_id=args.exp_name,
243
- split="test",
244
- num_rays=None,
245
- **test_dataset_kwargs,
246
- )
247
- if test_dataset_kwargs["have_images"]:
248
- test_dataset.images = test_dataset.images.to(device)
249
- test_dataset.camtoworlds = test_dataset.camtoworlds.to(device)
250
- test_dataset.K = test_dataset.K.to(device)
251
- else:
252
- from loaders.loader_captured_ours import LearnRays, SubjectLoaderTransientRealOurs as SubjectLoader
253
-
254
- params = np.load(args.intrinsics, allow_pickle=True)[()]
255
- shift = _to_numpy(params["shift"])
256
- rays = _to_numpy(params["rays"])
257
- source_img_shape = (int(rays.shape[0]), int(rays.shape[1]))
258
-
259
- measurement_root = args.measurement_root.strip() or None
260
- invalid_mask_path = args.invalid_mask_path.strip() or None
261
- data_exts = tuple(e.strip() for e in args.data_exts.split(",") if e.strip())
262
- if args.bin_width_s_loader is not None:
263
- bin_width_s_loader = float(args.bin_width_s_loader)
264
- else:
265
- bin_width_s_loader = float(args.exposure_time) / 299792458.0
266
-
267
- test_dataset_kwargs = {
268
- "img_shape": img_shape_test,
269
- "have_images": True,
270
- "n_bins": args.n_bins,
271
- "color_bkgd_aug": "black",
272
- "rfilter_sigma": rfilter_sigma,
273
- "sample_as_per_distribution": sample_as_per_distribution,
274
- "shift": shift,
275
- "measurement_root": measurement_root,
276
- "data_exts": data_exts,
277
- "bin_width_s": bin_width_s_loader,
278
- "source_img_shape": source_img_shape,
279
- "invalid_mask_path": invalid_mask_path,
280
- "invalid_mask_invalid_gt": float(args.invalid_mask_invalid_gt),
281
- }
282
- train_dataset_kwargs = {
283
- "img_shape": img_shape,
284
- "n_bins": args.n_bins,
285
- "color_bkgd_aug": "black",
286
- "rfilter_sigma": rfilter_sigma,
287
- "sample_as_per_distribution": sample_as_per_distribution,
288
- "shift": shift,
289
- "measurement_root": measurement_root,
290
- "data_exts": data_exts,
291
- "bin_width_s": bin_width_s_loader,
292
- "source_img_shape": source_img_shape,
293
- "invalid_mask_path": invalid_mask_path,
294
- "invalid_mask_invalid_gt": float(args.invalid_mask_invalid_gt),
295
- }
296
-
297
- train_dataset = SubjectLoader(
298
- root_fp=args.data_root_fp,
299
- subject_id=args.exp_name,
300
- split="train",
301
- num_rays=target_sample_batch_size // args.render_n_samples,
302
- **train_dataset_kwargs,
303
- )
304
- train_dataset.camtoworlds = train_dataset.camtoworlds.to(device)
305
- train_dataset.K = LearnRays(rays, device=device, img_shape=img_shape).to(device)
306
-
307
- test_dataset = SubjectLoader(
308
- root_fp=args.data_root_fp,
309
- subject_id=args.exp_name,
310
- split="test",
311
- num_rays=None,
312
- **test_dataset_kwargs,
313
- )
314
- if test_dataset_kwargs["have_images"]:
315
- test_dataset.images = test_dataset.images.to(device)
316
- test_dataset.camtoworlds = test_dataset.camtoworlds.to(device)
317
- test_dataset.K = LearnRays(rays, device=device, img_shape=img_shape_test).to(device)
318
-
319
- args.laser_kernel = build_irf_kernel(args, device=device)
320
- train_dataset_scale = float(_to_numpy(train_dataset.max).reshape(-1)[0])
321
- if train_dataset_scale <= 0:
322
- train_dataset_scale = 1.0
323
-
324
- scene_aabb = torch.tensor(args.aabb, dtype=torch.float32, device=device)
325
- render_step_size = ((scene_aabb[3:] - scene_aabb[:3]).max() * math.sqrt(3) / args.render_n_samples).item()
326
-
327
- grad_scaler = torch.cuda.amp.GradScaler(2**10)
328
- radiance_field = NGPRadianceField(
329
- use_viewdirs=True,
330
- aabb=args.aabb,
331
- unbounded=False,
332
- radiance_activation=torch.exp,
333
- args=args,
334
- ).to(device)
335
-
336
- optimizer = torch.optim.Adam(radiance_field.parameters(), lr=args.lr, eps=1e-15)
337
- scheduler = torch.optim.lr_scheduler.MultiStepLR(
338
- optimizer,
339
- milestones=[max_steps // 2, max_steps * 3 // 4, max_steps * 9 // 10],
340
- gamma=0.33,
341
- )
342
- occupancy_grid = OccGridEstimator(
343
- roi_aabb=aabb,
344
- resolution=args.grid_resolution,
345
- levels=args.grid_nlvl,
346
- ).to(device)
347
-
348
- if args.final:
349
- writer, step, outpath = make_save_folder_final(
350
- args,
351
- optimizer,
352
- scheduler,
353
- radiance_field,
354
- occupancy_grid,
355
- )
356
- args.outpath = outpath
357
- else:
358
- outpath = make_save_folder(args)
359
- args.outpath = outpath
360
- writer = SummaryWriter(log_dir=outpath)
361
- step = 0
362
-
363
- # When resuming (final=True), show progress from resumed step.
364
- pbar = tqdm.tqdm(total=args.max_steps, initial=min(step, args.max_steps))
365
- zero_sample_streak = 0
366
- while step < max_steps:
367
- pbar.update(1)
368
-
369
- if args.version == "simulated" and step % 1000 == 0:
370
- if train_dataset.rep < 30:
371
- train_dataset.rep += 2
372
-
373
- radiance_field.train()
374
-
375
- i = torch.randint(0, len(train_dataset), (1,)).item()
376
- data = train_dataset[i]
377
- rays = data["rays"]
378
- num_base_rays = int(rays.origins.shape[0] / train_dataset.rep)
379
- pixs = torch.reshape(
380
- data["pixels"][:num_base_rays],
381
- (-1, args.n_bins, 3),
382
- )
383
- data_valid_mask = data.get("valid_mask")
384
- if data_valid_mask is not None:
385
- data_valid_mask = data_valid_mask.to(device=device, dtype=torch.bool).reshape(-1)
386
- if data_valid_mask.numel() < num_base_rays:
387
- raise ValueError(
388
- f"valid_mask has too few elements: {data_valid_mask.numel()} < base rays {num_base_rays}"
389
- )
390
- data_valid_mask = data_valid_mask[:num_base_rays]
391
- else:
392
- data_valid_mask = torch.ones(pixs.shape[0], dtype=torch.bool, device=device)
393
- # Use measurement peak (pre-log) to exclude low-signal / out-of-range pixels.
394
- if args.version == "captured" and float(args.meas_peak_min) > 0:
395
- peak_thre_norm = float(args.meas_peak_min) / float(train_dataset_scale)
396
- meas_peak = torch.amax(pixs[..., 0], dim=-1)
397
- meas_valid_mask = meas_peak >= peak_thre_norm
398
- else:
399
- meas_valid_mask = torch.ones(pixs.shape[0], dtype=torch.bool, device=pixs.device)
400
-
401
- def occ_eval_fn(x):
402
- density = radiance_field.query_density(x)
403
- density = torch.nan_to_num(density, nan=0.0, posinf=0.0, neginf=0.0)
404
- return density.squeeze(-1) * render_step_size
405
-
406
- base_occ_thre = float(args.occ_thre)
407
- if args.version == "captured":
408
- warmup_steps = int(args.thold_warmup) if int(args.thold_warmup) > 0 else 10000
409
- occ_thre = min(base_occ_thre, 1e-6) if step < warmup_steps else base_occ_thre
410
- else:
411
- occ_thre = base_occ_thre
412
-
413
- try:
414
- occupancy_grid.update_every_n_steps(step=step, occ_eval_fn=occ_eval_fn, occ_thre=occ_thre)
415
- except RuntimeError as ex:
416
- if "invalid configuration argument" in str(ex).lower():
417
- raise RuntimeError(
418
- "CUDA invalid configuration argument during occupancy update. "
419
- "This is often an async CUDA error from an earlier kernel. "
420
- "Rerun with CUDA_LAUNCH_BLOCKING=1 to get the first failing op."
421
- ) from ex
422
- raise
423
-
424
- out = render_transient(
425
- radiance_field,
426
- occupancy_grid,
427
- rays,
428
- near_plane=args.near_plane,
429
- far_plane=args.far_plane,
430
- render_step_size=render_step_size,
431
- cone_angle=args.cone_angle,
432
- alpha_thre=args.alpha_thre,
433
- use_normals=False,
434
- args=args,
435
- )
436
-
437
- rgb, acc, n_rendering_samples, comp_weights = [
438
- out[key] for key in ["colors", "opacities", "n_rendering_samples", "comp_weights"]
439
- ]
440
- del out
441
-
442
- if n_rendering_samples == 0:
443
- # Avoid infinite loops where step never advances.
444
- zero_sample_streak += 1
445
- if zero_sample_streak % 100 == 0:
446
- print(
447
- f"[WARN] n_rendering_samples==0 streak={zero_sample_streak} "
448
- f"at step={step}. Try lowering occ_thre (current={occ_thre})."
449
- )
450
- step += 1
451
- continue
452
- zero_sample_streak = 0
453
-
454
- train_dataset.update_num_rays(args.num_rays_per_batch)
455
-
456
- alive_ray_mask = acc.squeeze(-1) > 0
457
- alive_ray_mask = alive_ray_mask.reshape(train_dataset.rep, -1)
458
- alive_ray_mask = alive_ray_mask.sum(0).bool()
459
- supervised_mask = alive_ray_mask & meas_valid_mask & data_valid_mask
460
-
461
- rgba = torch.reshape(rgb, (-1, args.n_bins, 3)) * data["weights"][:, None, None]
462
- carve_mask = pixs.sum(-1).repeat(train_dataset.rep, 1) < 1e-7
463
- valid_mask_flat = data_valid_mask.repeat(train_dataset.rep)[:, None]
464
- carve_mask = carve_mask & valid_mask_flat.expand(-1, args.n_bins)
465
- carve_vals = comp_weights[carve_mask]
466
- if carve_vals.numel() > 0:
467
- comp_weights = carve_vals.mean()
468
- else:
469
- comp_weights = torch.tensor(0.0, device=device, dtype=rgba.dtype)
470
- rgb = torch.zeros((int(rgba.shape[0] / train_dataset.rep), args.n_bins, 3), device=device)
471
- index = (
472
- torch.arange(int(rgba.shape[0] / train_dataset.rep), device=device)
473
- .repeat(train_dataset.rep)[:, None, None]
474
- .expand(-1, args.n_bins, 3)
475
- )
476
- rgb.scatter_add_(0, index.type(torch.int64), rgba)
477
-
478
- pixs = torch.log(pixs + 1)
479
- rgb = torch.log(rgb + 1)
480
- if supervised_mask.any():
481
- photometric_loss = torch.nn.functional.l1_loss(rgb[supervised_mask], pixs[supervised_mask])
482
- else:
483
- photometric_loss = torch.tensor(0.0, device=device)
484
- loss = photometric_loss + comp_weights * args.space_carving
485
-
486
- optimizer.zero_grad()
487
- grad_scaler.scale(loss).backward()
488
- optimizer.step()
489
- scheduler.step()
490
-
491
- writer.add_scalar("Loss/train", loss.detach().cpu().numpy(), step)
492
- writer.add_scalar("Loss/photometric", photometric_loss.detach().cpu().numpy(), step)
493
- writer.add_scalar("Mask/supervised_ratio", supervised_mask.float().mean().detach().cpu().numpy(), step)
494
-
495
- if not step % args.steps_til_checkpoint:
496
- path = os.path.join(outpath, "radiance_field_{:04d}.pth".format(step))
497
- torch.save(radiance_field.state_dict(), path)
498
- path = os.path.join(outpath, "occupancy_grid_{:04d}.pth".format(step))
499
- torch.save(occupancy_grid.state_dict(), path)
500
- path = os.path.join(outpath, "optimizer_{:04d}.pth".format(step))
501
- torch.save(optimizer.state_dict(), path)
502
- path = os.path.join(outpath, "scheduler_{:04d}.pth".format(step))
503
- torch.save(scheduler.state_dict(), path)
504
- torch.save({"step": step, "rays_per_pixel": train_dataset.rep}, os.path.join(outpath, "variables.pth"))
505
-
506
- if test_dataset_kwargs["have_images"]:
507
- write_summary_histogram(
508
- radiance_field,
509
- occupancy_grid,
510
- writer,
511
- test_dataset,
512
- step,
513
- render_step_size,
514
- args,
515
- )
516
-
517
- step += 1
518
-
519
-
520
- if __name__ == "__main__":
521
- run()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/transientnerf/utils.py DELETED
@@ -1,539 +0,0 @@
1
- from datetime import datetime
2
- import random
3
- from typing import Optional
4
- import ast
5
- import configargparse
6
- import os
7
- import numpy as np
8
- import torch
9
- from loaders.utils import Rays, namedtuple_map
10
- from nerfacc.estimators.occ_grid import OccGridEstimator
11
- from nerfacc.grid import ray_aabb_intersect, traverse_grids
12
- from misc.transient_volrend import (
13
- rendering_transient_single_path)
14
-
15
- from torch.utils.tensorboard import SummaryWriter
16
- import shutil
17
-
18
-
19
- def set_random_seed(seed):
20
- random.seed(seed)
21
- np.random.seed(seed)
22
- torch.manual_seed(seed)
23
-
24
- def render_transient(
25
- # scene
26
- radiance_field: torch.nn.Module,
27
- occupancy_grid: OccGridEstimator,
28
- rays: Rays,
29
- # rendering options
30
- near_plane = 0,
31
- far_plane = 2**15,
32
- render_step_size: float = 1e-3,
33
- cone_angle: float = 0.0,
34
- alpha_thre: float = 0.0,
35
- # test options
36
- # only useful for dnerf
37
- chunk = 8192*128,
38
- use_normals = False,
39
- args = None
40
- ):
41
- """Render the pixels of an image."""
42
- rays_shape = rays.origins.shape
43
- if len(rays_shape) == 3:
44
- height, width, _ = rays_shape
45
- n_rays = height * width
46
- rays = namedtuple_map(
47
- lambda r: r.reshape([n_rays] + list(r.shape[2:])), rays
48
- )
49
- else:
50
- n_rays, _ = rays_shape
51
-
52
- results = []
53
-
54
- def rgb_sigma_fn(t_starts, t_ends, ray_indices):
55
- t_origins = chunk_rays.origins[ray_indices]
56
- t_dirs = chunk_rays.viewdirs[ray_indices]
57
- positions = t_origins + t_dirs * (t_starts + t_ends)[:, None] / 2.0
58
- rgbs, sigmas = radiance_field(positions, t_dirs)
59
- return rgbs, sigmas.squeeze(-1)
60
-
61
-
62
- for i in range(0, n_rays, chunk):
63
- chunk_rays = namedtuple_map(lambda r: r[i : i + chunk], rays)
64
-
65
- def sigma_fn(t_starts, t_ends, ray_indices):
66
- t_origins = chunk_rays.origins[ray_indices]
67
- t_dirs = chunk_rays.viewdirs[ray_indices]
68
- positions = t_origins + t_dirs * (t_starts + t_ends)[:, None] / 2.0
69
- sigmas = radiance_field.query_density(positions)
70
- return sigmas.squeeze(-1)
71
-
72
- ray_indices, t_starts, t_ends = occupancy_grid.sampling(
73
- chunk_rays.origins,
74
- chunk_rays.viewdirs,
75
- sigma_fn=sigma_fn,
76
- near_plane=near_plane,
77
- far_plane=far_plane,
78
- render_step_size=render_step_size,
79
- stratified=radiance_field.training,
80
- cone_angle=cone_angle,
81
- alpha_thre=alpha_thre,
82
- )
83
- rgb, opacity, depth, depth_variance, comp_weights, raw_rgbs = rendering_transient_single_path(
84
- t_starts=t_starts,
85
- t_ends=t_ends,
86
- ray_indices=ray_indices,
87
- n_rays=n_rays,
88
- # radiance field
89
- rgb_sigma_fn=rgb_sigma_fn,
90
- # rendering options
91
- render_bkgd=None,
92
- args = args
93
- )
94
-
95
- chunk_results_single = [rgb, opacity, depth, depth_variance, comp_weights, raw_rgbs, len(t_starts)]
96
- results.append(chunk_results_single)
97
-
98
- colors_single, opacities_single, depths_single, depths_variance, densities, raw_rgbs, n_rendering_samples = [
99
- torch.cat(r, dim=0) if isinstance(r[0], torch.Tensor) else r
100
- for r in zip(*results)
101
- ]
102
-
103
- normals_loss = 0
104
-
105
- colors = torch.reshape(colors_single, (-1, args.n_bins, 3))
106
-
107
- return {'colors': colors.view((*rays_shape[:-1], -1)),
108
- 'opacities': opacities_single.view((*rays_shape[:-1], -1)),
109
- 'depths': depths_single.view((*rays_shape[:-1], -1)),
110
- 'depths_variance' : depths_variance.view((*rays_shape[:-1], -1)),
111
- 'n_rendering_samples': sum(n_rendering_samples),
112
- 'normals_loss': normals_loss,
113
- 'comp_weights': comp_weights,
114
- "raw_rgbs":raw_rgbs}
115
-
116
-
117
- def parse_list(arg):
118
- try:
119
- return ast.literal_eval(arg)
120
- except (SyntaxError, ValueError):
121
- raise configargparse.ArgumentTypeError(f"Invalid list format: {arg}")
122
-
123
- def str2bool(v):
124
- if isinstance(v, bool):
125
- return v
126
- if v.lower() in ('yes', 'true', 't', 'y', '1'):
127
- return True
128
- elif v.lower() in ('no', 'false', 'f', 'n', '0'):
129
- return False
130
- else:
131
- raise configargparse.ArgumentTypeError('Boolean value expected.')
132
-
133
-
134
- def load_args(eval = False, parser= None):
135
- # parser = configargparse.ArgumentParser()
136
- if not eval:
137
- parser = configargparse.ArgumentParser()
138
-
139
- has_test_config = (
140
- eval
141
- and parser is not None
142
- and hasattr(parser, "_option_string_actions")
143
- and "--test_config" in parser._option_string_actions
144
- )
145
- my_config_default = None if has_test_config else "./configs/train/simulated/bench_two_views.ini"
146
- parser.add('-c', '--my-config',
147
- is_config_file=True,
148
- default=my_config_default,
149
- help='Path to config file.'
150
- )
151
- parser.add_argument(
152
- '--exp_name',
153
- type=str,
154
- default='lego_two_views',
155
- help='Experiment name.'
156
- )
157
- parser.add_argument(
158
- "--aabb",
159
- nargs='+',
160
- type = lambda s: ast.literal_eval(s),
161
- default="[-1.5,-1.5,-1.5,1.5,1.5, 1.5]",
162
- help="AABB size.",
163
- )
164
- parser.add_argument(
165
- "--test_chunk_size",
166
- type=int,
167
- default=512,
168
- help="Test chunk size..",
169
- )
170
- parser.add_argument(
171
- "--num_rays_per_batch",
172
- type=int,
173
- default=512,
174
- help="Number of rays per batch.",
175
- )
176
- parser.add_argument(
177
- "--starting_rays_per_pixel",
178
- type=int,
179
- default=1,
180
- help="Starting rays per pixels.",
181
- )
182
- parser.add_argument(
183
- "--tfilter_sigma",
184
- type=int,
185
- default=3,
186
- help="Temporal filter standard deviation.",
187
- )
188
- parser.add_argument(
189
- "--space_carving",
190
- type=float,
191
- default=7*1e-3,
192
- help="Space carvig regaularization strength.",
193
- )
194
- # parser.add_argument(
195
- # "--dataset_scale",
196
- # type=int,
197
- # default=46,
198
- # help="Scale for all transient images.",
199
- # )
200
- parser.add_argument(
201
- "--rfilter_sigma",
202
- type=float,
203
- default=0.15,
204
- help="Spatial filter standard deviation.",
205
- )
206
- parser.add_argument(
207
- "--exposure_time",
208
- type=float,
209
- default=0.01,
210
- help="Exposure length per bin in meters.",
211
- )
212
- parser.add_argument(
213
- "--lr",
214
- type=float,
215
- default=1e-3,
216
- help="Learning rate.",
217
- )
218
- parser.add_argument(
219
- "--steps_til_checkpoint",
220
- type=int,
221
- default=20000,
222
- help="Steps per checkpoint.",
223
- )
224
- parser.add_argument(
225
- "--n_bins",
226
- type=int,
227
- default=1200,
228
- help="Number of bins.",
229
- )
230
- parser.add_argument(
231
- "--img_shape",
232
- type=int,
233
- default=512,
234
- help="Shape of training image.",
235
- )
236
- parser.add_argument(
237
- "--sample_as_per_distribution",
238
- action="store_true",
239
- help="Sample as per distribution or uniformly.",
240
- )
241
- parser.add_argument(
242
- "--render_n_samples",
243
- type=int,
244
- default=4096,
245
- help="Num samples per ray.",
246
- )
247
- parser.add_argument(
248
- "--exp",
249
- type=str2bool,
250
- default="true",
251
- help="Use double exp.",
252
- )
253
- parser.add_argument(
254
- "--max_steps",
255
- type=int,
256
- default=300000,
257
- help="Max number of steps.",
258
- )
259
- parser.add_argument(
260
- "--near_plane",
261
- type=float,
262
- default=0.0,
263
- help="Near plane value.",
264
- )
265
- parser.add_argument(
266
- "--alpha_thre",
267
- type=float,
268
- default=0,
269
- )
270
- parser.add_argument(
271
- "--far_plane",
272
- type=float,
273
- default=float(2**15),
274
- help="Far plane value.",
275
- )
276
- parser.add_argument(
277
- "--version",
278
- type=str,
279
- default="simulated",
280
- choices=["captured", "simulated"],
281
- help="Dataset being trained, captured or simulated.",
282
- )
283
- parser.add_argument(
284
- "--occ_thre",
285
- type=float,
286
- default=0.01,
287
- help="Occupancy threshold",
288
- )
289
- parser.add_argument(
290
- "--thold_warmup",
291
- type=int,
292
- default=-1,
293
- help="Warmup period for the occupancy threshold.",
294
- )
295
- parser.add_argument(
296
- "--final",
297
- type=str2bool,
298
- default="false",
299
- help="If final version or debug mode (creates dated folder).",
300
- )
301
- parser.add_argument(
302
- "--grid_resolution",
303
- type=int,
304
- default=128,
305
- help="Occgrid resolution.",
306
- )
307
- parser.add_argument(
308
- "--grid_nlvl",
309
- type=int,
310
- default=1,
311
- help="Number of grid levels.",
312
- )
313
- parser.add_argument(
314
- "--outpath",
315
- type=str,
316
- default="./results",
317
- help="Path to results folder.",
318
- )
319
- parser.add_argument(
320
- "--data_root_fp",
321
- type=str,
322
- default="./data/lego_data/lego_jsons/two_views",
323
- help="Root of dataset directory (where the transforms directory is).",
324
- )
325
- parser.add_argument(
326
- "--pulse_path",
327
- type=str,
328
- default="./datasets/pulse_low_flux.mat",
329
- help="Path to pulse for captured dataset.",
330
- )
331
- parser.add_argument(
332
- "--intrinsics",
333
- type=str,
334
- default="./data/lego_data/lego_jsons/two_views",
335
- help="Path to intrinsics for captured dataset",
336
- )
337
- parser.add_argument(
338
- "--pixels_to_plot",
339
- nargs='+',
340
- type = lambda s: ast.literal_eval(s),
341
- default=[(16, 16), (20, 16), (28, 25)],
342
- help="Pixels used for plotting in the summary.",
343
- )
344
- parser.add_argument(
345
- "--img_scale",
346
- type=int,
347
- default=100,
348
- help="Image scale used in summary.",
349
- )
350
- parser.add_argument(
351
- "--num_views",
352
- type=int,
353
- default=2,
354
- help="Number of views trained on.",
355
- )
356
- parser.add_argument(
357
- "--img_shape_test",
358
- type=int,
359
- default=64,
360
- help="Test image shape.",
361
- )
362
- parser.add_argument(
363
- "--seed",
364
- type=int,
365
- default=42,
366
- help="Seed.",
367
- )
368
- parser.add_argument(
369
- "--device",
370
- type=str,
371
- default="cuda:7",
372
- help="Device.",
373
- )
374
- parser.add_argument("--cone_angle", type=float, default=0.0)
375
- parser.add_argument(
376
- "--resume",
377
- type=str,
378
- default=None,
379
- help="Path to a checkpoint directory to resume training from.",
380
- )
381
- args = parser.parse_args()
382
- return args
383
-
384
- def make_save_folder(args):
385
- now = datetime.now()
386
- now = now.strftime("%m-%d_%H:%M:%S")
387
- exp_name = args.exp_name + "_" + now
388
- outpath = os.path.join(args.outpath, exp_name)
389
- os.makedirs(args.outpath, exist_ok=True)
390
- os.mkdir(outpath)
391
- shutil.copy(args.my_config, os.path.join(outpath, "params.txt"))
392
-
393
- with open(os.path.join(outpath, "params_full.txt"), "w") as out_file:
394
- param_list = []
395
- for key, value in vars(args).items():
396
- if type(value) == list:
397
- value = [eval(f"{x}") for x in value]
398
- elif type(value) != int and type(value) != float:
399
- value = str(value)
400
- value = f"'{value}'"
401
- param_list.append("%s= %s" % (key, value))
402
-
403
- out_file.write('\n'.join(param_list))
404
- return outpath
405
-
406
- def make_save_folder_final(args, optimizer, scheduler, radiance_field, occupancy_grid):
407
- outpath = os.path.join(args.outpath, args.exp_name)
408
-
409
- if not os.path.isdir(outpath):
410
-
411
- os.makedirs(outpath, exist_ok=True)
412
- with open(os.path.join(outpath, "params_full.txt"), "w") as out_file:
413
- param_list = []
414
- for key, value in vars(args).items():
415
- if type(value) != int and type(value) != float:
416
- value = str(value)
417
- value = f"'{value}'"
418
- param_list.append("%s= %s" % (key, value))
419
-
420
- out_file.write('\n'.join(param_list))
421
- step = 0
422
- writer = SummaryWriter(log_dir=outpath)
423
-
424
- else:
425
- ckpt_path_var = os.path.join(outpath, 'variables.pth')
426
- if not os.path.isfile(ckpt_path_var):
427
- print(f"warning: '{ckpt_path_var}' not found; starting fresh in existing directory.")
428
- step = 0
429
- writer = SummaryWriter(log_dir=outpath)
430
- return writer, step, outpath
431
-
432
- ckpt = torch.load(ckpt_path_var, map_location="cpu")
433
- step = int(ckpt.get('step', 0))
434
-
435
- ckpt_path_rf = os.path.join(outpath, 'radiance_field_%04d.pth' % (step))
436
- ckpt_path_oc = os.path.join(outpath, 'occupancy_grid_%04d.pth' % (step))
437
- ckpt_path_opt = os.path.join(outpath, 'optimizer_%04d.pth' % (step))
438
- ckpt_path_sch = os.path.join(outpath, 'scheduler_%04d.pth' % (step))
439
-
440
- if not (os.path.isfile(ckpt_path_rf) and os.path.isfile(ckpt_path_oc)):
441
- print(
442
- "warning: model checkpoint files missing for saved step; "
443
- "starting fresh optimizer/model state."
444
- )
445
- step = 0
446
- writer = SummaryWriter(log_dir=outpath)
447
- return writer, step, outpath
448
-
449
- ckpt = torch.load(ckpt_path_rf, map_location=args.device)
450
- radiance_field.load_state_dict(ckpt)
451
- radiance_field = radiance_field.to(args.device)
452
-
453
- ckpt = torch.load(ckpt_path_oc, map_location=args.device)
454
- occupancy_grid.load_state_dict(ckpt)
455
- occupancy_grid = occupancy_grid.to(args.device)
456
-
457
- if os.path.isfile(ckpt_path_opt):
458
- ckpt = torch.load(ckpt_path_opt, map_location=args.device)
459
- optimizer.load_state_dict(ckpt)
460
- else:
461
- print(f"warning: optimizer checkpoint missing at '{ckpt_path_opt}', using fresh optimizer state.")
462
-
463
- if os.path.isfile(ckpt_path_sch):
464
- ckpt = torch.load(ckpt_path_sch, map_location=args.device)
465
- scheduler.load_state_dict(ckpt)
466
- else:
467
- print(f"warning: scheduler checkpoint missing at '{ckpt_path_sch}', using fresh scheduler state.")
468
-
469
- print(f"previous checkpoint loaded; current step: {step}")
470
- writer = SummaryWriter(log_dir=outpath)
471
-
472
- return writer, step, outpath
473
-
474
-
475
- def resume_training(args, optimizer, scheduler, radiance_field, occupancy_grid):
476
- """Load a previous checkpoint and prepare writer/step/outpath."""
477
- ckpt_dir = args.resume
478
- if ckpt_dir is None:
479
- raise ValueError("args.resume is None, cannot resume.")
480
- if not os.path.isdir(ckpt_dir):
481
- raise FileNotFoundError(f"Checkpoint directory not found: {ckpt_dir}")
482
-
483
- variables_path = os.path.join(ckpt_dir, "variables.pth")
484
- step = 0
485
- rays_per_pixel = None
486
- if os.path.isfile(variables_path):
487
- ckpt_vars = torch.load(variables_path, map_location="cpu")
488
- step = ckpt_vars.get("step", 0)
489
- rays_per_pixel = ckpt_vars.get("rays_per_pixel")
490
- else:
491
- ckpt_steps = []
492
- for name in os.listdir(ckpt_dir):
493
- if name.startswith("radiance_field_") and name.endswith(".pth"):
494
- try:
495
- ckpt_steps.append(int(name.split("_")[-1].split(".")[0]))
496
- except ValueError:
497
- continue
498
- if not ckpt_steps:
499
- raise FileNotFoundError(
500
- "No checkpoint files found to resume from in "
501
- f"{ckpt_dir}. Expected radiance_field_XXXX.pth."
502
- )
503
- step = max(ckpt_steps)
504
-
505
- rf_path = os.path.join(ckpt_dir, f"radiance_field_{step:04d}.pth")
506
- oc_path = os.path.join(ckpt_dir, f"occupancy_grid_{step:04d}.pth")
507
- opt_path = os.path.join(ckpt_dir, f"optimizer_{step:04d}.pth")
508
- sch_path = os.path.join(ckpt_dir, f"scheduler_{step:04d}.pth")
509
-
510
- for required_path in [rf_path, oc_path]:
511
- if not os.path.isfile(required_path):
512
- raise FileNotFoundError(f"Missing checkpoint file: {required_path}")
513
-
514
- radiance_field.load_state_dict(
515
- torch.load(rf_path, map_location=args.device)
516
- )
517
- radiance_field = radiance_field.to(args.device)
518
-
519
- occupancy_grid.load_state_dict(
520
- torch.load(oc_path, map_location=args.device)
521
- )
522
- occupancy_grid = occupancy_grid.to(args.device)
523
-
524
- if os.path.isfile(opt_path):
525
- optimizer.load_state_dict(torch.load(opt_path, map_location=args.device))
526
- else:
527
- print(f"warning: missing optimizer checkpoint '{opt_path}', using fresh optimizer state.")
528
-
529
- if os.path.isfile(sch_path):
530
- scheduler.load_state_dict(torch.load(sch_path, map_location=args.device))
531
- else:
532
- print(f"warning: missing scheduler checkpoint '{sch_path}', using fresh scheduler state.")
533
-
534
- writer = SummaryWriter(log_dir=ckpt_dir)
535
- args.outpath = ckpt_dir
536
- return writer, step, ckpt_dir, rays_per_pixel
537
-
538
- if __name__=="__main__":
539
- pass