shuinb commited on
Commit
b004d6f
·
verified ·
1 Parent(s): 5fd951c

Upload STB code utilities

Browse files
Files changed (47) hide show
  1. codes/annotation tool/labelLidarwave.py +1780 -0
  2. codes/pointcloud_extract/ann2pc.py +185 -0
  3. codes/pointcloud_extract/raw2pc.py +533 -0
  4. codes/reconstruction/transientnerf/configs/test/captured/artbuilding3_five_views_quantitative.ini +47 -0
  5. codes/reconstruction/transientnerf/configs/test/captured/artbuilding3_ten_views_quantitative.ini +47 -0
  6. codes/reconstruction/transientnerf/configs/test/captured/balldesk_quantitative_fiveviews.ini +47 -0
  7. codes/reconstruction/transientnerf/configs/test/captured/balldesk_quantitative_tenviews.ini +47 -0
  8. codes/reconstruction/transientnerf/configs/test/captured/balldesk_quantitative_threeviews.ini +47 -0
  9. codes/reconstruction/transientnerf/configs/test/captured/designbuilding1_five_views_quantitative.ini +47 -0
  10. codes/reconstruction/transientnerf/configs/test/captured/designbuilding1_quantitative_tenviews.ini +47 -0
  11. codes/reconstruction/transientnerf/configs/test/captured/parking_five_views_quantitative.ini +48 -0
  12. codes/reconstruction/transientnerf/configs/test/captured/parking_ten_views_quantitative.ini +48 -0
  13. codes/reconstruction/transientnerf/configs/test/captured/physics_building2_ten_views_quantitative.ini +48 -0
  14. codes/reconstruction/transientnerf/configs/test/captured/physics_building2_ten_views_quantitative1.ini +48 -0
  15. codes/reconstruction/transientnerf/configs/train/captured/artbuilding3_five_views.ini +50 -0
  16. codes/reconstruction/transientnerf/configs/train/captured/artbuilding3_ten_views.ini +50 -0
  17. codes/reconstruction/transientnerf/configs/train/captured/designbuilding1_five_views.ini +50 -0
  18. codes/reconstruction/transientnerf/configs/train/captured/designbuilding1_tenviews.ini +50 -0
  19. codes/reconstruction/transientnerf/configs/train/captured/material_building_five_views.ini +51 -0
  20. codes/reconstruction/transientnerf/configs/train/captured/material_building_ten_views.ini +51 -0
  21. codes/reconstruction/transientnerf/configs/train/captured/parking_five_views.ini +51 -0
  22. codes/reconstruction/transientnerf/configs/train/captured/parking_ten_views.ini +51 -0
  23. codes/reconstruction/transientnerf/configs/train/captured/physics_building2_ten_views.ini +51 -0
  24. codes/reconstruction/transientnerf/configs/train/captured/tfnerf_balldesk_fiveviews.ini +50 -0
  25. codes/reconstruction/transientnerf/configs/train/captured/tfnerf_balldesk_tenviews.ini +50 -0
  26. codes/reconstruction/transientnerf/configs/train/captured/tfnerf_balldesk_threeviews.ini +50 -0
  27. codes/reconstruction/transientnerf/eval.py +556 -0
  28. codes/reconstruction/transientnerf/loaders/README.md +57 -0
  29. codes/reconstruction/transientnerf/loaders/__init__.py +0 -0
  30. codes/reconstruction/transientnerf/loaders/loader_captured.py +532 -0
  31. codes/reconstruction/transientnerf/loaders/loader_captured_ours.py +680 -0
  32. codes/reconstruction/transientnerf/loaders/loader_synthetic.py +453 -0
  33. codes/reconstruction/transientnerf/loaders/utils.py +12 -0
  34. codes/reconstruction/transientnerf/misc/__init__.py +0 -0
  35. codes/reconstruction/transientnerf/misc/dataset_utils.py +169 -0
  36. codes/reconstruction/transientnerf/misc/download_dataset.py +67 -0
  37. codes/reconstruction/transientnerf/misc/eval_utils.py +224 -0
  38. codes/reconstruction/transientnerf/misc/summary.py +147 -0
  39. codes/reconstruction/transientnerf/misc/transient_volrend.py +620 -0
  40. codes/reconstruction/transientnerf/radiance_fields/__init__.py +0 -0
  41. codes/reconstruction/transientnerf/radiance_fields/mlp.py +395 -0
  42. codes/reconstruction/transientnerf/radiance_fields/ngp.py +299 -0
  43. codes/reconstruction/transientnerf/train_ours.py +521 -0
  44. codes/reconstruction/transientnerf/utils.py +539 -0
  45. codes/simulator/generate_data_sim.py +402 -0
  46. codes/simulator/include/simsp.py +324 -0
  47. codes/simulator/include/singlephoton.py +195 -0
codes/annotation tool/labelLidarwave.py ADDED
@@ -0,0 +1,1780 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # visualize_semantic_labels_v3.py
2
+ # ------------------------------------------------------------
3
+ # Sequential peak annotation workflow + Multi-layer semantic 3D
4
+ #
5
+ # Added: Traditional Magic Wand UI & Edge-aware region growing
6
+ #
7
+ # MOD (New Features Request - V3):
8
+ # ✅ [Restored] 3D Bins Visualization button and logic.
9
+ # ✅ [Modified] Pixel Histogram now works in a dedicated "Inspect" tool mode.
10
+ # - Pick/Brush/Eraser: Perform labeling ONLY.
11
+ # - Inspect: Performs histogram visualization ONLY (Safe mode).
12
+ # ------------------------------------------------------------
13
+
14
+ import sys
15
+ import os
16
+ import traceback
17
+ import argparse
18
+ import numpy as np
19
+ import cv2
20
+ from glob import glob
21
+ from collections import deque
22
+ import matplotlib
23
+ from concurrent.futures import ProcessPoolExecutor, as_completed
24
+
25
+ # Set backend before importing pyplot
26
+ matplotlib.use("Qt5Agg")
27
+ import matplotlib.pyplot as plt
28
+ from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
29
+ from matplotlib.figure import Figure
30
+
31
+ try:
32
+ import pandas as pd
33
+ HAS_PANDAS = True
34
+ except ImportError:
35
+ HAS_PANDAS = False
36
+ print("[Warning] Pandas not installed. TXT->NPY conversion will be disabled.")
37
+
38
+ from PyQt5.QtWidgets import (
39
+ QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
40
+ QLabel, QPushButton, QSlider, QRadioButton, QGroupBox,
41
+ QSplitter, QSizePolicy, QTextEdit, QScrollArea, QCheckBox,
42
+ QButtonGroup, QShortcut, QListWidget, QListWidgetItem,
43
+ QProgressBar, QMessageBox, QLineEdit, QFileDialog, QDialog
44
+ )
45
+ from PyQt5.QtCore import Qt, QPoint, QRect, QThread, pyqtSignal
46
+ from PyQt5.QtGui import QImage, QPixmap, QPainter, QColor, QPen, QKeySequence
47
+
48
+ try:
49
+ import open3d as o3d
50
+ HAS_OPEN3D = True
51
+ except ImportError:
52
+ HAS_OPEN3D = False
53
+ print("[Warning] Open3D not installed. 3D visualization will be disabled.")
54
+
55
+
56
+ # ==========================================
57
+ # Config
58
+ # ==========================================
59
+ class AppConfig:
60
+ IMG_H = 192
61
+ IMG_W = 256
62
+ NUM_LAYERS = 30
63
+ BIN_UNIT = 297 * 1e-12 * 299792458 / 2.0
64
+ DEFAULT_SIGNAL_THRESHOLD = 5
65
+ DEFAULT_SNR_THRESHOLD = 2.0
66
+ LABEL_FWHM_RATIO = 0.5
67
+
68
+ CLASS_LABELS = [
69
+ "Tree (树)", "Road (路)", "Fence (围栏)", "Person (人)",
70
+ "Non-motor (非机动车)", "Car (汽车)", "Street Light (路灯)",
71
+ "Signage (指示牌)", "Traffic Light (信号灯)", "Door (门)",
72
+ "Building (建筑)", "Wall (墙壁)", "Indoor Roof (室内屋顶)",
73
+ "Unknown (未知)"
74
+ ]
75
+
76
+ CUSTOM_COLORS = {
77
+ 1: (0, 255, 0), 2: (128, 128, 128), 3: (255, 165, 0),
78
+ 4: (255, 0, 0), 5: (255, 20, 147), 6: (30, 144, 255),
79
+ 7: (218, 165, 32), 8: (0, 255, 255), 9: (255, 69, 0),
80
+ 10: (165, 42, 42), 11: (160, 32, 240), 12: (189, 183, 107),
81
+ 13: (0, 128, 128), 14: (255, 255, 0)
82
+ }
83
+
84
+ CAM_K = np.array([[120.94, 0.0, 130.41], [0.0, 121.12, 97.12], [0.0, 0.0, 1.0]], dtype=np.float64)
85
+ CAM_D = np.array([-0.276, 0.062, 0.0, 0.0, 0.0], dtype=np.float64)
86
+
87
+ DEFAULT_WAND_TOLERANCE = 15
88
+ DEFAULT_WAND_EDGE_HIGH = 80
89
+ DEFAULT_WAND_CONNECTIVITY_8 = True
90
+ DEFAULT_WAND_EDGE_AWARE = True
91
+
92
+
93
+ def get_class_colors_dict():
94
+ colors = {0: (0, 0, 0)}
95
+ colors.update(AppConfig.CUSTOM_COLORS)
96
+ return colors
97
+
98
+
99
+ CLASS_COLORS = get_class_colors_dict()
100
+
101
+
102
+ def _cv2_cmap(name: str, fallback):
103
+ return getattr(cv2, name, fallback)
104
+
105
+
106
+ PEAK_CMAPS = [
107
+ ("VIRIDIS", _cv2_cmap("COLORMAP_VIRIDIS", cv2.COLORMAP_JET)),
108
+ ("PLASMA", _cv2_cmap("COLORMAP_PLASMA", cv2.COLORMAP_JET)),
109
+ ("INFERNO", _cv2_cmap("COLORMAP_INFERNO", cv2.COLORMAP_JET)),
110
+ ("MAGMA", _cv2_cmap("COLORMAP_MAGMA", cv2.COLORMAP_JET)),
111
+ ("TURBO", _cv2_cmap("COLORMAP_TURBO", cv2.COLORMAP_JET)),
112
+ ("JET", cv2.COLORMAP_JET),
113
+ ("HOT", cv2.COLORMAP_HOT),
114
+ ("OCEAN", cv2.COLORMAP_OCEAN),
115
+ ]
116
+
117
+
118
+ # ==========================================
119
+ # Helpers (General)
120
+ # ==========================================
121
+ def load_hist_npy(path: str) -> np.ndarray:
122
+ try:
123
+ print(f"[Log] Loading NPY: {path}")
124
+ data = np.load(path, mmap_mode="r")
125
+ if data.ndim == 3:
126
+ H, W, B = data.shape
127
+ data = data.reshape(-1, B)
128
+ elif data.ndim == 1:
129
+ data = data.reshape(1, -1)
130
+ return np.ascontiguousarray(data, dtype=np.float32)
131
+ except Exception as e:
132
+ print(f"[Error] Loading {path} failed: {e}", flush=True)
133
+ return None
134
+
135
+
136
+ def analyze_peak_structure(vector, peak_idx, noise_floor):
137
+ B = len(vector)
138
+ peak_val = vector[peak_idx]
139
+ if peak_val <= noise_floor:
140
+ return (peak_idx, peak_idx), (peak_idx, peak_idx)
141
+
142
+ label_thresh = peak_val * AppConfig.LABEL_FWHM_RATIO
143
+ l_lab, r_lab = peak_idx, peak_idx
144
+ while l_lab > 0 and vector[l_lab] > label_thresh:
145
+ l_lab -= 1
146
+ while r_lab < B - 1 and vector[r_lab] > label_thresh:
147
+ r_lab += 1
148
+
149
+ l_rem, r_rem = peak_idx, peak_idx
150
+ while l_rem > 0:
151
+ if vector[l_rem] < noise_floor or vector[l_rem - 1] > vector[l_rem]:
152
+ break
153
+ l_rem -= 1
154
+ while r_rem < B - 1:
155
+ if vector[r_rem] < noise_floor or vector[r_rem + 1] > vector[r_rem]:
156
+ break
157
+ r_rem += 1
158
+
159
+ l_rem = min(l_rem, l_lab)
160
+ r_rem = max(r_rem, r_lab)
161
+ return (l_lab, r_lab), (l_rem, r_rem)
162
+
163
+
164
+ def safe_numpy_to_pixmap(img_data):
165
+ if img_data is None:
166
+ return None
167
+ h, w = img_data.shape[:2]
168
+ try:
169
+ if not img_data.flags["C_CONTIGUOUS"]:
170
+ img_data = np.ascontiguousarray(img_data)
171
+
172
+ if img_data.ndim == 2:
173
+ qimg = QImage(img_data.data, w, h, w, QImage.Format_Grayscale8).copy()
174
+ elif img_data.ndim == 3:
175
+ if img_data.shape[2] == 3:
176
+ img_rgba = cv2.cvtColor(img_data, cv2.COLOR_BGR2RGBA)
177
+ qimg = QImage(img_rgba.data, w, h, w * 4, QImage.Format_RGBA8888).copy()
178
+ elif img_data.shape[2] == 4:
179
+ qimg = QImage(img_data.data, w, h, w * 4, QImage.Format_RGBA8888).copy()
180
+ else:
181
+ return None
182
+ else:
183
+ return None
184
+ return QPixmap.fromImage(qimg)
185
+ except Exception:
186
+ return None
187
+
188
+
189
+ def get_robust_colors(values, colormap_name="jet", p_min=2, p_max=99.5):
190
+ vmin, vmax = np.percentile(values, [p_min, p_max])
191
+ denom = max(vmax - vmin, 1e-6)
192
+ norm_values = np.clip((values - vmin) / denom, 0, 1)
193
+ cmap = plt.get_cmap(colormap_name)
194
+ colors = cmap(norm_values)[:, :3]
195
+ return colors
196
+
197
+
198
+ def sem_bins_to_layers(sem_bins: np.ndarray, H: int, W: int, num_layers: int):
199
+ N, B = sem_bins.shape
200
+ masks = [np.zeros((H, W), dtype=np.uint8) for _ in range(num_layers)]
201
+ flat = sem_bins
202
+
203
+ for i in range(N):
204
+ row = flat[i]
205
+ nz = np.flatnonzero(row)
206
+ if nz.size == 0:
207
+ continue
208
+ breaks = np.flatnonzero(np.diff(nz) != 1)
209
+ run_starts = np.concatenate(([0], breaks + 1))
210
+ run_ends = np.concatenate((breaks, [nz.size - 1]))
211
+ segments = []
212
+ for rs, re in zip(run_starts, run_ends):
213
+ b0 = int(nz[rs])
214
+ b1 = int(nz[re])
215
+ cid = int(row[b0])
216
+ if cid <= 0: continue
217
+ segments.append((b0, b1, cid))
218
+ segments.sort(key=lambda t: t[0])
219
+ y = i // W
220
+ x = i % W
221
+ for k, (_, __, cid) in enumerate(segments[:num_layers]):
222
+ masks[k][y, x] = cid
223
+ return masks
224
+
225
+
226
+ def save_iterative_peeling_layers(out_path, raw_data, manual_masks, layer_thresholds, H, W, fallback_thresh):
227
+ try:
228
+ folder = os.path.dirname(out_path)
229
+ if folder and not os.path.exists(folder):
230
+ os.makedirs(folder, exist_ok=True)
231
+
232
+ N, B = raw_data.shape
233
+ sem_bins = np.zeros((N, B), dtype=np.uint8)
234
+ working_data = raw_data.copy()
235
+ saved_count = 0
236
+
237
+ for l, mask2d in enumerate(manual_masks):
238
+ thr = layer_thresholds[l] if layer_thresholds[l] is not None else fallback_thresh
239
+ mask_flat = mask2d.reshape(-1)
240
+ labeled_idx = np.flatnonzero(mask_flat > 0)
241
+ if labeled_idx.size == 0:
242
+ continue
243
+ for idx in labeled_idx:
244
+ cid = int(mask_flat[idx])
245
+ hist = working_data[idx]
246
+ if np.max(hist) <= thr:
247
+ continue
248
+ peak_idx = int(np.argmax(hist))
249
+ (l_lab, r_lab), (l_rem, r_rem) = analyze_peak_structure(hist, peak_idx, thr)
250
+ if r_rem <= l_rem:
251
+ continue
252
+ sem_bins[idx, l_lab:r_lab + 1] = cid
253
+ working_data[idx, l_rem:r_rem + 1] = 0
254
+ saved_count += 1
255
+
256
+ np.save(out_path, sem_bins)
257
+ return True, f"Saved: {os.path.basename(out_path)} [Pts: {saved_count}]", saved_count
258
+ except Exception as e:
259
+ traceback.print_exc()
260
+ return False, f"Error saving: {str(e)}", 0
261
+
262
+
263
+ # ==========================================
264
+ # Batch Conversion
265
+ # ==========================================
266
+ def convert_one_file(file_path, output_root):
267
+ try:
268
+ import pandas as pd
269
+ basename = os.path.basename(file_path)
270
+ npy_name = os.path.splitext(basename)[0] + '.npy'
271
+ out_path = os.path.join(output_root, npy_name)
272
+ if os.path.exists(out_path):
273
+ return "Skipped (Exists)"
274
+ df = pd.read_csv(file_path, sep=r'\s+', header=None, dtype=np.float32, engine='c', memory_map=True)
275
+ data = df.values
276
+ if data.ndim == 1:
277
+ data = data.reshape(1, -1)
278
+ np.save(out_path, data)
279
+ return "Success"
280
+ except Exception as e:
281
+ return f"Error: {str(e)}"
282
+
283
+ class BatchConverterThread(QThread):
284
+ progress_signal = pyqtSignal(int, int)
285
+ log_signal = pyqtSignal(str)
286
+ finished_signal = pyqtSignal(int, int, int)
287
+
288
+ def __init__(self, root_search_dir, output_dir):
289
+ super().__init__()
290
+ self.root_search_dir = root_search_dir
291
+ self.output_dir = output_dir
292
+ self.is_running = True
293
+
294
+ def run(self):
295
+ if not HAS_PANDAS:
296
+ self.log_signal.emit("[Error] Pandas not found.")
297
+ self.finished_signal.emit(0, 0, 0)
298
+ return
299
+
300
+ self.log_signal.emit(f"Scanning for TXT files in: {self.root_search_dir}")
301
+ search_pattern = os.path.join(self.root_search_dir, "**", "RawDataHistogramMap_frame_*.txt")
302
+ files = glob(search_pattern, recursive=True)
303
+ if not files:
304
+ search_pattern_alt = os.path.join(self.root_search_dir, "**", "*.txt")
305
+ files = glob(search_pattern_alt, recursive=True)
306
+
307
+ total_files = len(files)
308
+ self.log_signal.emit(f"Found {total_files} files.")
309
+ if total_files == 0:
310
+ self.finished_signal.emit(0, 0, 0)
311
+ return
312
+
313
+ try:
314
+ os.makedirs(self.output_dir, exist_ok=True)
315
+ except Exception as e:
316
+ self.finished_signal.emit(0, 0, 0)
317
+ return
318
+
319
+ success_count = 0
320
+ skip_count = 0
321
+ error_count = 0
322
+ processed = 0
323
+ max_workers = min(os.cpu_count() or 4, 8)
324
+
325
+ with ProcessPoolExecutor(max_workers=max_workers) as executor:
326
+ future_to_file = {executor.submit(convert_one_file, f, self.output_dir): f for f in files}
327
+ for future in as_completed(future_to_file):
328
+ if not self.is_running:
329
+ executor.shutdown(wait=False, cancel_futures=True)
330
+ break
331
+ result = future.result()
332
+ processed += 1
333
+ if result == "Success": success_count += 1
334
+ elif result == "Skipped (Exists)": skip_count += 1
335
+ else: error_count += 1
336
+ self.progress_signal.emit(processed, total_files)
337
+
338
+ self.finished_signal.emit(success_count, skip_count, error_count)
339
+
340
+ def stop(self):
341
+ self.is_running = False
342
+
343
+
344
+ # ==========================================
345
+ # GUI widgets
346
+ # ==========================================
347
+ class CenteredCanvas(QWidget):
348
+ def __init__(self, parent=None):
349
+ super().__init__(parent)
350
+ self.setMouseTracking(True)
351
+ self.setFocusPolicy(Qt.StrongFocus)
352
+ self.img_pixmap = None
353
+ self.zoom = 1.0
354
+ self.offset = QPoint(0, 0)
355
+ self.last_mouse_pos = QPoint()
356
+ self.mode = "pick"
357
+ self.panning = False
358
+ self.drawing = False
359
+ self.start_pos = QPoint()
360
+ self.curr_pos = QPoint()
361
+ self.action_callback = None
362
+ self.mask_overlay = None
363
+ self.ghost_overlay = None
364
+ self.hide_labels = False
365
+ self.ctrl_pressed = False
366
+
367
+ def set_content(self, pixmap, mask_pixmap, ghost_pixmap=None):
368
+ self.img_pixmap = pixmap
369
+ self.mask_overlay = mask_pixmap
370
+ self.ghost_overlay = ghost_pixmap
371
+ self.update()
372
+
373
+ def fit_to_window(self):
374
+ if self.img_pixmap is None:
375
+ return
376
+ w_view, h_view = self.width(), self.height()
377
+ w_img, h_img = self.img_pixmap.width(), self.img_pixmap.height()
378
+ if w_img > 0 and h_img > 0:
379
+ self.zoom = min(w_view / w_img, h_view / h_img) * 0.98
380
+ self.offset = QPoint(0, 0)
381
+ self.update()
382
+
383
+ def paintEvent(self, event):
384
+ painter = QPainter(self)
385
+ painter.fillRect(self.rect(), QColor(40, 40, 40))
386
+ if self.img_pixmap is None:
387
+ return
388
+ ww, wh = self.width(), self.height()
389
+ cx, cy = ww // 2, wh // 2
390
+ painter.translate(cx + self.offset.x(), cy + self.offset.y())
391
+ painter.scale(self.zoom, self.zoom)
392
+ iw, ih = self.img_pixmap.width(), self.img_pixmap.height()
393
+ painter.translate(-iw // 2, -ih // 2)
394
+ painter.setRenderHint(QPainter.SmoothPixmapTransform, False)
395
+ painter.drawPixmap(0, 0, self.img_pixmap)
396
+ if not self.hide_labels:
397
+ if self.ghost_overlay is not None:
398
+ painter.setOpacity(0.30)
399
+ painter.drawPixmap(0, 0, self.ghost_overlay)
400
+ painter.setOpacity(1.0)
401
+ if self.mask_overlay is not None:
402
+ painter.setOpacity(1.0)
403
+ painter.drawPixmap(0, 0, self.mask_overlay)
404
+
405
+ # Only draw selection box if NOT in inspect mode or pure panning
406
+ if self.drawing and self.mode == "pick":
407
+ pen = QPen(Qt.green, 2) if self.ctrl_pressed else QPen(Qt.yellow, 1)
408
+ pen.setStyle(Qt.SolidLine if self.ctrl_pressed else Qt.DashLine)
409
+ painter.setPen(pen)
410
+ painter.drawRect(QRect(self.start_pos, self.curr_pos).normalized())
411
+
412
+ def get_img_pos(self, widget_pos):
413
+ ww, wh = self.width(), self.height()
414
+ cx, cy = ww // 2, wh // 2
415
+ if self.img_pixmap:
416
+ dx = widget_pos.x() - (cx + self.offset.x())
417
+ dy = widget_pos.y() - (cy + self.offset.y())
418
+ return int(dx / self.zoom + self.img_pixmap.width() / 2), int(dy / self.zoom + self.img_pixmap.height() / 2)
419
+ return 0, 0
420
+
421
+ def wheelEvent(self, event):
422
+ self.zoom *= 1.1 if event.angleDelta().y() > 0 else 0.9
423
+ self.zoom = max(0.1, min(self.zoom, 50.0))
424
+ self.update()
425
+
426
+ def mousePressEvent(self, event):
427
+ if event.button() == Qt.MiddleButton:
428
+ self.panning = True
429
+ self.last_mouse_pos = event.pos()
430
+ self.setCursor(Qt.ClosedHandCursor)
431
+ elif event.button() == Qt.LeftButton:
432
+ x, y = self.get_img_pos(event.pos())
433
+ self.start_pos = QPoint(x, y)
434
+ self.curr_pos = QPoint(x, y)
435
+ self.drawing = True
436
+ if self.mode == "draw" and self.action_callback:
437
+ self.action_callback("draw_start", self.start_pos, None)
438
+
439
+ def mouseMoveEvent(self, event):
440
+ if self.panning:
441
+ self.offset += event.pos() - self.last_mouse_pos
442
+ self.last_mouse_pos = event.pos()
443
+ self.update()
444
+ else:
445
+ x, y = self.get_img_pos(event.pos())
446
+ self.curr_pos = QPoint(x, y)
447
+ if self.drawing:
448
+ if self.mode == "draw" and self.action_callback:
449
+ self.action_callback("draw_drag", self.start_pos, self.curr_pos)
450
+ self.start_pos = self.curr_pos
451
+ elif self.mode == "pick":
452
+ self.update()
453
+
454
+ def mouseReleaseEvent(self, event):
455
+ if self.panning:
456
+ self.panning = False
457
+ self.setCursor(Qt.ArrowCursor)
458
+ return
459
+ if event.button() == Qt.LeftButton and self.drawing:
460
+ self.drawing = False
461
+ end_pos = self.curr_pos if not self.curr_pos.isNull() else self.start_pos
462
+ if self.mode == "pick" and self.action_callback:
463
+ self.action_callback("pick_end_ctrl" if self.ctrl_pressed else "pick_end", self.start_pos, end_pos)
464
+ elif self.mode == "draw" and self.action_callback:
465
+ self.action_callback("draw_end", end_pos, None)
466
+ self.update()
467
+
468
+ class PopupImageDialog(QDialog):
469
+ def __init__(self, pixmap, title, parent=None):
470
+ super().__init__(parent)
471
+ self.setWindowTitle(title + " (Double click to close)")
472
+ self.resize(800, 600)
473
+ self.setWindowFlags(Qt.Window)
474
+ layout = QVBoxLayout(self)
475
+ layout.setContentsMargins(0, 0, 0, 0)
476
+ self.viewer = CenteredCanvas()
477
+ self.viewer.set_content(pixmap, None)
478
+ self.viewer.fit_to_window()
479
+ layout.addWidget(self.viewer)
480
+
481
+ def showEvent(self, event):
482
+ self.viewer.fit_to_window()
483
+ super().showEvent(event)
484
+
485
+ class ResizableImage(QWidget):
486
+ def __init__(self, parent=None, title=""):
487
+ super().__init__(parent)
488
+ self.pixmap = None
489
+ self.title = title
490
+ self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
491
+ self.setMinimumHeight(150)
492
+ self.setCursor(Qt.PointingHandCursor)
493
+ self.setToolTip("Double click to enlarge (Popup)")
494
+
495
+ def set_image(self, pixmap):
496
+ self.pixmap = pixmap
497
+ self.update()
498
+
499
+ def set_title(self, title: str):
500
+ self.title = title
501
+ self.update()
502
+
503
+ def paintEvent(self, event):
504
+ painter = QPainter(self)
505
+ painter.fillRect(self.rect(), QColor(25, 25, 25))
506
+ painter.setPen(Qt.white)
507
+ painter.drawText(10, 20, self.title)
508
+ if self.pixmap:
509
+ target = self.rect().adjusted(0, 25, 0, 0)
510
+ scaled = self.pixmap.scaled(target.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
511
+ x = target.x() + (target.width() - scaled.width()) // 2
512
+ y = target.y() + (target.height() - scaled.height()) // 2
513
+ painter.drawPixmap(x, y, scaled)
514
+
515
+ def mouseDoubleClickEvent(self, event):
516
+ if self.pixmap:
517
+ self.pop = PopupImageDialog(self.pixmap, self.title, self)
518
+ self.pop.show()
519
+
520
+ class PixelHistogramDialog(QDialog):
521
+ def __init__(self, parent=None):
522
+ super().__init__(parent)
523
+ self.setWindowTitle("Pixel Histogram Inspector")
524
+ self.resize(600, 450)
525
+ self.setWindowFlags(Qt.Window)
526
+ layout = QVBoxLayout(self)
527
+ self.fig = Figure(figsize=(5, 4), dpi=100)
528
+ self.canvas = FigureCanvas(self.fig)
529
+ self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
530
+ layout.addWidget(self.canvas)
531
+ self.ax = self.fig.add_subplot(111)
532
+ self.status_label = QLabel("Switch tool to 'Inspect' and click pixel.")
533
+ layout.addWidget(self.status_label)
534
+
535
+ def update_plot(self, x, y, raw_vec, labels_info, noise_floor=0):
536
+ self.ax.clear()
537
+ self.ax.plot(raw_vec, color='black', linewidth=1.0, label='Photon Counts')
538
+ max_val = np.max(raw_vec) if raw_vec.size > 0 else 1.0
539
+ drawn_labels = set()
540
+ for item in labels_info:
541
+ cid = item['cid']
542
+ l_range, r_range = item['range']
543
+ rgb = item['color']
544
+ c_norm = (rgb[0]/255.0, rgb[1]/255.0, rgb[2]/255.0)
545
+ x_vals = np.arange(l_range, r_range + 1)
546
+ if x_vals.size > 0:
547
+ label_text = f"Class {cid}"
548
+ if cid not in drawn_labels:
549
+ self.ax.fill_between(x_vals, 0, max_val * 1.1, color=c_norm, alpha=0.3, label=label_text)
550
+ drawn_labels.add(cid)
551
+ else:
552
+ self.ax.fill_between(x_vals, 0, max_val * 1.1, color=c_norm, alpha=0.3)
553
+ if noise_floor > 0:
554
+ self.ax.axhline(y=noise_floor, color='gray', linestyle='--', alpha=0.5, label='Noise Level')
555
+ self.ax.set_title(f"Pixel ({x}, {y}) | Max: {max_val:.1f}")
556
+ self.ax.set_xlabel("Time Bins")
557
+ self.ax.set_ylabel("Counts")
558
+ self.ax.grid(True, linestyle=':', alpha=0.6)
559
+ if drawn_labels:
560
+ self.ax.legend(loc='upper right')
561
+ self.canvas.draw()
562
+ self.status_label.setText(f"Inspecting Pixel: x={x}, y={y}")
563
+
564
+
565
+ # ==========================================
566
+ # Main window
567
+ # ==========================================
568
+ class SPADLabelerPixel(QMainWindow):
569
+ def __init__(self, args):
570
+ super().__init__()
571
+ self.args = args
572
+ self.setWindowTitle("SPAD Labeler - Sequential Peak Annotation")
573
+ self.resize(1780, 1040)
574
+ os.makedirs(self.args.cache_dir, exist_ok=True)
575
+
576
+ self.H, self.W = AppConfig.IMG_H, AppConfig.IMG_W
577
+ self.num_layers = AppConfig.NUM_LAYERS
578
+ self.class_names = {i + 1: name for i, name in enumerate(AppConfig.CLASS_LABELS)}
579
+ self.UNKNOWN_CID = int(max(self.class_names.keys()))
580
+ self.class_colors_rgb = CLASS_COLORS
581
+
582
+ self.raw_data = None
583
+ self.noise_map = None
584
+ self.layer_view_cache = {}
585
+
586
+ self.manual_masks = [np.zeros((self.H, self.W), dtype=np.uint8) for _ in range(self.num_layers)]
587
+ self.layer_thresholds = [None for _ in range(self.num_layers)]
588
+
589
+ self.undo_stack = deque(maxlen=20)
590
+ self.is_dirty = False
591
+ self.mask_revision = 0
592
+ self.brush_size = 5
593
+ self.tool_mode = "pick"
594
+ self.current_class = 1
595
+ self.peel_depth = 0
596
+ self.edit_layer = 0
597
+ self.region_step = 0
598
+ self.peel_by_class = True
599
+ self._region_cache_layer = None
600
+ self._region_cache_revision = -1
601
+ self._region_cache_mode = None
602
+ self._region_cache_regions = []
603
+
604
+ self.wand_tolerance = int(AppConfig.DEFAULT_WAND_TOLERANCE)
605
+ self.wand_connectivity_8 = bool(AppConfig.DEFAULT_WAND_CONNECTIVITY_8)
606
+ self.wand_edge_aware = bool(AppConfig.DEFAULT_WAND_EDGE_AWARE)
607
+ self.wand_edge_high = int(AppConfig.DEFAULT_WAND_EDGE_HIGH)
608
+
609
+ self.converter_thread = None
610
+ self.hist_inspector = None
611
+
612
+ self.init_ui()
613
+
614
+ self.file_list = sorted(glob(os.path.join(args.in_dir, args.pattern)))
615
+ self.current_file_idx = 0
616
+ self.update_file_list_ui()
617
+ if self.file_list:
618
+ self.load_file(self.file_list[0])
619
+
620
+ # ---------------- UI ----------------
621
+ def init_ui(self):
622
+ self.splitter = QSplitter(Qt.Horizontal)
623
+ self.setCentralWidget(self.splitter)
624
+
625
+ self.left_panel = QSplitter(Qt.Vertical)
626
+ self.lbl_global = ResizableImage(title="Layer 0 (Raw Peak)")
627
+ self.left_panel.addWidget(self.lbl_global)
628
+ self.lbl_result = ResizableImage(title="Annotation Preview (Unpeeled + Current Region State)")
629
+ self.left_panel.addWidget(self.lbl_result)
630
+ self.lbl_info = ResizableImage(title="Peeling View")
631
+ self.left_panel.addWidget(self.lbl_info)
632
+ self.lbl_depth = ResizableImage(title="Depth Map (Visible Peak)")
633
+ self.left_panel.addWidget(self.lbl_depth)
634
+
635
+ self.left_ctrl = QWidget()
636
+ l_lay = QVBoxLayout(self.left_ctrl)
637
+ l_lay.addWidget(QLabel("<b>Peel / Edit / Region Control</b>"))
638
+ l_lay.addWidget(QLabel("<i>Tip: Double-click images above to enlarge.</i>"))
639
+
640
+ l_lay.addWidget(QLabel("Peel Depth (display stage):"))
641
+ self.sl_peel = QSlider(Qt.Horizontal)
642
+ self.sl_peel.setRange(0, self.num_layers)
643
+ self.sl_peel.setValue(0)
644
+ self.sl_peel.valueChanged.connect(self.change_peel_depth)
645
+ l_lay.addWidget(self.sl_peel)
646
+
647
+ self.lbl_region = QLabel("Semantic Step (current peeled layer): 0 / 0")
648
+ l_lay.addWidget(self.lbl_region)
649
+ self.sl_region = QSlider(Qt.Horizontal)
650
+ self.sl_region.setRange(0, 0)
651
+ self.sl_region.setValue(0)
652
+ self.sl_region.valueChanged.connect(self.change_region_step)
653
+ l_lay.addWidget(self.sl_region)
654
+
655
+ self.lbl_next_region = QLabel("Selected Peel Target: -")
656
+ self.lbl_next_region.setWordWrap(True)
657
+ l_lay.addWidget(self.lbl_next_region)
658
+
659
+ l_lay.addWidget(QLabel("Edit Layer (write target):"))
660
+ self.sl_edit = QSlider(Qt.Horizontal)
661
+ self.sl_edit.setRange(0, self.num_layers - 1)
662
+ self.sl_edit.setValue(0)
663
+ self.sl_edit.valueChanged.connect(self.change_edit_layer)
664
+ l_lay.addWidget(self.sl_edit)
665
+
666
+ self.chk_auto_edit = QCheckBox("Auto Edit Layer = Peel Depth (recommended)")
667
+ self.chk_auto_edit.setChecked(True)
668
+ self.chk_auto_edit.toggled.connect(self.on_auto_edit_toggled)
669
+ l_lay.addWidget(self.chk_auto_edit)
670
+
671
+ self.chk_lock_to_visible = QCheckBox("Lock labeling to visible peak")
672
+ self.chk_lock_to_visible.setChecked(True)
673
+ self.chk_lock_to_visible.toggled.connect(self.update_all_views)
674
+ l_lay.addWidget(self.chk_lock_to_visible)
675
+
676
+ self.chk_focus_edit = QCheckBox("Focus view to Edit Layer")
677
+ self.chk_focus_edit.setChecked(True)
678
+ self.chk_focus_edit.toggled.connect(self.update_all_views)
679
+ l_lay.addWidget(self.chk_focus_edit)
680
+
681
+ self.chk_peel_class = QCheckBox("Region Step by Semantic")
682
+ self.chk_peel_class.setChecked(True)
683
+ self.chk_peel_class.toggled.connect(self.on_peel_mode_changed)
684
+ l_lay.addWidget(self.chk_peel_class)
685
+
686
+ self.lbl_state = QLabel("Peel Depth: 0 | Region Step: 0 | Edit Layer: 0")
687
+ l_lay.addWidget(self.lbl_state)
688
+ self.lbl_peeled_ids = QLabel("Fully Peeled Layers: None")
689
+ self.lbl_peeled_ids.setStyleSheet("color: #FFA500; font-weight: bold;")
690
+ l_lay.addWidget(self.lbl_peeled_ids)
691
+ self.btn_clear_layer_thr = QPushButton("Clear Layer Threshold Locks")
692
+ self.btn_clear_layer_thr.clicked.connect(self.clear_layer_threshold_locks)
693
+ l_lay.addWidget(self.btn_clear_layer_thr)
694
+
695
+ l_lay.addStretch()
696
+ self.left_panel.addWidget(self.left_ctrl)
697
+ self.left_panel.setSizes([220, 220, 220, 220, 300])
698
+ self.splitter.addWidget(self.left_panel)
699
+
700
+ self.canvas = CenteredCanvas()
701
+ self.canvas.action_callback = self.handle_canvas_action
702
+ self.splitter.addWidget(self.canvas)
703
+
704
+ self.right_panel = QWidget()
705
+ r_lay = QVBoxLayout(self.right_panel)
706
+
707
+ r_lay.addWidget(QLabel("<b>File List:</b>"))
708
+ self.file_list_widget = QListWidget()
709
+ self.file_list_widget.setFixedHeight(200)
710
+ self.file_list_widget.currentRowChanged.connect(self.on_file_list_clicked)
711
+ r_lay.addWidget(self.file_list_widget)
712
+
713
+ r_lay.addWidget(QLabel("<b>Batch Convert Config:</b>"))
714
+ h_src = QHBoxLayout()
715
+ self.txt_source_edit = QLineEdit()
716
+ self.txt_source_edit.setText(self.args.in_dir)
717
+ self.txt_source_edit.setPlaceholderText("Path to folder with TXT files...")
718
+ btn_browse_src = QPushButton("...")
719
+ btn_browse_src.setFixedWidth(30)
720
+ btn_browse_src.clicked.connect(self.browse_txt_source)
721
+ h_src.addWidget(self.txt_source_edit)
722
+ h_src.addWidget(btn_browse_src)
723
+ r_lay.addLayout(h_src)
724
+
725
+ self.btn_convert = QPushButton("Batch Convert TXT -> NPY")
726
+ self.btn_convert.setStyleSheet("background-color: #3d3d3d; color: #aaffaa;")
727
+ self.btn_convert.clicked.connect(self.start_batch_conversion)
728
+ r_lay.addWidget(self.btn_convert)
729
+ self.pbar = QProgressBar()
730
+ self.pbar.setVisible(False)
731
+ r_lay.addWidget(self.pbar)
732
+
733
+ h_nav = QHBoxLayout()
734
+ btn_pl = QPushButton("Peel -1 (A)")
735
+ btn_pl.clicked.connect(self.apply_peel_prev)
736
+ btn_nl = QPushButton("Peel +1 (D)")
737
+ btn_nl.clicked.connect(self.apply_peel_next)
738
+ h_nav.addWidget(btn_pl)
739
+ h_nav.addWidget(btn_nl)
740
+ r_lay.addLayout(h_nav)
741
+
742
+ h_reg = QHBoxLayout()
743
+ btn_rprev = QPushButton("Region -1 (Z)")
744
+ btn_rprev.clicked.connect(self.region_prev)
745
+ btn_rnext = QPushButton("Region +1 (X)")
746
+ btn_rnext.clicked.connect(self.region_next)
747
+ h_reg.addWidget(btn_rprev)
748
+ h_reg.addWidget(btn_rnext)
749
+ r_lay.addLayout(h_reg)
750
+
751
+ h_edit = QHBoxLayout()
752
+ btn_el = QPushButton("Edit -1 (Shift+A)")
753
+ btn_el.clicked.connect(self.edit_prev)
754
+ btn_er = QPushButton("Edit +1 (Shift+D)")
755
+ btn_er.clicked.connect(self.edit_next)
756
+ h_edit.addWidget(btn_el)
757
+ h_edit.addWidget(btn_er)
758
+ r_lay.addLayout(h_edit)
759
+
760
+ h_file = QHBoxLayout()
761
+ btn_pf = QPushButton("<< File")
762
+ btn_pf.clicked.connect(self.prev_file)
763
+ btn_nf = QPushButton("File >>")
764
+ btn_nf.clicked.connect(self.next_file)
765
+ h_file.addWidget(btn_pf)
766
+ h_file.addWidget(btn_nf)
767
+ r_lay.addLayout(h_file)
768
+
769
+ self.chk_autosave = QCheckBox("Auto Save")
770
+ self.chk_autosave.setChecked(True)
771
+ r_lay.addWidget(self.chk_autosave)
772
+
773
+ h_viz = QHBoxLayout()
774
+ self.chk_ghost = QCheckBox("Ghost (G)")
775
+ self.chk_ghost.toggled.connect(self.update_all_views)
776
+ self.chk_hide = QCheckBox("Hide (H)")
777
+ self.chk_hide.toggled.connect(self.update_all_views)
778
+ btn_viz = QPushButton("3D Depth")
779
+ btn_viz.clicked.connect(self.visualize_3d_point_cloud)
780
+ btn_sem = QPushButton("3D Semantic")
781
+ btn_sem.clicked.connect(self.visualize_3d_semantic_point_cloud)
782
+
783
+ # [RESTORED] 3D Bins Button
784
+ btn_bins = QPushButton("3D Bins")
785
+ btn_bins.clicked.connect(self.visualize_3d_semantic_bins_point_cloud)
786
+
787
+ btn_hist = QPushButton("Pixel Hist")
788
+ btn_hist.clicked.connect(self.open_pixel_inspector)
789
+
790
+ h_viz.addWidget(self.chk_ghost)
791
+ h_viz.addWidget(self.chk_hide)
792
+ h_viz.addWidget(btn_viz)
793
+ h_viz.addWidget(btn_sem)
794
+ h_viz.addWidget(btn_bins) # Add back
795
+ h_viz.addWidget(btn_hist)
796
+ r_lay.addLayout(h_viz)
797
+
798
+ g_filt = QGroupBox("Filter (Threshold & SNR)")
799
+ f_lay = QVBoxLayout(g_filt)
800
+ self.sl_thresh = QSlider(Qt.Horizontal)
801
+ self.sl_thresh.setRange(0, 2000)
802
+ self.sl_thresh.setValue(AppConfig.DEFAULT_SIGNAL_THRESHOLD)
803
+ self.lbl_thr = QLabel(f"Int Thresh: {AppConfig.DEFAULT_SIGNAL_THRESHOLD}")
804
+ self.sl_thresh.valueChanged.connect(self.on_thresh_changed)
805
+ h_t = QHBoxLayout()
806
+ h_t.addWidget(self.sl_thresh)
807
+ h_t.addWidget(self.lbl_thr)
808
+ f_lay.addLayout(h_t)
809
+ self.sl_snr = QSlider(Qt.Horizontal)
810
+ self.sl_snr.setRange(10, 200)
811
+ self.sl_snr.setValue(int(AppConfig.DEFAULT_SNR_THRESHOLD * 10))
812
+ self.lbl_snr = QLabel(f"SNR (Peak/Mean) > {AppConfig.DEFAULT_SNR_THRESHOLD:.1f}")
813
+ self.sl_snr.valueChanged.connect(self.on_snr_changed)
814
+ h_s = QHBoxLayout()
815
+ h_s.addWidget(self.sl_snr)
816
+ h_s.addWidget(self.lbl_snr)
817
+ f_lay.addLayout(h_s)
818
+ r_lay.addWidget(g_filt)
819
+
820
+ g_wand = QGroupBox("Magic Wand (传统魔棒)")
821
+ w_lay = QVBoxLayout(g_wand)
822
+ self.chk_wand_edge = QCheckBox("Edge-aware")
823
+ self.chk_wand_edge.setChecked(self.wand_edge_aware)
824
+ self.chk_wand_edge.toggled.connect(self.on_wand_params_changed)
825
+ w_lay.addWidget(self.chk_wand_edge)
826
+ self.chk_wand_conn8 = QCheckBox("8-way connectivity")
827
+ self.chk_wand_conn8.setChecked(self.wand_connectivity_8)
828
+ self.chk_wand_conn8.toggled.connect(self.on_wand_params_changed)
829
+ w_lay.addWidget(self.chk_wand_conn8)
830
+ w_lay.addWidget(QLabel("Tolerance:"))
831
+ self.sl_wand_tol = QSlider(Qt.Horizontal)
832
+ self.sl_wand_tol.setRange(0, 255)
833
+ self.sl_wand_tol.setValue(self.wand_tolerance)
834
+ self.sl_wand_tol.valueChanged.connect(self.on_wand_tol_changed)
835
+ self.lbl_wand_tol = QLabel(str(self.wand_tolerance))
836
+ h_tol = QHBoxLayout()
837
+ h_tol.addWidget(self.sl_wand_tol)
838
+ h_tol.addWidget(self.lbl_wand_tol)
839
+ w_lay.addLayout(h_tol)
840
+ w_lay.addWidget(QLabel("Edge strength:"))
841
+ self.sl_wand_edge = QSlider(Qt.Horizontal)
842
+ self.sl_wand_edge.setRange(0, 255)
843
+ self.sl_wand_edge.setValue(self.wand_edge_high)
844
+ self.sl_wand_edge.valueChanged.connect(self.on_wand_edge_changed)
845
+ self.lbl_wand_edge = QLabel(str(self.wand_edge_high))
846
+ h_ed = QHBoxLayout()
847
+ h_ed.addWidget(self.sl_wand_edge)
848
+ h_ed.addWidget(self.lbl_wand_edge)
849
+ w_lay.addLayout(h_ed)
850
+ r_lay.addWidget(g_wand)
851
+
852
+ g_tool = QGroupBox("Tools")
853
+ t_lay = QVBoxLayout(g_tool)
854
+ self.rb_pick = QRadioButton("Pick (Q)")
855
+ self.rb_pick.setChecked(True)
856
+ self.rb_pick.toggled.connect(self.update_tool_mode)
857
+ self.rb_brush = QRadioButton("Brush (W)")
858
+ self.rb_brush.toggled.connect(self.update_tool_mode)
859
+ self.rb_eraser = QRadioButton("Eraser (E)")
860
+ self.rb_eraser.toggled.connect(self.update_tool_mode)
861
+
862
+ # [NEW] Inspect Mode
863
+ self.rb_inspect = QRadioButton("Inspect (I)")
864
+ self.rb_inspect.toggled.connect(self.update_tool_mode)
865
+
866
+ t_lay.addWidget(self.rb_pick)
867
+ t_lay.addWidget(self.rb_brush)
868
+ t_lay.addWidget(self.rb_eraser)
869
+ t_lay.addWidget(self.rb_inspect)
870
+
871
+ h_sz = QHBoxLayout()
872
+ h_sz.addWidget(QLabel("Brush Size:"))
873
+ self.sl_size = QSlider(Qt.Horizontal)
874
+ self.sl_size.setRange(1, 30)
875
+ self.sl_size.setValue(self.brush_size)
876
+ self.lbl_size = QLabel(str(self.brush_size))
877
+ self.sl_size.valueChanged.connect(self.update_brush_size)
878
+ h_sz.addWidget(self.sl_size)
879
+ h_sz.addWidget(self.lbl_size)
880
+ t_lay.addLayout(h_sz)
881
+ self.chk_overwrite = QCheckBox("Allow Overwrite (允许覆盖)")
882
+ self.chk_overwrite.setChecked(True)
883
+ t_lay.addWidget(self.chk_overwrite)
884
+ r_lay.addWidget(g_tool)
885
+
886
+ g_cls = QGroupBox("Classes")
887
+ scroll = QScrollArea()
888
+ scroll.setWidgetResizable(True)
889
+ content = QWidget()
890
+ sc_lay = QVBoxLayout(content)
891
+ self.cls_bg = QButtonGroup(self)
892
+ self.cls_radios = {}
893
+ for cid, name in self.class_names.items():
894
+ rgb = self.class_colors_rgb.get(cid, (0, 0, 0))
895
+ rb = QRadioButton(f"■ {name}")
896
+ rb.setStyleSheet(f"color: rgb{rgb}; font-weight: bold;")
897
+ self.cls_bg.addButton(rb, cid)
898
+ self.cls_radios[cid] = rb
899
+ sc_lay.addWidget(rb)
900
+ scroll.setWidget(content)
901
+ c_lay = QVBoxLayout(g_cls)
902
+ c_lay.addWidget(scroll)
903
+ r_lay.addWidget(g_cls)
904
+ self.cls_bg.buttonClicked[int].connect(lambda i: setattr(self, "current_class", int(i)))
905
+
906
+ self.log_win = QTextEdit()
907
+ self.log_win.setReadOnly(True)
908
+ self.log_win.setFixedHeight(100)
909
+ r_lay.addWidget(self.log_win)
910
+
911
+ btn_unk = QPushButton("Fill Unknown (Layer U)")
912
+ btn_unk.clicked.connect(self.fill_unknown_current_layer)
913
+ r_lay.addWidget(btn_unk)
914
+ btn_save = QPushButton("SAVE (Ctrl+S)")
915
+ btn_save.clicked.connect(self.save_current)
916
+ r_lay.addWidget(btn_save)
917
+
918
+ self.splitter.addWidget(self.right_panel)
919
+ self.splitter.setSizes([430, 980, 340])
920
+
921
+ self.init_shortcuts()
922
+ self.hist_inspector = PixelHistogramDialog(self)
923
+
924
+ def init_shortcuts(self):
925
+ QShortcut(QKeySequence("A"), self, self.apply_peel_prev)
926
+ QShortcut(QKeySequence("D"), self, self.apply_peel_next)
927
+ QShortcut(QKeySequence("Z"), self, self.region_prev)
928
+ QShortcut(QKeySequence("X"), self, self.region_next)
929
+ QShortcut(QKeySequence("Shift+A"), self, self.edit_prev)
930
+ QShortcut(QKeySequence("Shift+D"), self, self.edit_next)
931
+ QShortcut(QKeySequence("Left"), self, self.prev_file)
932
+ QShortcut(QKeySequence("Right"), self, self.next_file)
933
+ QShortcut(QKeySequence("Q"), self, lambda: self.rb_pick.setChecked(True))
934
+ QShortcut(QKeySequence("W"), self, lambda: self.rb_brush.setChecked(True))
935
+ QShortcut(QKeySequence("E"), self, lambda: self.rb_eraser.setChecked(True))
936
+ # [NEW] Shortcut for Inspect
937
+ QShortcut(QKeySequence("I"), self, lambda: self.rb_inspect.setChecked(True))
938
+
939
+ QShortcut(QKeySequence("Ctrl+S"), self, self.save_current)
940
+ QShortcut(QKeySequence("Ctrl+Z"), self, self.undo)
941
+ QShortcut(QKeySequence("U"), self, self.fill_unknown_current_layer)
942
+ QShortcut(QKeySequence("H"), self, lambda: self.chk_hide.setChecked(not self.chk_hide.isChecked()))
943
+ QShortcut(QKeySequence("G"), self, lambda: self.chk_ghost.setChecked(not self.chk_ghost.isChecked()))
944
+ QShortcut(QKeySequence("F"), self, lambda: self.chk_focus_edit.setChecked(not self.chk_focus_edit.isChecked()))
945
+ QShortcut(QKeySequence("T"), self, lambda: self.chk_lock_to_visible.setChecked(not self.chk_lock_to_visible.isChecked()))
946
+ QShortcut(QKeySequence("R"), self, lambda: self.chk_peel_class.setChecked(not self.chk_peel_class.isChecked()))
947
+ QShortcut(QKeySequence("["), self, self.cycle_class_prev)
948
+ QShortcut(QKeySequence("]"), self, self.cycle_class_next)
949
+ QShortcut(QKeySequence("="), self, lambda: self.morph_current_mask("dilate"))
950
+ QShortcut(QKeySequence("-"), self, lambda: self.morph_current_mask("erode"))
951
+
952
+ keys = [Qt.Key_1, Qt.Key_2, Qt.Key_3, Qt.Key_4, Qt.Key_5,
953
+ Qt.Key_6, Qt.Key_7, Qt.Key_8, Qt.Key_9, Qt.Key_0]
954
+ for i, key in enumerate(keys):
955
+ cls_idx = i + 1
956
+ if cls_idx in self.class_names:
957
+ QShortcut(QKeySequence(key), self, lambda idx=cls_idx: self.set_class_by_key(idx))
958
+
959
+ # ---------------- UI Helper Methods ----------------
960
+ def browse_txt_source(self):
961
+ directory = QFileDialog.getExistingDirectory(
962
+ self, "Select TXT Source Directory", self.txt_source_edit.text()
963
+ )
964
+ if directory:
965
+ self.txt_source_edit.setText(directory)
966
+
967
+ # ---------------- Pixel Inspector ----------------
968
+ def open_pixel_inspector(self):
969
+ if self.hist_inspector is None:
970
+ self.hist_inspector = PixelHistogramDialog(self)
971
+ self.hist_inspector.show()
972
+ self.hist_inspector.raise_()
973
+ self.hist_inspector.activateWindow()
974
+ # Auto switch to inspect mode for convenience? Optional.
975
+ # self.rb_inspect.setChecked(True)
976
+
977
+ def update_histogram_inspector(self, x, y):
978
+ if self.hist_inspector is None or not self.hist_inspector.isVisible():
979
+ # If closed, re-open
980
+ self.open_pixel_inspector()
981
+
982
+ if self.raw_data is None: return
983
+ idx = y * self.W + x
984
+ if idx >= self.raw_data.shape[0]: return
985
+ raw_vec = self.raw_data[idx]
986
+ labels_info = self.simulate_pixel_peeling(x, y, raw_vec)
987
+ noise = self.noise_map[y, x] if self.noise_map is not None else 0
988
+ self.hist_inspector.update_plot(x, y, raw_vec, labels_info, noise)
989
+
990
+ def simulate_pixel_peeling(self, x, y, raw_vec):
991
+ labels_info = []
992
+ working_vec = raw_vec.copy()
993
+ curr_thr = int(self.sl_thresh.value())
994
+ for l in range(self.num_layers):
995
+ m = self.manual_masks[l]
996
+ cid = int(m[y, x])
997
+ if cid > 0:
998
+ thr = self.layer_thresholds[l] if self.layer_thresholds[l] is not None else curr_thr
999
+ if np.max(working_vec) > thr:
1000
+ peak_idx = int(np.argmax(working_vec))
1001
+ (l_lab, r_lab), (l_rem, r_rem) = analyze_peak_structure(working_vec, peak_idx, thr)
1002
+ if r_lab >= l_lab:
1003
+ color = self.class_colors_rgb.get(cid, (128, 128, 128))
1004
+ labels_info.append({'cid': cid, 'range': (l_lab, r_lab), 'color': color})
1005
+ if r_rem > l_rem:
1006
+ working_vec[l_rem:r_rem + 1] = 0
1007
+ return labels_info
1008
+
1009
+ # ... [Batch Conversion methods kept same] ...
1010
+ def start_batch_conversion(self):
1011
+ if self.converter_thread is not None and self.converter_thread.isRunning(): return
1012
+ target_dir = self.txt_source_edit.text().strip()
1013
+ if not target_dir or not os.path.isdir(target_dir):
1014
+ QMessageBox.warning(self, "Invalid Path", "Please select a valid directory containing TXT files.")
1015
+ return
1016
+ script_dir = os.path.dirname(os.path.abspath(__file__))
1017
+ output_npy_dir = os.path.join(script_dir, "npy")
1018
+ reply = QMessageBox.question(self, 'Batch Convert',
1019
+ f"Convert TXT files from:\n{target_dir}\n\nTo NPY files in:\n{output_npy_dir} ?",
1020
+ QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
1021
+ if reply == QMessageBox.No: return
1022
+ self.btn_convert.setEnabled(False)
1023
+ self.pbar.setVisible(True)
1024
+ self.pbar.setValue(0)
1025
+ self.log_win.append(f"Starting batch conversion...")
1026
+ self.converter_thread = BatchConverterThread(target_dir, output_npy_dir)
1027
+ self.converter_thread.progress_signal.connect(self.on_conversion_progress)
1028
+ self.converter_thread.log_signal.connect(self.log_win.append)
1029
+ self.converter_thread.finished_signal.connect(self.on_conversion_finished)
1030
+ self.converter_thread.start()
1031
+
1032
+ def on_conversion_progress(self, current, total):
1033
+ self.pbar.setMaximum(total)
1034
+ self.pbar.setValue(current)
1035
+
1036
+ def on_conversion_finished(self, success, skip, error):
1037
+ self.log_win.append(f"Conversion Done! Success: {success}, Skipped: {skip}, Errors: {error}")
1038
+ self.pbar.setVisible(False)
1039
+ self.btn_convert.setEnabled(True)
1040
+ source_dir = self.txt_source_edit.text().strip()
1041
+ output_npy_dir = os.path.join(source_dir, "npy")
1042
+ if os.path.abspath(self.args.in_dir) == os.path.abspath(output_npy_dir):
1043
+ self.file_list = sorted(glob(os.path.join(self.args.in_dir, self.args.pattern)))
1044
+ self.update_file_list_ui()
1045
+
1046
+ # ---------------- Magic Wand/Tools ----------------
1047
+ def on_wand_params_changed(self, _=None):
1048
+ self.wand_edge_aware = bool(self.chk_wand_edge.isChecked())
1049
+ self.wand_connectivity_8 = bool(self.chk_wand_conn8.isChecked())
1050
+
1051
+ def on_wand_tol_changed(self, v):
1052
+ self.wand_tolerance = int(v)
1053
+ self.lbl_wand_tol.setText(str(int(v)))
1054
+
1055
+ def on_wand_edge_changed(self, v):
1056
+ self.wand_edge_high = int(v)
1057
+ self.lbl_wand_edge.setText(str(int(v)))
1058
+
1059
+ # ... [State helpers kept same] ...
1060
+ def clear_layer_cache(self): self.layer_view_cache.clear()
1061
+ def set_dirty(self):
1062
+ self.clear_layer_cache()
1063
+ self.is_dirty = True
1064
+ self.mask_revision += 1
1065
+ if " *" not in self.windowTitle(): self.setWindowTitle(self.windowTitle() + " *")
1066
+ def push_undo(self):
1067
+ stack = np.stack(self.manual_masks, axis=0).copy()
1068
+ thr = list(self.layer_thresholds)
1069
+ self.undo_stack.append((stack, thr, self.peel_depth, self.region_step, self.edit_layer, self.peel_by_class))
1070
+ def clear_layer_threshold_locks(self):
1071
+ self.layer_thresholds = [None for _ in range(self.num_layers)]
1072
+ self.clear_layer_cache()
1073
+ self.update_all_views()
1074
+ def _clamp_xy(self, x, y):
1075
+ x = max(0, min(int(x), self.W - 1))
1076
+ y = max(0, min(int(y), self.H - 1))
1077
+ return x, y
1078
+ def _ensure_layer_threshold(self, layer_idx: int):
1079
+ if self.layer_thresholds[layer_idx] is None:
1080
+ self.layer_thresholds[layer_idx] = int(self.sl_thresh.value())
1081
+
1082
+ def update_brush_size(self, val):
1083
+ self.brush_size = int(val)
1084
+ self.lbl_size.setText(str(self.brush_size))
1085
+
1086
+ def on_thresh_changed(self, v):
1087
+ self.clear_layer_cache()
1088
+ self.update_all_views()
1089
+ self.lbl_thr.setText(f"Int Thresh: {int(v)}")
1090
+
1091
+ def on_snr_changed(self, v):
1092
+ val = float(v) / 10.0
1093
+ self.lbl_snr.setText(f"SNR > {val:.1f}")
1094
+ self.clear_layer_cache()
1095
+ self.update_all_views()
1096
+
1097
+ def update_tool_mode(self):
1098
+ # Determine mode
1099
+ if self.rb_pick.isChecked(): self.tool_mode = "pick"
1100
+ elif self.rb_brush.isChecked(): self.tool_mode = "brush"
1101
+ elif self.rb_eraser.isChecked(): self.tool_mode = "eraser"
1102
+ elif self.rb_inspect.isChecked(): self.tool_mode = "inspect"
1103
+
1104
+ # Set canvas visual mode (inspect shares pick cursor logic, but handled differently in click)
1105
+ if self.tool_mode in ["brush", "eraser"]:
1106
+ self.canvas.mode = "draw"
1107
+ else:
1108
+ self.canvas.mode = "pick"
1109
+
1110
+ # ... [Peel/Edit logic kept same] ...
1111
+ def on_auto_edit_toggled(self, checked):
1112
+ if checked: self._sync_edit_with_peel()
1113
+ self.update_all_views()
1114
+ def on_peel_mode_changed(self, checked):
1115
+ self.peel_by_class = bool(checked)
1116
+ self.region_step = 0
1117
+ self.clear_layer_cache()
1118
+ self._region_cache_layer = None
1119
+ self._region_cache_revision = -1
1120
+ self._region_cache_mode = None
1121
+ self._region_cache_regions = []
1122
+ self._sync_region_slider()
1123
+ self.update_all_views()
1124
+ def _sync_edit_with_peel(self):
1125
+ target = min(int(self.peel_depth), self.num_layers - 1)
1126
+ if int(self.edit_layer) != target:
1127
+ self.edit_layer = target
1128
+ self.sl_edit.blockSignals(True)
1129
+ self.sl_edit.setValue(self.edit_layer)
1130
+ self.sl_edit.blockSignals(False)
1131
+ def change_peel_depth(self, idx):
1132
+ self.peel_depth = int(idx)
1133
+ self.region_step = 0
1134
+ if self.chk_auto_edit.isChecked(): self._sync_edit_with_peel()
1135
+ self._sync_region_slider()
1136
+ self.update_all_views()
1137
+ def change_region_step(self, idx):
1138
+ self.region_step = int(idx)
1139
+ self.clear_layer_cache()
1140
+ self.update_all_views()
1141
+ def change_edit_layer(self, idx):
1142
+ self.edit_layer = int(idx)
1143
+ self.update_all_views()
1144
+ def apply_peel_next(self):
1145
+ self.peel_depth = min(self.num_layers, self.peel_depth + 1)
1146
+ self.region_step = 0
1147
+ self.sl_peel.blockSignals(True)
1148
+ self.sl_peel.setValue(self.peel_depth)
1149
+ self.sl_peel.blockSignals(False)
1150
+ if self.chk_auto_edit.isChecked(): self._sync_edit_with_peel()
1151
+ self._sync_region_slider()
1152
+ self.update_all_views()
1153
+ def apply_peel_prev(self):
1154
+ self.peel_depth = max(0, self.peel_depth - 1)
1155
+ self.region_step = 0
1156
+ self.sl_peel.blockSignals(True)
1157
+ self.sl_peel.setValue(self.peel_depth)
1158
+ self.sl_peel.blockSignals(False)
1159
+ if self.chk_auto_edit.isChecked(): self._sync_edit_with_peel()
1160
+ self._sync_region_slider()
1161
+ self.update_all_views()
1162
+ def region_next(self):
1163
+ maxv = self.sl_region.maximum()
1164
+ self.region_step = min(maxv, self.region_step + 1)
1165
+ self.sl_region.blockSignals(True)
1166
+ self.sl_region.setValue(self.region_step)
1167
+ self.sl_region.blockSignals(False)
1168
+ self.clear_layer_cache()
1169
+ self.update_all_views()
1170
+ def region_prev(self):
1171
+ self.region_step = max(0, self.region_step - 1)
1172
+ self.sl_region.blockSignals(True)
1173
+ self.sl_region.setValue(self.region_step)
1174
+ self.sl_region.blockSignals(False)
1175
+ self.clear_layer_cache()
1176
+ self.update_all_views()
1177
+ def edit_next(self):
1178
+ self.edit_layer = min(self.num_layers - 1, self.edit_layer + 1)
1179
+ self.sl_edit.blockSignals(True)
1180
+ self.sl_edit.setValue(self.edit_layer)
1181
+ self.sl_edit.blockSignals(False)
1182
+ self.update_all_views()
1183
+ def edit_prev(self):
1184
+ self.edit_layer = max(0, self.edit_layer - 1)
1185
+ self.sl_edit.blockSignals(True)
1186
+ self.sl_edit.setValue(self.edit_layer)
1187
+ self.sl_edit.blockSignals(False)
1188
+ self.update_all_views()
1189
+ def _get_peak_cmap_for_depth(self, peel_depth: int):
1190
+ name, cmap = PEAK_CMAPS[int(peel_depth) % len(PEAK_CMAPS)]
1191
+ return name, cmap
1192
+
1193
+ # ... [File list / Load Save ... same] ...
1194
+ def update_file_list_ui(self):
1195
+ self.file_list_widget.clear()
1196
+ for f in self.file_list:
1197
+ base = os.path.splitext(os.path.basename(f))[0]
1198
+ is_lbl = os.path.exists(os.path.join(self.args.out_root, f"{base}_semantic.npy"))
1199
+ item = QListWidgetItem(os.path.basename(f))
1200
+ if is_lbl:
1201
+ item.setForeground(QColor(0, 150, 0))
1202
+ font = item.font()
1203
+ font.setBold(True)
1204
+ item.setFont(font)
1205
+ item.setText(f"✔ {os.path.basename(f)}")
1206
+ self.file_list_widget.addItem(item)
1207
+ if 0 <= self.current_file_idx < len(self.file_list):
1208
+ self.file_list_widget.setCurrentRow(self.current_file_idx)
1209
+ def on_file_list_clicked(self, row):
1210
+ if row < 0 or row >= len(self.file_list): return
1211
+ if self.chk_autosave.isChecked() and self.is_dirty: self.save_current(silent=True)
1212
+ self.current_file_idx = int(row)
1213
+ self.load_file(self.file_list[self.current_file_idx])
1214
+ def prev_file(self): self.on_file_list_clicked(max(0, self.current_file_idx - 1))
1215
+ def next_file(self): self.on_file_list_clicked(min(len(self.file_list) - 1, self.current_file_idx + 1))
1216
+
1217
+ def load_file(self, path):
1218
+ QApplication.setOverrideCursor(Qt.WaitCursor)
1219
+ self.is_dirty = False
1220
+ try:
1221
+ self.undo_stack.clear()
1222
+ self.current_file_path = path
1223
+ self.setWindowTitle(f"SPAD Labeler - {os.path.basename(path)}")
1224
+ self.raw_data = load_hist_npy(path)
1225
+ if self.raw_data is None: return
1226
+ self.noise_map = np.mean(self.raw_data, axis=1).reshape(self.H, self.W)
1227
+ self.manual_masks = [np.zeros((self.H, self.W), dtype=np.uint8) for _ in range(self.num_layers)]
1228
+ self.layer_thresholds = [None for _ in range(self.num_layers)]
1229
+ self.layer_view_cache.clear()
1230
+ base = os.path.splitext(os.path.basename(path))[0]
1231
+ npy = os.path.join(self.args.out_root, f"{base}_semantic.npy")
1232
+ if os.path.exists(npy):
1233
+ try:
1234
+ d = np.load(npy)
1235
+ if d.ndim == 2 and d.shape[0] == self.H * self.W:
1236
+ self.manual_masks = sem_bins_to_layers(d.astype(np.uint8), self.H, self.W, self.num_layers)
1237
+ self.log_win.append("Loaded existing semantic.npy.")
1238
+ except Exception: pass
1239
+ self.peel_depth = 0
1240
+ self.edit_layer = 0
1241
+ self.region_step = 0
1242
+ self.peel_by_class = bool(self.chk_peel_class.isChecked())
1243
+ self.sl_peel.setValue(0)
1244
+ self.sl_edit.setValue(0)
1245
+ self._sync_region_slider()
1246
+ self.update_all_views()
1247
+ if self.hist_inspector and self.hist_inspector.isVisible():
1248
+ self.hist_inspector.ax.clear()
1249
+ self.hist_inspector.canvas.draw()
1250
+ except Exception as e:
1251
+ traceback.print_exc()
1252
+ finally:
1253
+ QApplication.restoreOverrideCursor()
1254
+
1255
+ def save_current(self, silent=False):
1256
+ if not self.is_dirty and not silent: return
1257
+ base = os.path.splitext(os.path.basename(self.current_file_path))[0]
1258
+ out = os.path.join(self.args.out_root, f"{base}_semantic.npy")
1259
+ ok, msg, _ = save_iterative_peeling_layers(out, self.raw_data, self.manual_masks, self.layer_thresholds, self.H, self.W, int(self.sl_thresh.value()))
1260
+ if ok:
1261
+ self.is_dirty = False
1262
+ self.setWindowTitle(f"SPAD Labeler - {os.path.basename(self.current_file_path)}")
1263
+ if not silent: self.log_win.append(msg)
1264
+ self.update_file_list_ui()
1265
+
1266
+ def closeEvent(self, event):
1267
+ if self.chk_autosave.isChecked() and self.is_dirty: self.save_current(silent=True)
1268
+ if self.hist_inspector: self.hist_inspector.close()
1269
+ event.accept()
1270
+
1271
+ # ... [Region calc/Peel calc/Display state... same] ...
1272
+ def _get_current_peeled_layer(self):
1273
+ if self.peel_depth <= 0: return None
1274
+ return self.peel_depth - 1
1275
+ def _compute_regions_for_layer(self, layer_idx: int, peel_by_class: bool):
1276
+ mask2d = self.manual_masks[layer_idx]
1277
+ regions = []
1278
+ if peel_by_class:
1279
+ flat = mask2d.reshape(-1)
1280
+ for cid in sorted(self.class_names.keys()):
1281
+ pix = np.flatnonzero(flat == cid)
1282
+ if pix.size == 0: continue
1283
+ regions.append({"cid": int(cid), "pixels": pix, "area": int(pix.size)})
1284
+ regions.sort(key=lambda r: (r["cid"],))
1285
+ return regions
1286
+ for cid in sorted(self.class_names.keys()):
1287
+ binary = (mask2d == cid).astype(np.uint8)
1288
+ if binary.sum() == 0: continue
1289
+ n, cc = cv2.connectedComponents(binary, connectivity=8)
1290
+ for k in range(1, n):
1291
+ pix = np.flatnonzero(cc.reshape(-1) == k)
1292
+ if pix.size == 0: continue
1293
+ regions.append({"cid": int(cid), "pixels": pix, "area": int(pix.size)})
1294
+ regions.sort(key=lambda r: (r["cid"], -r["area"]))
1295
+ return regions
1296
+ def _get_regions_cached(self, layer_idx: int):
1297
+ if layer_idx is None: return []
1298
+ mode = bool(self.peel_by_class)
1299
+ if (self._region_cache_layer == layer_idx and self._region_cache_revision == self.mask_revision and self._region_cache_mode == mode):
1300
+ return self._region_cache_regions
1301
+ regions = self._compute_regions_for_layer(layer_idx, peel_by_class=mode)
1302
+ self._region_cache_layer = layer_idx
1303
+ self._region_cache_revision = self.mask_revision
1304
+ self._region_cache_mode = mode
1305
+ self._region_cache_regions = regions
1306
+ return regions
1307
+ def _sync_region_slider(self):
1308
+ L = self._get_current_peeled_layer()
1309
+ if L is None:
1310
+ self.sl_region.blockSignals(True)
1311
+ self.sl_region.setRange(0, 0)
1312
+ self.sl_region.setValue(0)
1313
+ self.sl_region.blockSignals(False)
1314
+ self.lbl_region.setText("Semantic Step: 0 / 0")
1315
+ self.lbl_next_region.setText("Selected Peel Target: -")
1316
+ return
1317
+ regions = self._get_regions_cached(L)
1318
+ n = len(regions)
1319
+ self.region_step = max(0, min(self.region_step, n))
1320
+ self.sl_region.blockSignals(True)
1321
+ self.sl_region.setRange(0, n)
1322
+ self.sl_region.setValue(self.region_step)
1323
+ self.sl_region.blockSignals(False)
1324
+ self.lbl_region.setText(f"Semantic Step (Layer {L}): {self.region_step} / {n}")
1325
+ if n == 0: self.lbl_next_region.setText("Target: (no regions)")
1326
+ elif self.region_step == 0: self.lbl_next_region.setText("Target: (none)")
1327
+ else:
1328
+ rid = min(max(0, self.region_step - 1), n - 1)
1329
+ r = regions[rid]
1330
+ cname = self.class_names.get(int(r["cid"]), f"Class {r['cid']}")
1331
+ self.lbl_next_region.setText(f"Target: #{rid+1} | {cname} | area={r['area']}")
1332
+
1333
+ def _peel_pixels_peak_segment(self, working_data, pixel_indices, thr, peel_count=None):
1334
+ if pixel_indices is None or pixel_indices.size == 0: return
1335
+ for idx in pixel_indices:
1336
+ hist = working_data[idx]
1337
+ if np.max(hist) > thr:
1338
+ p_idx = int(np.argmax(hist))
1339
+ _, (l_rem, r_rem) = analyze_peak_structure(hist, p_idx, thr)
1340
+ if r_rem > l_rem:
1341
+ working_data[idx, l_rem:r_rem + 1] = 0
1342
+ if peel_count is not None: peel_count[idx] += 1
1343
+ def _build_working_hist_for_display(self, return_peel_count=False):
1344
+ working = self.raw_data.copy()
1345
+ curr_thr = int(self.sl_thresh.value())
1346
+ peel_count = None
1347
+ if return_peel_count: peel_count = np.zeros((self.H * self.W,), dtype=np.int16)
1348
+ if self.peel_depth <= 0: return (working, peel_count) if return_peel_count else working
1349
+ full_end = self.peel_depth - 1
1350
+ for l in range(0, max(0, full_end)):
1351
+ mask_flat = self.manual_masks[l].reshape(-1)
1352
+ pix = np.flatnonzero(mask_flat > 0)
1353
+ if pix.size == 0: continue
1354
+ thr = self.layer_thresholds[l] if self.layer_thresholds[l] is not None else curr_thr
1355
+ self._peel_pixels_peak_segment(working, pix, thr, peel_count=peel_count)
1356
+ L = self.peel_depth - 1
1357
+ thrL = self.layer_thresholds[L] if self.layer_thresholds[L] is not None else curr_thr
1358
+ regions = self._get_regions_cached(L)
1359
+ if len(regions) > 0 and self.region_step > 0:
1360
+ rid = min(max(0, self.region_step - 1), len(regions) - 1)
1361
+ self._peel_pixels_peak_segment(working, regions[rid]["pixels"], thrL, peel_count=peel_count)
1362
+ return (working, peel_count) if return_peel_count else working
1363
+ def get_display_state(self, return_peak_idx=False):
1364
+ key_thr = int(self.sl_thresh.value())
1365
+ lock_sig = tuple([(-1 if t is None else int(t)) for t in self.layer_thresholds[:max(0, self.peel_depth)]])
1366
+ key = (int(self.peel_depth), int(self.region_step), int(self.peel_by_class), key_thr, lock_sig, int(self.mask_revision), int(return_peak_idx))
1367
+ if key in self.layer_view_cache: return self.layer_view_cache[key]
1368
+ working, peel_count = self._build_working_hist_for_display(return_peel_count=True)
1369
+ raw2d = np.max(working, axis=1).reshape(self.H, self.W)
1370
+ peel2d = peel_count.reshape(self.H, self.W)
1371
+ if return_peak_idx:
1372
+ peak_idx2d = np.argmax(working, axis=1).reshape(self.H, self.W)
1373
+ self.layer_view_cache[key] = (raw2d, peel2d, peak_idx2d)
1374
+ return raw2d, peel2d, peak_idx2d
1375
+ self.layer_view_cache[key] = (raw2d, peel2d)
1376
+ return raw2d, peel2d
1377
+ def _get_valid_edit_mask(self, peel2d):
1378
+ if not self.chk_lock_to_visible.isChecked(): return np.ones((self.H, self.W), dtype=bool)
1379
+ return peel2d == int(self.edit_layer)
1380
+ def _get_snr_mask(self, current_intensity):
1381
+ if self.noise_map is None: return np.ones((self.H, self.W), dtype=bool)
1382
+ snr_map = current_intensity / (self.noise_map + 1e-6)
1383
+ return snr_map > (float(self.sl_snr.value()) / 10.0)
1384
+
1385
+ # ... [Combine layers/Split layers... same] ...
1386
+ def _combine_layers(self, l_start, l_end_exclusive):
1387
+ combined = np.zeros((self.H, self.W), dtype=np.uint8)
1388
+ for l in range(max(0, int(l_start)), min(self.num_layers, int(l_end_exclusive))):
1389
+ m = self.manual_masks[l]
1390
+ combined[m > 0] = m[m > 0]
1391
+ return combined
1392
+ def _split_partial_layer_by_region_step(self, layer_idx):
1393
+ peeled = np.zeros(self.H * self.W, dtype=np.uint8)
1394
+ unpeeled = np.zeros(self.H * self.W, dtype=np.uint8)
1395
+ if layer_idx is None: return peeled, unpeeled
1396
+ regions = self._get_regions_cached(layer_idx)
1397
+ if len(regions) == 0: return peeled, unpeeled
1398
+ if self.region_step <= 0:
1399
+ for r in regions: unpeeled[r["pixels"]] = np.uint8(r["cid"])
1400
+ return peeled, unpeeled
1401
+ sel = min(max(0, self.region_step - 1), len(regions) - 1)
1402
+ for rid, r in enumerate(regions):
1403
+ if rid == sel: peeled[r["pixels"]] = np.uint8(r["cid"])
1404
+ else: unpeeled[r["pixels"]] = np.uint8(r["cid"])
1405
+ return peeled, unpeeled
1406
+
1407
+ # ... [update_all_views ... same] ...
1408
+ def update_all_views(self):
1409
+ if self.raw_data is None: return
1410
+ self._sync_region_slider()
1411
+ L = self._get_current_peeled_layer()
1412
+ raw, peel2d, peak_idx2d = self.get_display_state(return_peak_idx=True)
1413
+ display_raw = raw.copy()
1414
+ snr_mask = self._get_snr_mask(display_raw)
1415
+ if self.chk_focus_edit.isChecked():
1416
+ display_raw[~self._get_valid_edit_mask(peel2d)] = 0
1417
+ display_raw[display_raw < int(self.sl_thresh.value())] = 0
1418
+ display_raw[~snr_mask] = 0
1419
+ norm = cv2.normalize(np.log1p(display_raw), None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
1420
+ cmap_name, cmap = self._get_peak_cmap_for_depth(self.peel_depth)
1421
+ self.lbl_info.set_image(safe_numpy_to_pixmap(cv2.applyColorMap(norm, cmap)))
1422
+
1423
+ depth_vis = peak_idx2d.astype(np.float32) * float(AppConfig.BIN_UNIT)
1424
+ valid = display_raw > 0
1425
+ depth_vis[~valid] = 0.0
1426
+ if np.any(valid):
1427
+ d = depth_vis[valid]
1428
+ lo, hi = float(np.percentile(d, 2)), float(np.percentile(d, 98))
1429
+ if hi <= lo: hi = lo + 1e-6
1430
+ dn = np.clip((depth_vis - lo) / (hi - lo), 0.0, 1.0)
1431
+ depth_col = cv2.applyColorMap((dn * 255.0).astype(np.uint8), _cv2_cmap("COLORMAP_TURBO", cv2.COLORMAP_JET))
1432
+ depth_col[~valid] = 0
1433
+ else: depth_col = np.zeros((self.H, self.W, 3), dtype=np.uint8)
1434
+ self.lbl_depth.set_image(safe_numpy_to_pixmap(depth_col))
1435
+
1436
+ l0_raw = np.max(self.raw_data, axis=1).reshape(self.H, self.W)
1437
+ n0 = cv2.normalize(np.log1p(l0_raw), None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
1438
+ self.lbl_global.set_image(safe_numpy_to_pixmap(cv2.applyColorMap(n0, _cv2_cmap("COLORMAP_MAGMA", cv2.COLORMAP_JET))))
1439
+
1440
+ unpeeled_mask = self._combine_layers(self.peel_depth, self.num_layers)
1441
+ ghost_mask = self._combine_layers(0, max(0, self.peel_depth - 1)) if self.chk_ghost.isChecked() else None
1442
+ pL, uL = self._split_partial_layer_by_region_step(L)
1443
+ if L is not None: unpeeled_mask[uL.reshape(self.H, self.W) > 0] = uL.reshape(self.H, self.W)[uL.reshape(self.H, self.W) > 0]
1444
+ if self.chk_ghost.isChecked() and L is not None and ghost_mask is not None:
1445
+ ghost_mask[pL.reshape(self.H, self.W) > 0] = pL.reshape(self.H, self.W)[pL.reshape(self.H, self.W) > 0]
1446
+
1447
+ mask_rgba = np.zeros((self.H, self.W, 4), dtype=np.uint8)
1448
+ ghost_rgba = np.zeros((self.H, self.W, 4), dtype=np.uint8) if ghost_mask is not None else None
1449
+ if not self.chk_hide.isChecked():
1450
+ for cid, rgb in self.class_colors_rgb.items():
1451
+ if cid <= 0: continue
1452
+ mask_rgba[unpeeled_mask == cid] = [rgb[0], rgb[1], rgb[2], 180]
1453
+ if ghost_rgba is not None: ghost_rgba[ghost_mask == cid] = [rgb[0], rgb[1], rgb[2], 180]
1454
+ self.canvas.hide_labels = self.chk_hide.isChecked()
1455
+ self.canvas.set_content(safe_numpy_to_pixmap(depth_col), safe_numpy_to_pixmap(mask_rgba), safe_numpy_to_pixmap(ghost_rgba))
1456
+
1457
+ res_rgb = np.zeros((self.H, self.W, 3), dtype=np.uint8)
1458
+ for cid, rgb in self.class_colors_rgb.items():
1459
+ if cid > 0: res_rgb[unpeeled_mask == cid] = rgb
1460
+ self.lbl_result.set_image(safe_numpy_to_pixmap(res_rgb))
1461
+
1462
+ # ... [Assign/Erase... same] ...
1463
+ def _assign_to_current_layer(self, region, cid, layer, overwrite=True):
1464
+ if cid <= 0 or region is None or not np.any(region): return 0
1465
+ m = self.manual_masks[int(layer)]
1466
+ target = region if overwrite else (region & (m == 0))
1467
+ if not np.count_nonzero(target): return 0
1468
+ m[target] = np.uint8(cid)
1469
+ self._ensure_layer_threshold(int(layer))
1470
+ return np.count_nonzero(target)
1471
+ def _erase_current_layer(self, region, layer):
1472
+ if region is None or not np.any(region): return 0
1473
+ m = self.manual_masks[int(layer)]
1474
+ hit = region & (m > 0)
1475
+ if not np.count_nonzero(hit): return 0
1476
+ m[hit] = 0
1477
+ return np.count_nonzero(hit)
1478
+ def _erase_topmost_per_pixel(self, region): return self._erase_current_layer(region, self.edit_layer)
1479
+ def _make_brush_region_circle(self, x, y, radius):
1480
+ tmp = np.zeros((self.H, self.W), dtype=np.uint8)
1481
+ cv2.circle(tmp, (x, y), int(radius), 1, -1)
1482
+ return tmp > 0
1483
+ def _make_brush_region_line(self, x1, y1, x2, y2, thickness):
1484
+ tmp = np.zeros((self.H, self.W), dtype=np.uint8)
1485
+ cv2.line(tmp, (x1, y1), (x2, y2), 1, int(thickness))
1486
+ return tmp > 0
1487
+
1488
+ # ... [Magic Wand ... same] ...
1489
+ def _compute_edge_barrier(self, raw_u8):
1490
+ if not self.wand_edge_aware: return np.zeros_like(raw_u8, dtype=bool)
1491
+ high = int(self.wand_edge_high)
1492
+ return cv2.Canny(raw_u8, max(0, min(255, int(high * 0.5))), high).astype(bool)
1493
+ def _magic_wand_grow(self, seed_x, seed_y, raw2d, valid_mask, thr):
1494
+ if seed_x < 0 or seed_x >= self.W or seed_y < 0 or seed_y >= self.H: return np.zeros((self.H, self.W), dtype=bool)
1495
+ if not valid_mask[seed_y, seed_x] or raw2d[seed_y, seed_x] <= thr: return np.zeros((self.H, self.W), dtype=bool)
1496
+ raw_u8 = cv2.normalize(np.log1p(np.clip(raw2d, 0, None)), None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
1497
+ seed_I, tol, barrier = int(raw_u8[seed_y, seed_x]), int(self.wand_tolerance), self._compute_edge_barrier(raw_u8)
1498
+ neigh = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] if self.wand_connectivity_8 else [(0, -1), (-1, 0), (1, 0), (0, 1)]
1499
+ visited, region = np.zeros((self.H, self.W), dtype=bool), np.zeros((self.H, self.W), dtype=bool)
1500
+ dq = deque([(seed_x, seed_y)])
1501
+ visited[seed_y, seed_x] = True
1502
+ while dq:
1503
+ x, y = dq.popleft()
1504
+ if barrier[y, x] or not valid_mask[y, x] or raw2d[y, x] <= thr or abs(int(raw_u8[y, x]) - seed_I) > tol: continue
1505
+ region[y, x] = True
1506
+ for dx, dy in neigh:
1507
+ nx, ny = x + dx, y + dy
1508
+ if 0 <= nx < self.W and 0 <= ny < self.H and not visited[ny, nx]:
1509
+ visited[ny, nx] = True
1510
+ if not barrier[ny, nx] and valid_mask[ny, nx] and raw2d[ny, nx] > thr: dq.append((nx, ny))
1511
+ return region
1512
+
1513
+ # ==========================================
1514
+ # Canvas actions (Modified for Inspect Mode)
1515
+ # ==========================================
1516
+ def handle_canvas_action(self, action, p1, p2):
1517
+ if self.raw_data is None or p1 is None: return
1518
+ if action == "draw_end": return
1519
+
1520
+ x1, y1 = self._clamp_xy(p1.x(), p1.y())
1521
+ x2, y2 = (x1, y1) if p2 is None else self._clamp_xy(p2.x(), p2.y())
1522
+
1523
+ # [NEW LOGIC] If in Inspect Mode, only update histogram and exit.
1524
+ if self.tool_mode == "inspect":
1525
+ if action in ["pick_end", "pick_end_ctrl"]:
1526
+ # Only react to single clicks to avoid confusion with dragging
1527
+ if (p1 - p2).manhattanLength() <= 5:
1528
+ self.update_histogram_inspector(x1, y1)
1529
+ return # <--- STOP HERE, do NOT proceed to labeling logic
1530
+
1531
+ # --- Labeling Logic Below (Pick/Brush/Eraser) ---
1532
+ raw, peel2d, peak_idx2d = self.get_display_state(return_peak_idx=True)
1533
+ curr_thresh = int(self.sl_thresh.value())
1534
+ is_erase_action = (self.tool_mode == "eraser") or (action == "pick_end_ctrl")
1535
+ valid_mask = np.ones((self.H, self.W), dtype=bool) if is_erase_action else self._get_valid_edit_mask(peel2d)
1536
+ valid_mask = valid_mask & self._get_snr_mask(raw)
1537
+
1538
+ if action in ["draw_start", "pick_end", "pick_end_ctrl"]: self.push_undo()
1539
+ changed = 0
1540
+ allow_overwrite = self.chk_overwrite.isChecked()
1541
+
1542
+ if action == "draw_start":
1543
+ region = self._make_brush_region_circle(x1, y1, self.brush_size)
1544
+ if not is_erase_action: region = region & valid_mask
1545
+ changed = self._erase_topmost_per_pixel(region) if self.tool_mode == "eraser" else self._assign_to_current_layer(region, int(self.current_class), int(self.edit_layer), allow_overwrite)
1546
+ elif action == "draw_drag":
1547
+ region = self._make_brush_region_line(x1, y1, x2, y2, self.brush_size * 2)
1548
+ if not is_erase_action: region = region & valid_mask
1549
+ changed = self._erase_topmost_per_pixel(region) if self.tool_mode == "eraser" else self._assign_to_current_layer(region, int(self.current_class), int(self.edit_layer), allow_overwrite)
1550
+ elif action in ["pick_end", "pick_end_ctrl"]:
1551
+ if (p1 - p2).manhattanLength() > 5:
1552
+ xs, xe, ys, ye = sorted([x1, x2])[0], sorted([x1, x2])[1], sorted([y1, y2])[0], sorted([y1, y2])[1]
1553
+ xe, ye = min(xe + 1, self.W), min(ye + 1, self.H)
1554
+ region = np.zeros((self.H, self.W), dtype=bool)
1555
+ roi = raw[ys:ye, xs:xe]
1556
+ region[ys:ye, xs:xe] = (roi > curr_thresh) & valid_mask[ys:ye, xs:xe]
1557
+ else:
1558
+ region = self._magic_wand_grow(x1, y1, raw, valid_mask, curr_thresh)
1559
+
1560
+ if not np.any(region):
1561
+ if not is_erase_action and self.chk_lock_to_visible.isChecked():
1562
+ self.log_win.append("Pick ignored: invalid area.")
1563
+ else:
1564
+ ctrl_erase = (action == "pick_end_ctrl")
1565
+ changed = self._erase_topmost_per_pixel(region) if (ctrl_erase or self.tool_mode == "eraser") else self._assign_to_current_layer(region, int(self.current_class), int(self.edit_layer), allow_overwrite)
1566
+
1567
+ if changed > 0:
1568
+ self.set_dirty()
1569
+ self.update_all_views()
1570
+
1571
+ # ... [Undo/Morph/Key events ... same] ...
1572
+ def undo(self):
1573
+ if not self.undo_stack: return
1574
+ stack, thr, pd, rs, el, peel_mode = self.undo_stack.pop()
1575
+ self.manual_masks = [stack[l].copy() for l in range(self.num_layers)]
1576
+ self.layer_thresholds = list(thr)
1577
+ self.peel_depth, self.region_step, self.edit_layer, self.peel_by_class = int(pd), int(rs), int(el), bool(peel_mode)
1578
+ self.chk_peel_class.blockSignals(True)
1579
+ self.chk_peel_class.setChecked(self.peel_by_class)
1580
+ self.chk_peel_class.blockSignals(False)
1581
+ self.sl_peel.blockSignals(True)
1582
+ self.sl_peel.setValue(self.peel_depth)
1583
+ self.sl_peel.blockSignals(False)
1584
+ self.sl_edit.blockSignals(True)
1585
+ self.sl_edit.setValue(self.edit_layer)
1586
+ self.sl_edit.blockSignals(False)
1587
+ self.clear_layer_cache()
1588
+ self.is_dirty = True
1589
+ self.mask_revision += 1
1590
+ self._sync_region_slider()
1591
+ self.update_all_views()
1592
+ self.log_win.append("Undo.")
1593
+ if self.hist_inspector and self.hist_inspector.isVisible():
1594
+ self.hist_inspector.ax.clear()
1595
+ self.hist_inspector.canvas.draw()
1596
+ def keyPressEvent(self, event):
1597
+ if event.key() == Qt.Key_Up: self.sl_thresh.setValue(self.sl_thresh.value() + (10 if event.modifiers() & Qt.ShiftModifier else 1))
1598
+ elif event.key() == Qt.Key_Down: self.sl_thresh.setValue(max(0, self.sl_thresh.value() - (10 if event.modifiers() & Qt.ShiftModifier else 1)))
1599
+ elif event.key() == Qt.Key_Control:
1600
+ self.canvas.ctrl_pressed = True
1601
+ self.canvas.update()
1602
+ else: super().keyPressEvent(event)
1603
+ def keyReleaseEvent(self, event):
1604
+ if event.key() == Qt.Key_Control:
1605
+ self.canvas.ctrl_pressed = False
1606
+ self.canvas.update()
1607
+ super().keyReleaseEvent(event)
1608
+ def set_class_by_key(self, idx):
1609
+ if int(idx) in self.cls_radios:
1610
+ self.cls_radios[int(idx)].setChecked(True)
1611
+ self.current_class = int(idx)
1612
+ def cycle_class_prev(self): self.set_class_by_key(self.current_class - 1 if self.current_class > 1 else len(self.class_names))
1613
+ def cycle_class_next(self): self.set_class_by_key(self.current_class + 1 if self.current_class < len(self.class_names) else 1)
1614
+ def morph_current_mask(self, op):
1615
+ mask = self.manual_masks[0]
1616
+ if not np.any(mask): return
1617
+ self.push_undo()
1618
+ kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
1619
+ for cid in self.class_names:
1620
+ c_mask = (mask == cid).astype(np.uint8)
1621
+ if not np.any(c_mask): continue
1622
+ proc = cv2.dilate(c_mask, kernel) if op == "dilate" else cv2.erode(c_mask, kernel)
1623
+ mask[proc > 0] = cid
1624
+ self.set_dirty()
1625
+ self.update_all_views()
1626
+ def fill_unknown_current_layer(self):
1627
+ if self.raw_data is None: return
1628
+ layer = int(self.edit_layer)
1629
+ raw2d, peel2d = self.get_display_state()
1630
+ valid = self._get_valid_edit_mask(peel2d) & self._get_snr_mask(raw2d)
1631
+ region = (raw2d > int(self.sl_thresh.value())) & valid
1632
+ m = self.manual_masks[layer]
1633
+ fill = region & (m == 0)
1634
+ if not np.count_nonzero(fill): return
1635
+ self.push_undo()
1636
+ m[fill] = np.uint8(self.UNKNOWN_CID)
1637
+ self._ensure_layer_threshold(layer)
1638
+ self.set_dirty()
1639
+ self.update_all_views()
1640
+
1641
+ # ==========================================
1642
+ # 3D
1643
+ # ==========================================
1644
+ def visualize_3d_point_cloud(self):
1645
+ if not HAS_OPEN3D or self.raw_data is None: return
1646
+ QApplication.setOverrideCursor(Qt.WaitCursor)
1647
+ try:
1648
+ raw, _ = self.get_display_state()
1649
+ snr_mask = self._get_snr_mask(raw)
1650
+ valid = (raw > int(self.sl_thresh.value())) & snr_mask
1651
+ rows, cols = np.where(valid)
1652
+ working_data = self._build_working_hist_for_display(return_peel_count=False)
1653
+ zs = [int(np.argmax(working_data[r * self.W + c])) for r, c in zip(rows, cols)]
1654
+ Z = np.array(zs, dtype=np.float32) * AppConfig.BIN_UNIT
1655
+ u, v = cols.astype(float), rows.astype(float)
1656
+ pts_uv = np.stack([u, v], axis=1).reshape(-1, 1, 2)
1657
+ pts_undist = cv2.undistortPoints(pts_uv, AppConfig.CAM_K, AppConfig.CAM_D).reshape(-1, 2)
1658
+ xyz = np.stack([pts_undist[:, 0] * Z, pts_undist[:, 1] * Z, Z], axis=1)
1659
+ pcd = o3d.geometry.PointCloud()
1660
+ pcd.points = o3d.utility.Vector3dVector(xyz)
1661
+ pcd.colors = o3d.utility.Vector3dVector(get_robust_colors(raw[rows, cols]))
1662
+ o3d.visualization.draw_geometries([pcd], window_name=f"3D Depth (PeelDepth {self.peel_depth})")
1663
+ finally: QApplication.restoreOverrideCursor()
1664
+
1665
+ def visualize_3d_semantic_point_cloud(self):
1666
+ if not HAS_OPEN3D or self.raw_data is None: return
1667
+ QApplication.setOverrideCursor(Qt.WaitCursor)
1668
+ try:
1669
+ curr_thr = int(self.sl_thresh.value())
1670
+ working = self.raw_data.copy()
1671
+ all_rows, all_cols, all_Z, all_cids = [], [], [], []
1672
+ for l in range(self.num_layers):
1673
+ m = self.manual_masks[l]
1674
+ flat = m.reshape(-1)
1675
+ labeled_idx = np.flatnonzero(flat > 0)
1676
+ if labeled_idx.size == 0: continue
1677
+ thr_l = self.layer_thresholds[l] if self.layer_thresholds[l] is not None else curr_thr
1678
+ for idx in labeled_idx:
1679
+ cid = int(flat[idx])
1680
+ hist = working[idx]
1681
+ if np.max(hist) <= thr_l: continue
1682
+ peak_idx = int(np.argmax(hist))
1683
+ (__, ___), (l_rem, r_rem) = analyze_peak_structure(hist, peak_idx, thr_l)
1684
+ if r_rem <= l_rem: continue
1685
+ all_rows.append(int(idx // self.W))
1686
+ all_cols.append(int(idx % self.W))
1687
+ all_Z.append(float(peak_idx) * AppConfig.BIN_UNIT)
1688
+ all_cids.append(cid)
1689
+ working[idx, l_rem:r_rem + 1] = 0
1690
+ if len(all_rows) == 0: return
1691
+ rows, cols, Z, cids = np.asarray(all_rows), np.asarray(all_cols), np.asarray(all_Z), np.asarray(all_cids)
1692
+ u, v = cols.astype(np.float32), rows.astype(np.float32)
1693
+ pts_uv = np.stack([u, v], axis=1).reshape(-1, 1, 2)
1694
+ pts_undist = cv2.undistortPoints(pts_uv, AppConfig.CAM_K, AppConfig.CAM_D).reshape(-1, 2)
1695
+ xyz = np.stack([pts_undist[:, 0] * Z, pts_undist[:, 1] * Z, Z], axis=1)
1696
+ colors = np.zeros((cids.size, 3), dtype=np.float32)
1697
+ for i, cid in enumerate(cids):
1698
+ rgb = self.class_colors_rgb.get(int(cid), (255, 255, 255))
1699
+ colors[i] = [rgb[0]/255.0, rgb[1]/255.0, rgb[2]/255.0]
1700
+ pcd = o3d.geometry.PointCloud()
1701
+ pcd.points = o3d.utility.Vector3dVector(xyz)
1702
+ pcd.colors = o3d.utility.Vector3dVector(colors)
1703
+ o3d.visualization.draw_geometries([pcd], window_name="3D Semantic (Multi-layer)")
1704
+ finally: QApplication.restoreOverrideCursor()
1705
+
1706
+ # [RESTORED METHOD]
1707
+ def visualize_3d_semantic_bins_point_cloud(self):
1708
+ if not HAS_OPEN3D or self.raw_data is None: return
1709
+ QApplication.setOverrideCursor(Qt.WaitCursor)
1710
+ try:
1711
+ thr_global = int(self.sl_thresh.value())
1712
+ H, W = self.H, self.W
1713
+ BIN_STRIDE = 1
1714
+ PIX_STRIDE = 1
1715
+ MAX_POINTS = 2_000_000
1716
+ working = self.raw_data.copy()
1717
+ all_xyz, all_rgb = [], []
1718
+ total_pts = 0
1719
+
1720
+ for layer in range(self.num_layers):
1721
+ m = self.manual_masks[layer]
1722
+ flat = m.reshape(-1)
1723
+ pix = np.flatnonzero(flat > 0)
1724
+ if pix.size == 0: continue
1725
+ if PIX_STRIDE > 1: pix = pix[::PIX_STRIDE]
1726
+ thr = self.layer_thresholds[layer] if self.layer_thresholds[layer] is not None else thr_global
1727
+ thr = int(thr)
1728
+ rows, cols = (pix // W).astype(np.int32), (pix % W).astype(np.int32)
1729
+ pts_uv = np.stack([cols.astype(np.float32), rows.astype(np.float32)], axis=1).reshape(-1, 1, 2)
1730
+ pts_undist = cv2.undistortPoints(pts_uv, AppConfig.CAM_K, AppConfig.CAM_D).reshape(-1, 2)
1731
+ xnd, ynd = pts_undist[:, 0], pts_undist[:, 1]
1732
+ cids = flat[pix].astype(np.int32)
1733
+
1734
+ for i, idx in enumerate(pix):
1735
+ hist = working[idx]
1736
+ if hist.max() <= thr: continue
1737
+ p_idx = int(np.argmax(hist))
1738
+ (l_lab, r_lab), (l_rem, r_rem) = analyze_peak_structure(hist, p_idx, thr)
1739
+ if r_lab >= l_lab:
1740
+ bins = np.arange(l_lab, r_lab + 1, BIN_STRIDE, dtype=np.int32)
1741
+ if bins.size > 0:
1742
+ Z = bins.astype(np.float32) * float(AppConfig.BIN_UNIT)
1743
+ xyz = np.stack([xnd[i] * Z, ynd[i] * Z, Z], axis=1)
1744
+ cid = int(cids[i])
1745
+ rgb = self.class_colors_rgb.get(cid, (64, 64, 64))
1746
+ rgb_f = (np.array(rgb, dtype=np.float32) / 255.0).reshape(1, 3)
1747
+ rgb_arr = np.repeat(rgb_f, xyz.shape[0], axis=0)
1748
+ all_xyz.append(xyz)
1749
+ all_rgb.append(rgb_arr)
1750
+ total_pts += xyz.shape[0]
1751
+ if total_pts >= MAX_POINTS: break
1752
+ if r_rem > l_rem: working[idx, l_rem:r_rem + 1] = 0
1753
+ if total_pts >= MAX_POINTS: break
1754
+
1755
+ if total_pts == 0:
1756
+ self.log_win.append("3D Labeled Bins: no labeled bin segments to draw.")
1757
+ return
1758
+ xyz = np.concatenate(all_xyz, axis=0)
1759
+ rgb = np.concatenate(all_rgb, axis=0)
1760
+ pcd = o3d.geometry.PointCloud()
1761
+ pcd.points = o3d.utility.Vector3dVector(xyz)
1762
+ pcd.colors = o3d.utility.Vector3dVector(rgb)
1763
+ o3d.visualization.draw_geometries([pcd], window_name="3D Labeled Bins (per-pixel labeled segments)")
1764
+ finally: QApplication.restoreOverrideCursor()
1765
+
1766
+
1767
+ if __name__ == "__main__":
1768
+ import multiprocessing as mp
1769
+ mp.freeze_support()
1770
+ ap = argparse.ArgumentParser()
1771
+ ap.add_argument("--in_dir", default="npy")
1772
+ ap.add_argument("--out_root", default="output")
1773
+ ap.add_argument("--pattern", default="*.npy")
1774
+ ap.add_argument("--cache_dir", default="cache")
1775
+ args = ap.parse_args()
1776
+
1777
+ app = QApplication(sys.argv)
1778
+ win = SPADLabelerPixel(args)
1779
+ win.show()
1780
+ sys.exit(app.exec_())
codes/pointcloud_extract/ann2pc.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ 将标注文件 (semantic.npy) 转换为带语义标签的PLY点云真值
4
+ 基于 visualize_semantic_labels.py 的标注逻辑
5
+ """
6
+
7
+ import os
8
+ import glob
9
+ import numpy as np
10
+ import cv2
11
+ import yaml
12
+ from tqdm import tqdm
13
+ from concurrent.futures import ProcessPoolExecutor, as_completed
14
+ import multiprocessing
15
+
16
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
17
+
18
+ def load_config(config_path=None):
19
+ if config_path is None:
20
+ config_path = os.path.join(SCRIPT_DIR, 'config.yaml')
21
+ with open(config_path, 'r', encoding='utf-8') as f:
22
+ return yaml.safe_load(f)
23
+
24
+ CONFIG = load_config()
25
+
26
+ # 相机和深度参数
27
+ IMG_H, IMG_W = 192, 256
28
+ BIN_TO_M = 299_792_458.0 * CONFIG['common']['dt_ps'] * 1e-12 / 2.0
29
+
30
+
31
+ def save_ply_with_label(pts, path):
32
+ """保存带语义标签的PLY文件: x y z label"""
33
+ with open(path, "wb") as f:
34
+ header = f"ply\nformat ascii 1.0\nelement vertex {len(pts)}\n"
35
+ header += "property float x\nproperty float y\nproperty float z\nproperty int label\nend_header\n"
36
+ f.write(header.encode())
37
+ np.savetxt(f, pts, fmt='%.6f %.6f %.6f %d')
38
+
39
+
40
+ def process_single_ann(args):
41
+ """处理单个标注文件,转换为PLY点云"""
42
+ npy_path, cam_config, out_dir = args
43
+
44
+ # 从文件名提取基础名 (去掉 _semantic.npy)
45
+ basename = os.path.basename(npy_path)
46
+ if basename.endswith('_semantic.npy'):
47
+ basename = basename[:-13] # 去掉 '_semantic.npy'
48
+
49
+ out_path = os.path.join(out_dir, f"{basename}_gt.ply")
50
+
51
+ try:
52
+ # 加载标注数据 (H*W, num_bins)
53
+ sem_bins = np.load(npy_path)
54
+ num_pos, num_bins = sem_bins.shape
55
+
56
+ # 预计算相机参数
57
+ K = np.array([[cam_config['fx'], 0, cam_config['cx']],
58
+ [0, cam_config['fy'], cam_config['cy']],
59
+ [0, 0, 1]], dtype=np.float64)
60
+ D = np.array([cam_config['k1'], cam_config['k2'], cam_config['p1'], cam_config['p2']], dtype=np.float64)
61
+
62
+ points = []
63
+
64
+ # 遍历每个像素,提取标注的峰值
65
+ for idx in range(num_pos):
66
+ row = sem_bins[idx]
67
+ nz = np.flatnonzero(row > 0) # 找到有标注的bin
68
+ if nz.size == 0:
69
+ continue
70
+
71
+ # 找到连续的标注段
72
+ breaks = np.flatnonzero(np.diff(nz) != 1)
73
+ run_starts = np.concatenate(([0], breaks + 1))
74
+ run_ends = np.concatenate((breaks, [nz.size - 1]))
75
+
76
+ for rs, re in zip(run_starts, run_ends):
77
+ b0 = int(nz[rs])
78
+ b1 = int(nz[re])
79
+ cid = int(row[b0]) # 语义类别
80
+ if cid <= 0:
81
+ continue
82
+
83
+ # 使用标注段的中心bin作为深度
84
+ peak_bin = (b0 + b1) // 2
85
+ depth = peak_bin * BIN_TO_M
86
+
87
+ # 深度范围过滤
88
+ if depth < CONFIG['common']['min_range_m'] or depth > CONFIG['common']['max_range_m']:
89
+ continue
90
+
91
+ # 计算3D坐标
92
+ v, u = idx // IMG_W, idx % IMG_W
93
+
94
+ if CONFIG['common']['undistort']:
95
+ uv = np.array([[[u, v]]], dtype=np.float32)
96
+ uv_norm = cv2.undistortPoints(uv, K, D)
97
+ x_n, y_n = uv_norm[0, 0, 0], uv_norm[0, 0, 1]
98
+ else:
99
+ x_n = (u - cam_config['cx']) / cam_config['fx']
100
+ y_n = (v - cam_config['cy']) / cam_config['fy']
101
+
102
+ if CONFIG['common']['depth_is_range']:
103
+ ray = np.array([x_n, y_n, 1.0])
104
+ ray_unit = ray / np.linalg.norm(ray)
105
+ xyz = ray_unit * depth
106
+ else:
107
+ xyz = np.array([x_n * depth, y_n * depth, depth])
108
+
109
+ points.append([xyz[0], xyz[1], xyz[2], cid])
110
+
111
+ if len(points) == 0:
112
+ return basename, False, 0
113
+
114
+ pts = np.array(points, dtype=np.float32)
115
+ pts[:, 3] = pts[:, 3].astype(np.int32) # 确保label是整数
116
+ save_ply_with_label(pts, out_path)
117
+
118
+ return basename, True, len(pts)
119
+
120
+ except Exception as e:
121
+ print(f"Error processing {npy_path}: {e}")
122
+ return basename, False, 0
123
+
124
+
125
+ def main():
126
+ config = load_config()
127
+ datasets = config['datasets']
128
+
129
+ ann_root = os.path.join(SCRIPT_DIR, 'ann')
130
+ output_root = os.path.join(SCRIPT_DIR, 'output_denoised', 'gt')
131
+
132
+ num_workers = min(config['common'].get('num_workers', 8), multiprocessing.cpu_count())
133
+
134
+ print(f"[INFO] Converting annotations to PLY ground truth")
135
+ print(f"[INFO] Ann root: {ann_root}")
136
+ print(f"[INFO] Output root: {output_root}")
137
+ print(f"[INFO] Workers: {num_workers}")
138
+
139
+ # 遍历数据集 (p1, p2)
140
+ for dataset_name, cam_config in datasets.items():
141
+ dataset_ann_path = os.path.join(ann_root, dataset_name)
142
+ if not os.path.isdir(dataset_ann_path):
143
+ print(f"[Skip] {dataset_name} not found in ann/")
144
+ continue
145
+
146
+ print(f"\n[Dataset] {dataset_name}")
147
+
148
+ # 遍历序列目录
149
+ seq_dirs = [d for d in os.listdir(dataset_ann_path)
150
+ if os.path.isdir(os.path.join(dataset_ann_path, d))]
151
+
152
+ for seq_name in seq_dirs:
153
+ seq_path = os.path.join(dataset_ann_path, seq_name)
154
+ out_dir = os.path.join(output_root, seq_name)
155
+ os.makedirs(out_dir, exist_ok=True)
156
+
157
+ # 查找所有标注文件
158
+ npy_files = sorted(glob.glob(os.path.join(seq_path, "*_semantic.npy")))
159
+ if not npy_files:
160
+ continue
161
+
162
+ # 准备任务
163
+ tasks = [(f, cam_config, out_dir) for f in npy_files]
164
+
165
+ success_count = 0
166
+ total_pts = 0
167
+
168
+ with ProcessPoolExecutor(max_workers=num_workers) as executor:
169
+ futures = [executor.submit(process_single_ann, t) for t in tasks]
170
+
171
+ pbar = tqdm(as_completed(futures), total=len(npy_files),
172
+ desc=f" {seq_name}", leave=False)
173
+ for future in pbar:
174
+ basename, ok, pts_count = future.result()
175
+ if ok:
176
+ success_count += 1
177
+ total_pts += pts_count
178
+
179
+ print(f" {seq_name}: {success_count}/{len(npy_files)} files, {total_pts:,} pts")
180
+
181
+ print(f"\n[Done] Ground truth PLY saved to: {output_root}")
182
+
183
+
184
+ if __name__ == "__main__":
185
+ main()
codes/pointcloud_extract/raw2pc.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import glob
3
+ import os
4
+ import re
5
+
6
+ import cv2
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+ import pandas as pd
10
+
11
+ C = 299_792_458.0 # m/s
12
+ COMMON_SIZES = ((192, 256), (256, 192))
13
+ TARGET_PIXELS = 192 * 256
14
+
15
+ OUTPUT_COLUMNS = ["Timestamp", "X", "Y", "Z", "Reflectivity"]
16
+
17
+
18
+ def _str2bool(value):
19
+ if isinstance(value, bool):
20
+ return value
21
+ text = str(value).strip().lower()
22
+ return text in {"1", "true", "yes", "y", "on"}
23
+
24
+
25
+ def _extract_timestamp_from_name(path):
26
+ name = os.path.basename(path)
27
+ m = re.search(r"(\d+)(?=\.txt$)", name)
28
+ if m:
29
+ return int(m.group(1))
30
+
31
+ nums = re.findall(r"\d+", name)
32
+ if nums:
33
+ return int(nums[-1])
34
+ return -1
35
+
36
+
37
+ def _infer_shape(num_pos):
38
+ for h, w in COMMON_SIZES:
39
+ if h * w == num_pos:
40
+ return h, w, num_pos
41
+
42
+ if num_pos >= TARGET_PIXELS:
43
+ return 192, 256, TARGET_PIXELS
44
+
45
+ h = int(np.sqrt(num_pos))
46
+ while h > 1 and num_pos % h != 0:
47
+ h -= 1
48
+ w = num_pos // h
49
+ return h, w, num_pos
50
+
51
+
52
+ def _build_intrinsics(fx, fy, cx, cy, k1, k2, p1, p2):
53
+ K = np.array(
54
+ [
55
+ [fx, 0, cx],
56
+ [0, fy, cy],
57
+ [0, 0, 1],
58
+ ],
59
+ dtype=np.float64,
60
+ )
61
+ D = np.array([k1, k2, p1, p2], dtype=np.float64)
62
+ return K, D
63
+
64
+
65
+ def _top2_counts_per_row(data):
66
+ top2 = np.partition(data, -2, axis=1)[:, -2:]
67
+ second = top2[:, 0].astype(np.float32)
68
+ peak = top2[:, 1].astype(np.float32)
69
+ return peak, second
70
+
71
+
72
+ def _load_hist_intensity_depth(txt_path, dt_ps):
73
+ data = np.loadtxt(txt_path, dtype=np.int64)
74
+ if data.ndim == 1:
75
+ data = data.reshape(1, -1)
76
+
77
+ num_pos, _ = data.shape
78
+ intensity_1d, _ = _top2_counts_per_row(data)
79
+ peak_bin_1d = data.argmax(axis=1).astype(np.int32)
80
+
81
+ dt = dt_ps * 1e-12
82
+ bin_to_m = C * dt / 2.0
83
+ # depth_m_1d = peak_bin_1d.astype(np.float32) * bin_to_m
84
+ depth_m_1d = ( peak_bin_1d.astype(np.float32) - 17) * bin_to_m#25 18
85
+
86
+ ###
87
+ offset = np.loadtxt("./offset.txt", dtype=float)
88
+ idx_offset = np.argwhere( offset < 10 )[:,0]
89
+ depth_m_1d[idx_offset] -= offset[idx_offset]
90
+
91
+ height, width, keep_n = _infer_shape(num_pos)
92
+ if keep_n < num_pos:
93
+ intensity_1d = intensity_1d[:keep_n]
94
+ depth_m_1d = depth_m_1d[:keep_n]
95
+
96
+ intensity = intensity_1d.reshape(height, width)
97
+ depth_m = depth_m_1d.reshape(height, width)
98
+
99
+ return intensity, depth_m, height, width
100
+
101
+
102
+ def _compute_points_undistort_points(
103
+ intensity,
104
+ depth_m,
105
+ K,
106
+ D,
107
+ depth_is_range,
108
+ min_range_m,
109
+ max_range_m,
110
+ intensity_min,
111
+ intensity_max,
112
+ undistort_intensity,
113
+ ):
114
+ if undistort_intensity:
115
+ intensity_u = cv2.undistort(intensity, K, D)
116
+ else:
117
+ intensity_u = intensity
118
+
119
+ depth_u = depth_m
120
+
121
+ h, w = depth_u.shape
122
+ u, v = np.meshgrid(np.arange(w), np.arange(h))
123
+
124
+ valid = (
125
+ np.isfinite(depth_u)
126
+ & (depth_u > float(min_range_m))
127
+ & (depth_u < float(max_range_m))
128
+ & (intensity_u >= float(intensity_min))
129
+ )
130
+ if intensity_max is not None:
131
+ valid &= intensity_u <= float(intensity_max)
132
+
133
+ offset = np.loadtxt("offset.txt", dtype=float)
134
+ offset_m = offset.reshape(h, w)
135
+ valid_offset = offset_m < 10
136
+ valid = valid & valid_offset
137
+
138
+ u_valid = u[valid].astype(np.float32)
139
+ v_valid = v[valid].astype(np.float32)
140
+ d_valid = depth_u[valid].astype(np.float32)
141
+ i_valid = intensity_u[valid].astype(np.float32)
142
+
143
+ uv = np.stack([u_valid, v_valid], axis=1).reshape(-1, 1, 2).astype(np.float32)
144
+ xy = cv2.undistortPoints(uv, K, D)
145
+ x_n = xy[:, 0, 0]
146
+ y_n = xy[:, 0, 1]
147
+
148
+ ray = np.stack([x_n, y_n, np.ones_like(x_n)], axis=1)
149
+ ray_norm = np.linalg.norm(ray, axis=1, keepdims=True)
150
+ ray_unit = ray / np.maximum(ray_norm, 1e-12)
151
+
152
+ if depth_is_range:
153
+ pts = ray_unit * d_valid.reshape(-1, 1)
154
+ else:
155
+ pts = ray_unit * (d_valid.reshape(-1, 1) / np.maximum(ray_unit[:, 2:3], 1e-12))
156
+
157
+ reflectivity = np.rint(i_valid).astype(np.int32)
158
+ return pts.astype(np.float32), reflectivity, intensity_u, depth_u
159
+
160
+
161
+ def _normalize_to_u8(values):
162
+ arr = values.astype(np.float32)
163
+ if arr.size == 0:
164
+ return np.array([], dtype=np.uint8)
165
+ lo = float(np.min(arr))
166
+ hi = float(np.max(arr))
167
+ if hi <= lo:
168
+ return np.zeros(arr.shape, dtype=np.uint8)
169
+ return ((arr - lo) * (255.0 / (hi - lo))).clip(0, 255).astype(np.uint8)
170
+
171
+
172
+ def _write_ply_ascii(path, pts, reflectivity):
173
+ i_255 = _normalize_to_u8(reflectivity.astype(np.float32))
174
+ with open(path, "w", encoding="utf-8") as f:
175
+ f.write("ply\n")
176
+ f.write("format ascii 1.0\n")
177
+ f.write(f"element vertex {pts.shape[0]}\n")
178
+ f.write("property float x\n")
179
+ f.write("property float y\n")
180
+ f.write("property float z\n")
181
+ f.write("property uchar red\n")
182
+ f.write("property uchar green\n")
183
+ f.write("property uchar blue\n")
184
+ f.write("end_header\n")
185
+ for idx in range(pts.shape[0]):
186
+ x, y, z = pts[idx]
187
+ ii = int(i_255[idx]) if idx < i_255.shape[0] else 0
188
+ f.write(f"{x} {y} {z} {ii} {ii} {ii}\n")
189
+
190
+
191
+ def _save_maps_png(path, intensity_u, depth_u):
192
+ plt.figure(figsize=(12, 5))
193
+ plt.subplot(1, 2, 1)
194
+ plt.imshow(intensity_u, origin="upper")
195
+ plt.title("Intensity (max count)")
196
+ plt.colorbar()
197
+ plt.subplot(1, 2, 2)
198
+ plt.imshow(depth_u, origin="upper")
199
+ plt.title("Depth (m) from peak bin")
200
+ plt.colorbar()
201
+ plt.tight_layout()
202
+ plt.savefig(path, dpi=150)
203
+ plt.close()
204
+
205
+
206
+ def _points_to_simple_csv(pts, reflectivity, timestamp):
207
+ n = pts.shape[0]
208
+ df = pd.DataFrame(
209
+ {
210
+ "Timestamp": np.full(n, int(timestamp), dtype=np.int64),
211
+ "X": pts[:, 0],
212
+ "Y": pts[:, 1],
213
+ "Z": pts[:, 2],
214
+ "Reflectivity": reflectivity.astype(np.int32),
215
+ },
216
+ columns=OUTPUT_COLUMNS,
217
+ )
218
+ return df
219
+
220
+
221
+ def _maybe_visualize_open3d(pts, reflectivity, point_size=1.5):
222
+ try:
223
+ import open3d as o3d
224
+ import matplotlib.cm as cm
225
+ except Exception:
226
+ print("[warn] open3d/matplotlib colormap not available, skip visualization")
227
+ return
228
+
229
+ pcd = o3d.geometry.PointCloud()
230
+ pcd.points = o3d.utility.Vector3dVector(pts.astype(np.float64))
231
+
232
+ if reflectivity.size > 0:
233
+ refl = reflectivity.astype(np.float32)
234
+ refl_norm = (refl - refl.min()) / (refl.max() - refl.min() + 1e-12)
235
+ colors = cm.get_cmap("turbo")(refl_norm)[:, :3]
236
+ pcd.colors = o3d.utility.Vector3dVector(colors.astype(np.float64))
237
+
238
+ axis = o3d.geometry.TriangleMesh.create_coordinate_frame(size=0.2, origin=[0, 0, 0])
239
+
240
+ vis = o3d.visualization.Visualizer()
241
+ vis.create_window(window_name="SP Point Cloud (undistortPoints)", width=1200, height=800)
242
+ vis.add_geometry(pcd)
243
+ vis.add_geometry(axis)
244
+ opt = vis.get_render_option()
245
+ if opt is not None:
246
+ opt.point_size = float(point_size)
247
+ opt.background_color = np.array([0.02, 0.02, 0.02], dtype=np.float64)
248
+ vis.run()
249
+ vis.destroy_window()
250
+
251
+
252
+ def convert_one_txt(
253
+ txt_path,
254
+ output_base,
255
+ dt_ps,
256
+ depth_is_range,
257
+ undistort_intensity,
258
+ K,
259
+ D,
260
+ min_range_m,
261
+ max_range_m,
262
+ intensity_min,
263
+ intensity_max,
264
+ output_mode,
265
+ save_maps,
266
+ show,
267
+ show_point_size=1.5,
268
+ ):
269
+ timestamp = _extract_timestamp_from_name(txt_path)
270
+ if timestamp < 0:
271
+ raise ValueError(f"No timestamp found in filename: {txt_path}")
272
+
273
+ intensity, depth_m, _, _ = _load_hist_intensity_depth(txt_path=txt_path, dt_ps=dt_ps)
274
+ pts, refl, intensity_u, depth_u = _compute_points_undistort_points(
275
+ intensity=intensity,
276
+ depth_m=depth_m,
277
+ K=K,
278
+ D=D,
279
+ depth_is_range=depth_is_range,
280
+ min_range_m=min_range_m,
281
+ max_range_m=max_range_m,
282
+ intensity_min=intensity_min,
283
+ intensity_max=intensity_max,
284
+ undistort_intensity=undistort_intensity,
285
+ )
286
+
287
+ csv_path = ""
288
+ ply_path = ""
289
+ map_path = ""
290
+
291
+ if output_mode in ("csv", "both"):
292
+ csv_path = output_base + ".csv"
293
+ _points_to_simple_csv(pts, refl, timestamp).to_csv(csv_path, index=False)
294
+
295
+ if output_mode in ("ply", "both"):
296
+ ply_path = output_base + ".ply"
297
+ _write_ply_ascii(ply_path, pts, refl)
298
+
299
+ if save_maps:
300
+ map_path = output_base + "_maps.png"
301
+ _save_maps_png(map_path, intensity_u, depth_u)
302
+
303
+ if show:
304
+ _maybe_visualize_open3d(pts, refl, point_size=show_point_size)
305
+
306
+ return {
307
+ "txt": txt_path,
308
+ "timestamp": timestamp,
309
+ "points": int(pts.shape[0]),
310
+ "csv": csv_path,
311
+ "ply": ply_path,
312
+ "maps": map_path,
313
+ }
314
+
315
+
316
+ def batch_convert(
317
+ input_dir,
318
+ output_dir,
319
+ pattern,
320
+ prefix,
321
+ start_index,
322
+ dt_ps,
323
+ depth_is_range,
324
+ undistort_intensity,
325
+ K,
326
+ D,
327
+ min_range_m,
328
+ max_range_m,
329
+ intensity_min,
330
+ intensity_max,
331
+ output_mode,
332
+ save_maps,
333
+ ):
334
+ os.makedirs(output_dir, exist_ok=True)
335
+
336
+ txt_files = glob.glob(os.path.join(input_dir, pattern))
337
+ if not txt_files:
338
+ raise FileNotFoundError(f"No files matched: {os.path.join(input_dir, pattern)}")
339
+
340
+ txt_files.sort(key=lambda p: (_extract_timestamp_from_name(p), os.path.basename(p)))
341
+
342
+ results = []
343
+ out_idx = int(start_index)
344
+ for txt_path in txt_files:
345
+ out_base = os.path.join(output_dir, f"{prefix}{out_idx}")
346
+ info = convert_one_txt(
347
+ txt_path=txt_path,
348
+ output_base=out_base,
349
+ dt_ps=dt_ps,
350
+ depth_is_range=depth_is_range,
351
+ undistort_intensity=undistort_intensity,
352
+ K=K,
353
+ D=D,
354
+ min_range_m=min_range_m,
355
+ max_range_m=max_range_m,
356
+ intensity_min=intensity_min,
357
+ intensity_max=intensity_max,
358
+ output_mode=output_mode,
359
+ save_maps=save_maps,
360
+ show=False,
361
+ )
362
+ results.append(info)
363
+
364
+ outputs = []
365
+ if info["csv"]:
366
+ outputs.append(os.path.basename(info["csv"]))
367
+ if info["ply"]:
368
+ outputs.append(os.path.basename(info["ply"]))
369
+ if info["maps"]:
370
+ outputs.append(os.path.basename(info["maps"]))
371
+ out_text = ", ".join(outputs) if outputs else "<none>"
372
+
373
+ print(
374
+ f"[{out_idx}] {os.path.basename(txt_path)} -> {out_text}, "
375
+ f"ts={info['timestamp']}, points={info['points']}"
376
+ )
377
+ out_idx += 1
378
+
379
+ return results
380
+
381
+
382
+ def build_parser():
383
+ parser = argparse.ArgumentParser(
384
+ description="Convert single-photon histogram txt to point cloud with cv2.undistortPoints."
385
+ )
386
+
387
+ parser.add_argument("--input-dir", type=str, default="./imaging")
388
+ parser.add_argument("--output-dir", type=str, default="./imaging")
389
+ parser.add_argument(
390
+ "--pattern",
391
+ type=str,
392
+ default="RawDataHistogramMap_frame_0_*.txt",
393
+ help="glob pattern under input-dir",
394
+ )
395
+ parser.add_argument("--prefix", type=str, default="")
396
+ parser.add_argument("--start-index", type=int, default=1)
397
+
398
+ parser.add_argument("--single-txt", type=str, default="", help="optional: convert one txt only")
399
+ parser.add_argument(
400
+ "--single-out-base",
401
+ type=str,
402
+ default="",
403
+ help="optional: output base path without extension for --single-txt",
404
+ )
405
+
406
+ parser.add_argument("--dt-ps", type=float, default=750.0)
407
+ parser.add_argument("--depth-is-range", type=_str2bool, default=True)
408
+ parser.add_argument("--undistort-intensity", type=_str2bool, default=True)
409
+
410
+ parser.add_argument("--fx", type=float, default=118.6514575329715)
411
+ parser.add_argument("--fy", type=float, default=118.7964934010577)
412
+ parser.add_argument("--cx", type=float, default=130.6802784645003)
413
+ parser.add_argument("--cy", type=float, default=100.3605702468140)
414
+
415
+ parser.add_argument("--k1", type=float, default=-0.257910069121181)
416
+ parser.add_argument("--k2", type=float, default=0.053237073644331)
417
+ parser.add_argument("--p1", type=float, default=0.0)
418
+ parser.add_argument("--p2", type=float, default=0.0)
419
+
420
+ parser.add_argument("--min-range-m", type=float, default=0.0)
421
+ parser.add_argument("--max-range-m", type=float, default=20.0)
422
+ parser.add_argument("--intensity-min", type=float, default=1.0)
423
+ parser.add_argument(
424
+ "--intensity-max",
425
+ type=float,
426
+ default=None,
427
+ help="optional max photon-count threshold",
428
+ )
429
+
430
+ parser.add_argument(
431
+ "--output-mode",
432
+ type=str,
433
+ choices=["ply", "csv", "both"],
434
+ default="csv",
435
+ help="export file mode",
436
+ )
437
+ parser.add_argument("--save-maps", type=_str2bool, default=True)
438
+ parser.add_argument("--show", type=_str2bool, default=False)
439
+ parser.add_argument("--show-point-size", type=float, default=1.5)
440
+
441
+ return parser
442
+
443
+
444
+ def main():
445
+ args = build_parser().parse_args()
446
+
447
+ K, D = _build_intrinsics(
448
+ fx=args.fx,
449
+ fy=args.fy,
450
+ cx=args.cx,
451
+ cy=args.cy,
452
+ k1=args.k1,
453
+ k2=args.k2,
454
+ p1=args.p1,
455
+ p2=args.p2,
456
+ )
457
+
458
+ if args.single_txt:
459
+ if args.single_out_base:
460
+ out_base = args.single_out_base
461
+ else:
462
+ base = os.path.splitext(os.path.basename(args.single_txt))[0]
463
+ out_base = os.path.join(args.output_dir, base)
464
+
465
+ os.makedirs(os.path.dirname(out_base) or ".", exist_ok=True)
466
+ info = convert_one_txt(
467
+ txt_path=args.single_txt,
468
+ output_base=out_base,
469
+ dt_ps=args.dt_ps,
470
+ depth_is_range=args.depth_is_range,
471
+ undistort_intensity=args.undistort_intensity,
472
+ K=K,
473
+ D=D,
474
+ min_range_m=args.min_range_m,
475
+ max_range_m=args.max_range_m,
476
+ intensity_min=args.intensity_min,
477
+ intensity_max=args.intensity_max,
478
+ output_mode=args.output_mode,
479
+ save_maps=args.save_maps,
480
+ show=args.show,
481
+ show_point_size=args.show_point_size,
482
+ )
483
+ print(
484
+ f"done: {os.path.basename(info['txt'])}, points={info['points']}, "
485
+ f"csv={info['csv'] or '-'}, ply={info['ply'] or '-'}, maps={info['maps'] or '-'}"
486
+ )
487
+ return
488
+
489
+ results = batch_convert(
490
+ input_dir=args.input_dir,
491
+ output_dir=args.output_dir,
492
+ pattern=args.pattern,
493
+ prefix=args.prefix,
494
+ start_index=args.start_index,
495
+ dt_ps=args.dt_ps,
496
+ depth_is_range=args.depth_is_range,
497
+ undistort_intensity=args.undistort_intensity,
498
+ K=K,
499
+ D=D,
500
+ min_range_m=args.min_range_m,
501
+ max_range_m=args.max_range_m,
502
+ intensity_min=args.intensity_min,
503
+ intensity_max=args.intensity_max,
504
+ output_mode=args.output_mode,
505
+ save_maps=args.save_maps,
506
+ )
507
+ print(f"done: converted {len(results)} files")
508
+
509
+ if args.show and results:
510
+ target = results[0]["txt"]
511
+ out_base = os.path.join(args.output_dir, "_preview_first")
512
+ info = convert_one_txt(
513
+ txt_path=target,
514
+ output_base=out_base,
515
+ dt_ps=args.dt_ps,
516
+ depth_is_range=args.depth_is_range,
517
+ undistort_intensity=args.undistort_intensity,
518
+ K=K,
519
+ D=D,
520
+ min_range_m=args.min_range_m,
521
+ max_range_m=args.max_range_m,
522
+ intensity_min=args.intensity_min,
523
+ intensity_max=args.intensity_max,
524
+ output_mode="ply",
525
+ save_maps=False,
526
+ show=True,
527
+ show_point_size=args.show_point_size,
528
+ )
529
+ print(f"preview shown for: {os.path.basename(info['txt'])}")
530
+
531
+
532
+ if __name__ == "__main__":
533
+ main()
codes/reconstruction/transientnerf/configs/test/captured/artbuilding3_five_views_quantitative.ini ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
File without changes
codes/reconstruction/transientnerf/loaders/loader_captured.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,680 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
File without changes
codes/reconstruction/transientnerf/misc/dataset_utils.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
File without changes
codes/reconstruction/transientnerf/radiance_fields/mlp.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
codes/simulator/generate_data_sim.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 处理data文件夹数据生成仿真数据的脚本
2
+ import include.simsp as simsp
3
+ import numpy as np
4
+ import cv2
5
+ import argparse
6
+ import os
7
+ import torch
8
+ from tqdm import tqdm
9
+ import re
10
+ from pathlib import Path
11
+ from concurrent.futures import ThreadPoolExecutor, as_completed
12
+ import threading
13
+ import time
14
+
15
+
16
+ def get_matching_files(images_dir, depth_dir):
17
+ """
18
+ 获取匹配的图像和深度文件对
19
+
20
+ Args:
21
+ images_dir (str): 图像文件夹路径
22
+ depth_dir (str): 深度图文件夹路径
23
+
24
+ Returns:
25
+ list: 匹配的文件对列表 [(image_path, depth_path, base_name), ...]
26
+ """
27
+ # 检查文件夹是否存在
28
+ if not os.path.exists(images_dir):
29
+ raise FileNotFoundError(f"图像文件夹不存在: {images_dir}")
30
+ if not os.path.exists(depth_dir):
31
+ raise FileNotFoundError(f"深度文件夹不存在: {depth_dir}")
32
+
33
+ # 获取所有图像文件
34
+ image_files = []
35
+ for ext in ['*.jpg', '*.jpeg', '*.JPG', '*.JPEG']:
36
+ image_files.extend(Path(images_dir).glob(ext))
37
+
38
+ # 获取所有深度文件
39
+ depth_files = []
40
+ for ext in ['*.png', '*.PNG']:
41
+ depth_files.extend(Path(depth_dir).glob(ext))
42
+
43
+ # 创建文件名到路径的映射
44
+ image_dict = {}
45
+ depth_dict = {}
46
+
47
+ for img_path in image_files:
48
+ # 提取基础文件名(不含扩展名)
49
+ base_name = img_path.stem
50
+ image_dict[base_name] = str(img_path)
51
+
52
+ for depth_path in depth_files:
53
+ # 提取基础文件名(不含扩展名)
54
+ base_name = depth_path.stem
55
+ depth_dict[base_name] = str(depth_path)
56
+
57
+ # 找到匹配的文件对
58
+ matched_pairs = []
59
+ for base_name in image_dict.keys():
60
+ if base_name in depth_dict:
61
+ matched_pairs.append((
62
+ image_dict[base_name],
63
+ depth_dict[base_name],
64
+ base_name
65
+ ))
66
+
67
+ print(f"找到 {len(matched_pairs)} 对匹配的文件")
68
+ return matched_pairs
69
+
70
+
71
+ def png_to_npy_depth(png_path, output_path=None):
72
+ """
73
+ 将PNG深度图转换为numpy数组格式
74
+
75
+ Args:
76
+ png_path (str): PNG深度图路径
77
+ output_path (str): 输出npy文件路径(可选)
78
+
79
+ Returns:
80
+ np.ndarray: 深度数组
81
+ """
82
+ # 读取PNG深度图
83
+ depth_img = cv2.imread(png_path, cv2.IMREAD_UNCHANGED)
84
+
85
+ if depth_img is None:
86
+ raise ValueError(f"无法读取深度图: {png_path}")
87
+
88
+ # 如果是3通道图像,转换为单通道
89
+ if len(depth_img.shape) == 3:
90
+ depth_img = cv2.cvtColor(depth_img, cv2.COLOR_BGR2GRAY)
91
+
92
+ # 转换为浮点数并归一化
93
+ depth_array = depth_img.astype(np.float64)
94
+
95
+ # 根据深度图的编码方式进行处理
96
+ # 假设PNG深度图使用16位编码,需要转换为实际深度值(米)
97
+ # 这里可能需要根据具体的深度图编码方式调整
98
+ if depth_array.max() > 1.0:
99
+ # 如果最大值大于1,假设是16位编码,转换为0-1范围
100
+ depth_array = depth_array / 65535.0
101
+
102
+ # 转换为实际深度值(假设最大深度为15米)
103
+ max_depth = 15.0
104
+ depth_array = depth_array * max_depth
105
+
106
+ # 保存为npy文件(如果指定了输出路径)
107
+ if output_path:
108
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
109
+ np.save(output_path, depth_array)
110
+
111
+ return depth_array
112
+
113
+
114
+ def generate_sim_data_from_png(image_path, depth_png_path, SBR=0.2, meanSigDetect=4, save_path=None):
115
+ """
116
+ 从PNG深度图和JPG图像生成仿真数据
117
+
118
+ Args:
119
+ image_path (str): RGB图像文件路径
120
+ depth_png_path (str): PNG深度图文件路径
121
+ SBR (float): 信号背景比 (默认0.2)
122
+ meanSigDetect (int): 每像素平均信号光子数 (推荐值2/3/4)
123
+ save_path (str): 数据保存路径 (.npz文件)
124
+
125
+ Returns:
126
+ tuple: (Z_true, depth_ssp, tBinMax, binDuration)
127
+ """
128
+ # 转换PNG深度图为numpy数组
129
+ Z_true = png_to_npy_depth(depth_png_path)
130
+
131
+ # 读取并处理RGB图像
132
+ rgb_img = cv2.imread(image_path)
133
+ if rgb_img is None:
134
+ raise ValueError(f"无法读取图像: {image_path}")
135
+
136
+ Alpha_true = cv2.cvtColor(rgb_img, cv2.COLOR_BGR2GRAY).astype(np.float64)
137
+
138
+ # 确保两个图像尺寸一致
139
+ if Z_true.shape != Alpha_true.shape:
140
+ # 将Alpha_true调整为与Z_true相同的尺寸
141
+ Alpha_true = cv2.resize(Alpha_true, (Z_true.shape[1], Z_true.shape[0]),
142
+ interpolation=cv2.INTER_AREA)
143
+
144
+ # 动态计算参数
145
+ zMax = int(np.max(Z_true) * 1.5) if np.max(Z_true) > 0 else 15
146
+ binDuration = zMax / 2e11
147
+
148
+ # 计算目标尺寸(保持长宽比,缩放到64像素)
149
+ target_size = 64
150
+ height, width = Z_true.shape
151
+ scale = target_size / min(height, width)
152
+ new_width = int(width * scale)
153
+ new_height = int(height * scale)
154
+
155
+ # 缩放图像
156
+ Z_true = cv2.resize(Z_true, (new_width, new_height), interpolation=cv2.INTER_AREA)
157
+ Alpha_true = cv2.resize(Alpha_true, (new_width, new_height), interpolation=cv2.INTER_AREA)
158
+
159
+ # 生成仿真数据
160
+ tBinMax, sigDetect, spad = simsp.generate_simdata(
161
+ Z_true, Alpha_true, SBR, meanSigDetect, save_path, zMax, binDuration
162
+ )
163
+
164
+ # 使用SSP算法进行深度估计
165
+ from include.singlephoton import SinglePhotonImaging
166
+ lr, lc = Z_true.shape
167
+ sp = SinglePhotonImaging(lr, lc, binDuration)
168
+ # depth_ssp = sp.ssp(spad)
169
+
170
+ # 保存结果
171
+ if save_path:
172
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
173
+ dic_data = {
174
+ # "depth_ssp": depth_ssp,
175
+ "Alpha_true": Alpha_true,
176
+ "Z_true": Z_true,
177
+ "tBinMax": tBinMax,
178
+ "binDuration": binDuration,
179
+ "spad_data": spad.data,
180
+ "spad_indices": spad.indices,
181
+ "spad_indptr": spad.indptr,
182
+ "spad_shape": spad.shape,
183
+ "sigDetect_data": sigDetect,
184
+ }
185
+ np.savez_compressed(save_path, **dic_data)
186
+
187
+ # return Z_true, depth_ssp, tBinMax, binDuration
188
+ return Z_true, Alpha_true, tBinMax, binDuration
189
+
190
+
191
+ def process_single_file(args_tuple):
192
+ """
193
+ 处理单个文件的线程安全函数
194
+
195
+ Args:
196
+ args_tuple: (image_path, depth_path, base_name, output_dir, sbr, meanSigDetect, thread_id)
197
+
198
+ Returns:
199
+ tuple: (success, base_name, error_msg)
200
+ """
201
+ image_path, depth_path, base_name, output_dir, sbr, meanSigDetect, thread_id = args_tuple
202
+
203
+ try:
204
+ output_path = os.path.join(output_dir, f"{base_name}.npz")
205
+
206
+ # 跳过已存在的文件
207
+ if os.path.exists(output_path):
208
+ return True, base_name, f"文件已存在,跳过: {base_name}"
209
+
210
+ # 生成仿真数据
211
+ generate_sim_data_from_png(
212
+ image_path, depth_path,
213
+ sbr, meanSigDetect,
214
+ output_path
215
+ )
216
+
217
+ return True, base_name, None
218
+
219
+ except Exception as e:
220
+ # 清理GPU内存(如果使用了GPU)
221
+ if torch.cuda.is_available():
222
+ torch.cuda.empty_cache()
223
+ return False, base_name, str(e)
224
+
225
+
226
+ def process_files_multithread(matched_files, output_dir, sbr, meanSigDetect, max_workers=4):
227
+ """
228
+ 多线程处理文件
229
+
230
+ Args:
231
+ matched_files: 匹配的文件对列表
232
+ output_dir: 输出目录
233
+ sbr: 信噪比
234
+ meanSigDetect: 平均检测信号强度
235
+ max_workers: 最大线程数
236
+
237
+ Returns:
238
+ tuple: (success_count, error_count, error_files)
239
+ """
240
+ success_count = 0
241
+ error_count = 0
242
+ error_files = []
243
+
244
+ # 准备任务参数
245
+ tasks = []
246
+ for i, (image_path, depth_path, base_name) in enumerate(matched_files):
247
+ task_args = (image_path, depth_path, base_name, output_dir, sbr, meanSigDetect, i)
248
+ tasks.append(task_args)
249
+
250
+ # 使用线程池执行任务
251
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
252
+ # 提交所有任务
253
+ future_to_task = {executor.submit(process_single_file, task): task for task in tasks}
254
+
255
+ # 使用tqdm显示进度
256
+ with tqdm(total=len(tasks), desc="多线程处理进度") as pbar:
257
+ for future in as_completed(future_to_task):
258
+ task = future_to_task[future]
259
+ try:
260
+ success, base_name, error_msg = future.result()
261
+ if success:
262
+ success_count += 1
263
+ if error_msg: # 跳过的文件
264
+ pbar.set_postfix_str(f"跳过: {base_name}")
265
+ else:
266
+ error_count += 1
267
+ error_files.append((base_name, error_msg))
268
+ pbar.set_postfix_str(f"错误: {base_name}")
269
+ print(f"\n处理 {base_name} 时发生错误: {error_msg}")
270
+
271
+ except Exception as e:
272
+ error_count += 1
273
+ base_name = task[2]
274
+ error_files.append((base_name, str(e)))
275
+ pbar.set_postfix_str(f"异常: {base_name}")
276
+ print(f"\n处理 {base_name} 时发生异常: {str(e)}")
277
+
278
+ pbar.update(1)
279
+
280
+ return success_count, error_count, error_files
281
+
282
+
283
+
284
+ def main():
285
+ parser = argparse.ArgumentParser(description='处理data文件夹生成仿真数据')
286
+ parser.add_argument('--sbr', type=float, default=0.5,
287
+ help='信噪比 (默认: 0.5)')
288
+ parser.add_argument('--meanSigDetect', type=float, default=2,
289
+ help='平均检测信号强度 (默认: 2)')
290
+ parser.add_argument('--data_dir', type=str, default='./data',
291
+ help='数据文件夹路径 (默认: ./data)')
292
+ parser.add_argument('--output_dir', type=str, default='./output_data',
293
+ help='输出文件夹路径 (默认: ./output_data)')
294
+ parser.add_argument('--max_files', type=int, default=None,
295
+ help='最大处理文件数量 (默认: 处理所有文件)')
296
+ parser.add_argument('--threads', type=int, default=16,
297
+ help='线程数量 (默认: 4)')
298
+ parser.add_argument('--single_thread', action='store_true',
299
+ help='使用单线程模式 (默认: 使用多线程)')
300
+
301
+ args = parser.parse_args()
302
+
303
+ # 设置路径
304
+ images_dir = os.path.join(args.data_dir, 'images')
305
+ depth_dir = os.path.join(args.data_dir, 'depthpng')
306
+ output_dir = os.path.join(args.output_dir, f"{args.sbr}_{args.meanSigDetect}")
307
+
308
+ print(f"图像目录: {images_dir}")
309
+ print(f"深度目录: {depth_dir}")
310
+ print(f"输出目录: {output_dir}")
311
+
312
+ # 验证线程数设置
313
+ if args.threads < 1:
314
+ print("错误: 线程数必须大于0")
315
+ return
316
+
317
+ # 显示处理模式
318
+ if args.single_thread:
319
+ print("使用单线程模式")
320
+ max_workers = 1
321
+ else:
322
+ max_workers = args.threads
323
+ print(f"使用多线程模式,线程数: {max_workers}")
324
+
325
+ # 创建输出目录
326
+ os.makedirs(output_dir, exist_ok=True)
327
+
328
+ # 获取匹配的文件对
329
+ try:
330
+ matched_files = get_matching_files(images_dir, depth_dir)
331
+ except FileNotFoundError as e:
332
+ print(f"错误: {e}")
333
+ return
334
+
335
+ if not matched_files:
336
+ print("未找到匹配的文件对")
337
+ return
338
+
339
+ # 限制处理文件数量
340
+ if args.max_files:
341
+ matched_files = matched_files[:args.max_files]
342
+ print(f"限制处理文件数量为: {args.max_files}")
343
+
344
+ # 记录开始时间
345
+ start_time = time.time()
346
+
347
+ # 选择处理模式
348
+ if args.single_thread or max_workers == 1:
349
+ # 单线程模式(原始逻辑)
350
+ success_count = 0
351
+ error_count = 0
352
+ error_files = []
353
+
354
+ for image_path, depth_path, base_name in tqdm(matched_files, desc="单线程处理进度"):
355
+ output_path = os.path.join(output_dir, f"{base_name}.npz")
356
+
357
+ # 跳过已存在的文件
358
+ if os.path.exists(output_path):
359
+ print(f"跳过已存在的文件: {base_name}")
360
+ continue
361
+
362
+ try:
363
+ generate_sim_data_from_png(
364
+ image_path, depth_path,
365
+ args.sbr, args.meanSigDetect,
366
+ output_path
367
+ )
368
+ success_count += 1
369
+
370
+ except Exception as e:
371
+ print(f"处理 {base_name} 时发生错误: {str(e)}")
372
+ error_count += 1
373
+ error_files.append((base_name, str(e)))
374
+ torch.cuda.empty_cache() # 清理GPU内存
375
+ else:
376
+ # 多线程模式
377
+ success_count, error_count, error_files = process_files_multithread(
378
+ matched_files, output_dir, args.sbr, args.meanSigDetect, max_workers
379
+ )
380
+
381
+ # 计算处理时间
382
+ end_time = time.time()
383
+ total_time = end_time - start_time
384
+
385
+ print(f"\n处理完成!")
386
+ print(f"成功处理: {success_count} 个文件")
387
+ print(f"处理失败: {error_count} 个文件")
388
+ print(f"总处理时间: {total_time:.2f} 秒")
389
+ print(f"平均每文件: {total_time/len(matched_files):.2f} 秒")
390
+ print(f"输出目录: {output_dir}")
391
+
392
+ # 显示错误文件详情
393
+ if error_files:
394
+ print(f"\n错误文件详情:")
395
+ for base_name, error_msg in error_files[:10]: # 只显示前10个错误
396
+ print(f" {base_name}: {error_msg}")
397
+ if len(error_files) > 10:
398
+ print(f" ... 还有 {len(error_files) - 10} 个错误文件")
399
+
400
+
401
+ if __name__ == "__main__":
402
+ main()
codes/simulator/include/simsp.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+ import os
4
+ from scipy.sparse import csc_matrix
5
+ from include.singlephoton import SinglePhotonImaging
6
+
7
+
8
+ # import os
9
+ def fcn_PoissonRV(lambda_, ni=None, nj=None):
10
+ """
11
+ 生成泊松分布随机数矩阵 (向量化实现)
12
+
13
+ 参数:
14
+ lambda_ (float/array): 泊松分布参数λ(标量或二维数组)
15
+ ni (int): 输出矩阵的行数(当lambda为标量时必填)
16
+ nj (int): 输出矩阵的列数(当lambda为标量时必填)
17
+
18
+ 返回:
19
+ np.ndarray: 生成的泊松随机数矩阵[ni, nj]
20
+
21
+ 异常:
22
+ ValueError: 输入参数不符合要求时抛出
23
+ """
24
+ # ========================= 参数验证 =========================
25
+ # 情况1:未指定ni/nj时,lambda必须是二维数组
26
+ if ni is None and nj is None:
27
+ if not isinstance(lambda_, np.ndarray) or lambda_.ndim != 2:
28
+ raise ValueError("当未指定ni/nj时,lambda必须是二维数组!")
29
+ ni, nj = lambda_.shape
30
+
31
+ # 情况2:指定了ni/nj
32
+ elif ni is not None and nj is not None:
33
+ # 如果lambda是标量,扩展为指定大小的矩阵
34
+ if np.isscalar(lambda_):
35
+ lambda_ = np.full((ni, nj), lambda_)
36
+ # 如果lambda是数组,验证形状是否匹配
37
+ elif isinstance(lambda_, np.ndarray) and lambda_.shape != (ni, nj):
38
+ raise ValueError(f"lambda形状{lambda_.shape}与({ni},{nj})不匹配!")
39
+
40
+ # 情况3:参数不完整
41
+ else:
42
+ raise ValueError("必须同时指定ni和nj,或都不指定!")
43
+
44
+ # ========================= 初始化 =========================
45
+ ks1 = np.zeros((ni, nj), dtype=int) # 结果矩阵
46
+ ks2 = np.ones((ni, nj), dtype=int) # 比较矩阵
47
+ produ = np.ones((ni, nj)) # 乘积累加器
48
+
49
+ # ========================= 主循环 =========================
50
+ while np.any(ks1 != ks2):
51
+ # 更新乘积(向量化操作)
52
+ produ *= np.random.rand(ni, nj)
53
+
54
+ # 保存当前状态
55
+ ks2 = ks1.copy()
56
+
57
+ # 找出需要增加计数的位置(向量化掩码操作)
58
+ mask = produ >= np.exp(-lambda_)
59
+ ks1[mask] += 1
60
+
61
+ return ks1
62
+
63
+
64
+ def tof2spad(tof, binnum):
65
+ h, w = tof.shape
66
+
67
+ # 将 data_processed 重塑为列向量
68
+ tof = tof.T
69
+ data = tof.reshape(h * w)
70
+
71
+ # 创建一个大小为 h * w 行,10000 列的零矩阵
72
+ spad = np.zeros((h * w, int(binnum)), dtype=float)
73
+
74
+ # 遍历 data
75
+ for i in range(h * w):
76
+ d = data[i]
77
+ for j in range(len(d)):
78
+ if int(d[j] - 1) < binnum:
79
+ spad[i, int(d[j] - 1)] += 1
80
+
81
+ spad = csc_matrix(spad)
82
+ return spad
83
+
84
+
85
+ def generate_simdata(
86
+ Z_true,
87
+ Alpha_true,
88
+ SBR=0.2,
89
+ meanSigDetect=2,
90
+ save_path=None,
91
+ zMax=15,
92
+ binDuration=8e-12,
93
+ ):
94
+ """
95
+ 生成单光子数据集仿真数据(Python版本)
96
+
97
+ 参数:
98
+ Z_true (array): 深度真值
99
+ Alpha_true (array): 反射率真值
100
+ SBR (float): 信号背景比 (默认0.2)
101
+ meanSigDetect (int): 每像素平均信号光子数 (推荐值2/3/4)
102
+ save_path (str): 数据保存路径 (.mat文件)
103
+
104
+ 返回:
105
+ tuple: (tBinMax, binDuration, sigDetect, totDetect)
106
+ tBinMax (int): 最大时间bin数
107
+ binDuration (float): 单个时间bin持续时间 (秒)
108
+ sigDetect (np.ndarray): 信号光子
109
+ totDetect (np.ndarray): 检测事件对象数组 [H,W] (每个元素包含时间bin序列)
110
+ """
111
+ # 第一阶段: 物理参数配置
112
+ # 场景参数
113
+ # zMax = 15.0 # 最大探测距离(米)
114
+ # binDuration = 8e-12 # 单个时间bin持续时间(秒)
115
+ pulseRMS = 270 / 8 # 脉冲RMS宽度(时间bin数)
116
+
117
+ # 计算衍生参数
118
+ ttd = 3e8 * binDuration / 2 # 时间到距离转换因子 (米/bin)
119
+ tBinMax = int(round(zMax / ttd)) # 最大时间bin数
120
+ pulseSTD = pulseRMS / 2 # 高斯脉冲标准差
121
+
122
+ # print("tBinMax:",tBinMax)
123
+
124
+ # 第二阶段: 信号光子生成
125
+ # 计算时间维度真实值
126
+ T_true = np.floor(Z_true / ttd).astype(int)
127
+
128
+ # 计算总帧数
129
+ numFrames = int(meanSigDetect * 500)
130
+
131
+ # 标准化反射率参数
132
+ Lr, Lc = Alpha_true.shape
133
+ Alpha_true = meanSigDetect * Alpha_true / np.mean(Alpha_true) / numFrames
134
+
135
+ # 生成信号光子数(泊松分布)
136
+ numSigDetect = fcn_PoissonRV(numFrames * Alpha_true)
137
+ actual_mean = np.mean(numSigDetect)
138
+ sigDetect = np.empty((Lr, Lc), dtype=object)
139
+ sampMean = np.zeros((Lr, Lc))
140
+
141
+ # 遍历每个像素生成时间分布
142
+ for i in range(Lr):
143
+ for j in range(Lc):
144
+ mu = T_true[i, j]
145
+ n = numSigDetect[i, j]
146
+ # 生成高斯分布时间偏移
147
+ tempVect = np.round(mu + pulseSTD * np.random.randn(n)).astype(int)
148
+ sampMean[i, j] = np.mean(tempVect) if n > 0 else 0
149
+ sigDetect[i, j] = tempVect
150
+
151
+ # 第三阶段: 背景噪声生成
152
+ # 计算背景光子率
153
+ bgndRate = actual_mean / numFrames / SBR
154
+
155
+ # 生成背景光子数
156
+ numBgndDetect = fcn_PoissonRV(numFrames * bgndRate, Lr, Lc)
157
+ bgndDetect = np.empty((Lr, Lc), dtype=object)
158
+
159
+ # 生成均匀分布时间
160
+ for i in range(Lr):
161
+ for j in range(Lc):
162
+ n = numBgndDetect[i, j]
163
+ bgndDetect[i, j] = np.random.randint(0, tBinMax, n)
164
+
165
+ # 第四阶段: 数据合并与后处理
166
+ totDetect = np.empty((Lr, Lc), dtype=object)
167
+ for i in range(Lr):
168
+ for j in range(Lc):
169
+ combined = np.concatenate((sigDetect[i, j], bgndDetect[i, j]))
170
+ combined = np.sort(combined)
171
+ combined = combined[combined > 0] # 移除非法时间bin
172
+ totDetect[i, j] = combined
173
+
174
+ spad = tof2spad(totDetect, tBinMax)
175
+ sigDetect = tof2spad(sigDetect, tBinMax)
176
+
177
+ return tBinMax, sigDetect, spad
178
+
179
+ # 补充泊松生成函数(原型实现)
180
+ def fcn_PoissonRV(lamda, *shape):
181
+ if not shape:
182
+ return np.random.poisson(lamda)
183
+ else:
184
+ return np.random.poisson(lamda, shape)
185
+
186
+
187
+ import cv2
188
+ import numpy as np
189
+ import os
190
+ from scipy.io import savemat
191
+ from pathlib import Path
192
+
193
+
194
+
195
+ def generate_sim_imageNet(
196
+ depth_path, rgb_path, SBR=0.2, meanSigDetect=4, save_path=None
197
+ ):
198
+ """
199
+ 生成cityscapes数据集仿真数据(Python版本)
200
+
201
+ 参数:
202
+ depth_path (str): 深度图文件路径 (npz)
203
+ rgb_path (str): RGB图像文件路径
204
+ SBR (float): 信号背景比 (默认0.2)
205
+ meanSigDetect (int): 每像素平均信号光子数 (推荐值2/3/4)
206
+ save_path (str): 数据保存路径 (.npz文件)
207
+
208
+ 返回:
209
+ tuple: (Z_true, totDetect, tBinMax, binDuration)
210
+ Z_true (np.ndarray): 真实深度图矩阵 [H,W] (单位:米)
211
+ totDetect (np.ndarray): 检测事件对象数组 [H,W] (每个元素包含时间bin序列)
212
+ tBinMax (int): 最大时间bin数
213
+ binDuration (float): 单个时间bin持续时间 (秒)
214
+
215
+ PS:
216
+ 由于使用DepthAnything数据生成的深度图,是三通道的,所以在处理前需要先将其转换为单通道的
217
+ 为了保证数据兼容性,所以统一提取第一个通道作为深度数据
218
+ """
219
+ # 第一阶段: 基础数据加载与参数初始化
220
+ # 读取深度图并转换为米单位
221
+ # 读取深度图的最大深度
222
+
223
+ # binDuration = 4e-10
224
+ # zMax = 15
225
+ # binDuration = zMax/1.5e11
226
+
227
+ # 读取深度数据
228
+ Z_true = np.load(depth_path, allow_pickle=True).astype(np.float64)
229
+ if Z_true.ndim == 3:
230
+ Z_true = Z_true[:, :, 0]
231
+
232
+ # 1. 避免除零和过小值
233
+ threshold = 1e-10
234
+ Z_affine_safe = np.clip(Z_true, threshold, None)
235
+
236
+ # 2. 取倒数得到缩放深度
237
+ Z_scaled = 1 / Z_affine_safe
238
+ max_value = np.max(Z_scaled)
239
+ min_value = np.min(Z_scaled)
240
+
241
+ # # 3. 截断离群值(可选)
242
+ # lower, upper = np.percentile(Z_scaled, [1, 99])
243
+ # Z_clipped = np.clip(Z_scaled, lower, upper)
244
+
245
+ # 4. 归一化到[0,1]
246
+ Z_normalized = (Z_scaled - min_value) / (max_value - min_value)
247
+
248
+ # 5. 反转方向:近处亮,远处暗
249
+ Z_depth = (1 - Z_normalized)*max_value
250
+
251
+ # zMax = np.max(Z_true)
252
+ zMax = int(np.max(Z_true)*1.5)
253
+ binDuration = zMax / 2e11
254
+
255
+ # 验证时间箱数量
256
+ ttd = 3e8 * binDuration / 2 # 时间到距离转换因子 (米/bin)
257
+ tBinMax = int(round(zMax / ttd)) # 最大时间bin数
258
+ print(f"tBinMax: {tBinMax}")
259
+
260
+ # 计算深度范围 (必须在缩放前获取原始深度最大值)
261
+ # zMax = int(np.max(Z_true) + 1)
262
+ # zMax = 15
263
+ # binDuration = 10e-11
264
+
265
+
266
+ # 计算目标尺寸(保持长宽比)
267
+ target_size = 64
268
+ height, width = Z_true.shape
269
+ scale = target_size / min(height, width)
270
+ new_width = int(width * scale)
271
+ new_height = int(height * scale)
272
+
273
+ # 缩放深度图(使用INTER_AREA保持精度)
274
+ Z_true = cv2.resize(
275
+ Z_true,
276
+ (new_width, new_height),
277
+ interpolation=cv2.INTER_AREA
278
+ )
279
+
280
+ # 读取并处理RGB图像
281
+ rgb_img = cv2.imread(rgb_path)
282
+ Alpha_true = cv2.cvtColor(rgb_img, cv2.COLOR_BGR2GRAY).astype(np.float64)
283
+
284
+ # 以相同比例缩放灰度图
285
+ Alpha_true = cv2.resize(
286
+ Alpha_true,
287
+ (new_width, new_height),
288
+ interpolation=cv2.INTER_AREA
289
+ )
290
+
291
+ # # 输出最终尺寸信息
292
+ # print(f"深度图最终尺寸: {Z_true.shape}")
293
+ # print(f"反射率图最终尺寸: {Alpha_true.shape}")
294
+ # # 动态计算zMax(忽略深度为0的无效点)
295
+ # valid_depths = Z_true[Z_true > 0] # 筛选有效深度点(>0)
296
+ # if valid_depths.size > 0:
297
+ # zMax = np.max(valid_depths) * 2 # 取最大值并增加10%余量
298
+ # else:
299
+ # zMax = 15 # 默认值(无有效点时使用)
300
+
301
+ tBinMax, sigDetect, spad = generate_simdata(
302
+ Z_true, Alpha_true, SBR, meanSigDetect, save_path, zMax, binDuration
303
+ )
304
+
305
+ lr, lc = Z_true.shape
306
+
307
+ sp = SinglePhotonImaging(lr, lc, binDuration)
308
+ depth = sp.ssp(spad)
309
+
310
+ if save_path:
311
+ # 创建保存目录(如果不存在)
312
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
313
+ dic_data = {}
314
+ dic_data["depth_ssp"] = depth
315
+ dic_data["Z_true"] = Z_true
316
+ dic_data["tBinMax"] = tBinMax
317
+ dic_data["binDuration"] = binDuration
318
+ dic_data["spad_data"] = spad.data
319
+ dic_data["spad_indices"] = spad.indices
320
+ dic_data["spad_indptr"] = spad.indptr
321
+ dic_data["spad_shape"] = spad.shape
322
+ dic_data["sigDetect_data"] = sigDetect
323
+ # scipy.io.savemat(save_path, dic_data)
324
+ np.savez_compressed(save_path, **dic_data)
codes/simulator/include/singlephoton.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ # import matlab.engine
3
+ from .SSP.ssp import get_ssp_depth
4
+
5
+ c = 3e8
6
+
7
+
8
+ class SinglePhotonImaging:
9
+ def __init__(self, lr: int, lc: int, tp: float):
10
+ """
11
+ 初始化深度估计器
12
+
13
+ 参数:
14
+ lr: 图像行数
15
+ lc: 图像列数
16
+ tp: 时间bin持续时间 (秒)
17
+ """
18
+ self.lr = lr
19
+ self.lc = lc
20
+ self.tp = tp
21
+
22
+ def _spad2tof(self, spad: np.ndarray) -> np.ndarray:
23
+ """
24
+ 将稀疏SPAD数据转换为时间飞行(TOF)对象数组 [内部方法]
25
+
26
+ 参数:
27
+ spad: 稀疏SPAD数据矩阵 [N, M]
28
+
29
+ 返回:
30
+ np.ndarray: TOF对象数组 [lr, lc],每个元素为时间bin数组
31
+ """
32
+ rows, cols = spad.nonzero()
33
+ values = spad.data
34
+ tof = np.empty((self.lr, self.lc), dtype=np.ndarray)
35
+
36
+ for i in range(self.lr * self.lc):
37
+ indices = np.where(rows == i)[0]
38
+ ph = []
39
+ for j in indices:
40
+ ph += [int(cols[j])] * int(values[j])
41
+
42
+ ph = np.array([ph]).T
43
+
44
+ x = i % self.lc
45
+ y = i // self.lc
46
+
47
+ tof[x, y] = ph
48
+
49
+ return tof
50
+
51
+ def _time_to_depth(self, time_data: np.ndarray, time_bin: float) -> np.ndarray:
52
+ """统一时间到深度转换"""
53
+ return time_data * c / 2 * time_bin
54
+
55
+ def max_hist(self, spads: np.ndarray) -> np.ndarray:
56
+ """
57
+ 通过滑动窗口均值法获取深度图
58
+
59
+ 参数:
60
+ spads: 稀疏SPAD数据矩阵 [N, T]
61
+
62
+ 返回:
63
+ np.ndarray: 深度图矩阵 [lc, lr] (单位:米)
64
+ """
65
+ print("Max Hist Processing...")
66
+
67
+ spads_dense = spads.todense()
68
+ max_histogram_mean = np.empty(self.lr * self.lc, dtype=float)
69
+
70
+ for i in range(self.lr * self.lc):
71
+ data = np.ascontiguousarray(spads_dense[i, :]).ravel()
72
+ max_index = np.argmax(data)
73
+ max_histogram_mean[i] = max_index
74
+
75
+ depth = self._time_to_depth(
76
+ max_histogram_mean.reshape(self.lr, self.lc).T, self.tp
77
+ )
78
+
79
+ return depth
80
+
81
+ # def shin(self, spads: np.ndarray) -> np.ndarray:
82
+ # """
83
+ # 使用Shin算法估计深度图
84
+
85
+ # 参数:
86
+ # spads: 稀疏SPAD数据矩阵 [N, T]
87
+
88
+ # 返回:
89
+ # np.ndarray: 深度图矩阵 [lc, lr] (单位:米)
90
+ # """
91
+ # print("Shin Processing...")
92
+
93
+ # tofs = self._spad2tof(spads)
94
+ # eng = matlab.engine.start_matlab()
95
+ # eng.addpath(r"matlab\fcns_Shin")
96
+ # matlab_tofs = eng.eval("cell(1, 3136)", nargout=1)
97
+ # matlab_tofs = [tof for row in tofs for tof in row]
98
+
99
+ # tof_shin = np.array(eng.cal_Shin(matlab_tofs))
100
+ # eng.quit()
101
+
102
+ # depth = self._time_to_depth(tof_shin, self.tp)
103
+ # return depth
104
+
105
+ # def rapp(
106
+ # self, spads: np.ndarray, signal_per_pixel: float, frame_num: int
107
+ # ) -> np.ndarray:
108
+ # """
109
+ # 使用Rapp算法估计深度图
110
+
111
+ # 参数:
112
+ # spads: 稀疏SPAD数据矩阵 [N, T]
113
+ # signal_per_pixel: 每像素平均信号光子数
114
+ # frame_num: 总帧数
115
+
116
+ # 返回:
117
+ # np.ndarray: 深度图矩阵 [lc, lr] (单位:米)
118
+ # """
119
+ # print("Rapp Processing...")
120
+
121
+ # binnum = spads.shape[1]
122
+ # tofs = self._spad2tof(spads)
123
+
124
+ # sbr = 0.2
125
+ # perframenum = 50.0
126
+ # numFrames = perframenum * frame_num
127
+ # eng = matlab.engine.start_matlab()
128
+ # eng.addpath(r"matlab\fcns_Rapp")
129
+
130
+ # matlab_tofs = eng.eval("cell(1, 3136)", nargout=1)
131
+ # matlab_tofs = [tof for row in tofs for tof in row]
132
+
133
+ # tof_rapp = np.array(
134
+ # eng.cal_Rapp_py(
135
+ # matlab_tofs,
136
+ # signal_per_pixel,
137
+ # numFrames,
138
+ # sbr,
139
+ # float(self.tp),
140
+ # float(binnum),
141
+ # )
142
+ # )
143
+
144
+ # eng.quit()
145
+
146
+ # depth = self._time_to_depth(tof_rapp, self.tp)
147
+
148
+ # return depth
149
+
150
+ # def li(self, spads: np.ndarray) -> np.ndarray:
151
+ # """
152
+ # 使用Li算法估计深度图
153
+
154
+ # 参数:
155
+ # spads: 稀疏SPAD数据矩阵 [N, T]
156
+
157
+ # 返回:
158
+ # np.ndarray: 深度图矩阵 [lc, lr] (单位:米)
159
+ # """
160
+ # print("Li Processing...")
161
+ # eng = matlab.engine.start_matlab()
162
+ # eng.addpath(r"matlab\fcns_Li", nargout=0)
163
+
164
+ # # 直接使用原始SPAD数据
165
+ # spads = spads.todense()
166
+ # tof_li = np.array(
167
+ # eng.cal_Li_py(
168
+ # spads,
169
+ # float(self.tp),
170
+ # float(spads.shape[1]),
171
+ # nargout=1,
172
+ # )
173
+ # )
174
+ # eng.quit()
175
+
176
+ # depth = self._time_to_depth(tof_li, self.tp)
177
+
178
+ # return depth
179
+
180
+ def ssp(self, spads: np.ndarray) -> np.ndarray:
181
+ """
182
+ 使用SSP算法估计深度图
183
+
184
+ 参数:
185
+ spads: 稀疏SPAD数据矩阵 [N, T]
186
+
187
+ 返回:
188
+ np.ndarray: 深度图矩阵 [lc, lr] (单位:米)
189
+ """
190
+ # print("SSP Processing...")
191
+ tp = self.tp
192
+ tr = spads.shape[1]
193
+ depth = get_ssp_depth(spads, tr, tp, self.lr, self.lc)
194
+
195
+ return depth