-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualize_benchmark_web.py
More file actions
2402 lines (2026 loc) · 90.1 KB
/
Copy pathvisualize_benchmark_web.py
File metadata and controls
2402 lines (2026 loc) · 90.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Web-based Benchmark GT Point Cloud Viewer.
Reads scene indices from benchmark/scene_indices/, loads GT depth + pose + intrinsics,
unprojects to 3D point cloud, and displays in an interactive Three.js viewer.
Supports filtering by dataset, view density (sparse/medium/dense), environment,
dynamics, and view type.
Usage:
python visualize_benchmark_web.py
python visualize_benchmark_web.py --benchmark-root SpatialBenchmark --port 8082
"""
import argparse
import io
import json
import os
os.environ.setdefault('OPENCV_IO_ENABLE_OPENEXR', '1') # 启用 EXR 支持 (Waymo 深度图)
import struct
import sys
from functools import lru_cache
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from benchmark.datasets.benchmark_dataset import BenchmarkDataset
from benchmark.utils.visualization import save_pointcloud_glb
import cv2
import numpy as np
from fastapi import FastAPI, Query
from fastapi.responses import HTMLResponse, JSONResponse, Response
import uvicorn
# ── Config ──
SCENE_INDEX_DIR: Path = Path("benchmark/scene_indices")
SCENE_INDEX_PATH: Path = SCENE_INDEX_DIR / "all_scenes.json"
BENCHMARK_ROOT: Path = Path("SpatialBenchmark")
DATA_ROOTS: dict = {} # Legacy placeholder; unified reader uses BENCHMARK_ROOT.
Z_FAR_DEFAULT = 10.0
RESOLUTION = (518, 378) # (W, H) — same as benchmark configs
GLB_OUTPUT_DIR: Path = Path("glb_output")
# Per-dataset default z_far — kept in sync with DEFAULT_Z_FAR in data_readers.py
DATASET_Z_FAR: dict = {
"droid": 1.0, # DroidReader
"ropedia": 5.0, # RopediaReader
"tum": 5.0, # TumReader
"nrgbd": 10.0, # NrgbdReader
"7scenes": 10.0, # SevenScenesReader
"adt": 10.0, # AdtReader
"robotwin": 3.0, # RoboTwinReader
"rlbench": 3.0, # RLBenchReader
"robolab": 3.0, # RoboLabReader
"dtu": 3.0, # DtuReader
"eth3d": 30.0, # Eth3dReader
"tanks_and_temples": 30.0, # TanksAndTemplesReader
"omniworld": 50.0, # OmniworldReader
"lingbot": 20.0, # LingbotReader
"hiroom": 10.0, # HiroomReader
"scannetpp": 10.0, # ScannetppReader
"spatialvid": 50.0, # SpatialVidReader
"vkitti": 80.0, # VkittiReader
"waymo": 50.0, # WaymoReader
"kitti_odometry": 80.0, # KittiOdometryReader
}
app = FastAPI(title="Benchmark GT Point Cloud Viewer")
# ── Scene index cache ──
_all_scenes: list = [] # flat list of scene dicts
_dataset_names: list = [] # unique dataset names
_benchmark_dataset: BenchmarkDataset | None = None
_scene_to_dataset_idx: dict = {}
def _load_all_scenes():
"""Load all scene indices from JSON files."""
global _all_scenes, _dataset_names
index_path = SCENE_INDEX_PATH
if index_path.exists():
with open(index_path) as f:
_all_scenes = json.load(f)
else:
# Fallback: merge individual files
_all_scenes = []
for p in sorted(SCENE_INDEX_DIR.glob("*_scenes.json")):
if p.name == "all_scenes.json":
continue
with open(p) as f:
_all_scenes.extend(json.load(f))
_dataset_names = sorted(set(s["source_dataset"] for s in _all_scenes))
print(f"[SceneIndex] Loaded {len(_all_scenes)} scenes from {len(_dataset_names)} datasets")
def _init_benchmark_dataset():
"""Initialize the same unified loader used by benchmark/evaluation."""
global _benchmark_dataset, _scene_to_dataset_idx, DATASET_Z_FAR
_benchmark_dataset = BenchmarkDataset(
scene_index_path=str(SCENE_INDEX_PATH),
benchmark_root=str(BENCHMARK_ROOT),
tags=None,
tag_operator="AND",
max_scenes=None,
)
_scene_to_dataset_idx = {
s["scene_id"]: i for i, s in enumerate(_benchmark_dataset.scenes)
}
DATASET_Z_FAR = {
name: float(reader.DEFAULT_Z_FAR)
for name, reader in _benchmark_dataset._readers.items()
}
# ---------------------------------------------------------------------------
# Data loading helpers
# ---------------------------------------------------------------------------
def _get_data_root(dataset: str) -> Path:
density = "unknown"
return BENCHMARK_ROOT / density / dataset
def _load_scene_data_raw(scene: dict, z_far: float, use_depth_mask: bool = True, conf_threshold: float = 0.0):
"""Load a scene through BenchmarkDataset's current unified data pipeline.
Current SpatialBenchmark layout:
<benchmark_root>/<density>/<dataset>/<scene_path>/{images,depths,poses,intrinsics,...}
This function adapts the BenchmarkDataset output to the older web-viewer
return shape: lists of RGB uint8 images, depth maps, c2w extrinsics, and
intrinsics. Dataset-specific path and depth decoding logic lives in
benchmark/datasets/data_readers.py.
"""
if _benchmark_dataset is None:
raise RuntimeError("BenchmarkDataset is not initialized")
dataset = scene["source_dataset"]
scene_id = scene["scene_id"]
ds_idx = _scene_to_dataset_idx.get(scene_id)
if ds_idx is None:
raise KeyError(f"Scene {scene_id!r} not found in BenchmarkDataset")
reader = _benchmark_dataset._readers.get(dataset)
if reader is None:
raise ValueError(f"No reader for dataset {dataset!r}")
# Endpoint controls are applied by temporarily overriding the reader settings
# before BenchmarkDataset calls reader.read_scene().
had_z_far = 'DEFAULT_Z_FAR' in reader.__dict__
orig_z_far = getattr(reader, 'DEFAULT_Z_FAR', None)
had_depth_masks = '_USE_DEPTH_MASKS' in reader.__dict__
orig_depth_masks = getattr(reader, '_USE_DEPTH_MASKS', True)
had_aliasing_masks = '_USE_ALIASING_MASKS' in reader.__dict__
orig_aliasing_masks = getattr(reader, '_USE_ALIASING_MASKS', True)
had_conf = 'conf_threshold' in reader.__dict__
orig_conf = getattr(reader, 'conf_threshold', None)
try:
reader.DEFAULT_Z_FAR = float(z_far)
if not use_depth_mask:
reader._USE_DEPTH_MASKS = False
reader._USE_ALIASING_MASKS = False
if hasattr(reader, 'conf_threshold'):
reader.conf_threshold = float(conf_threshold)
loaded = _benchmark_dataset[ds_idx]
finally:
if had_z_far:
reader.DEFAULT_Z_FAR = orig_z_far
elif 'DEFAULT_Z_FAR' in reader.__dict__:
delattr(reader, 'DEFAULT_Z_FAR')
if had_depth_masks:
reader._USE_DEPTH_MASKS = orig_depth_masks
elif '_USE_DEPTH_MASKS' in reader.__dict__:
delattr(reader, '_USE_DEPTH_MASKS')
if had_aliasing_masks:
reader._USE_ALIASING_MASKS = orig_aliasing_masks
elif '_USE_ALIASING_MASKS' in reader.__dict__:
delattr(reader, '_USE_ALIASING_MASKS')
if had_conf:
reader.conf_threshold = orig_conf
elif 'conf_threshold' in reader.__dict__:
delattr(reader, 'conf_threshold')
images_np = loaded["images_raw"].permute(0, 2, 3, 1).cpu().numpy()
images = [
np.ascontiguousarray(np.clip(img * 255.0, 0, 255).astype(np.uint8))
for img in images_np
]
depths = [np.ascontiguousarray(d.astype(np.float32)) for d in loaded["depth"]]
extrinsics = [
np.ascontiguousarray(e.astype(np.float32))
for e in loaded["extrinsic"]
]
intrinsics = [
np.ascontiguousarray(k.astype(np.float32))
for k in loaded["intrinsic"]
]
return {
"images": images,
"depths": depths,
"extrinsics": extrinsics,
"intrinsics": intrinsics,
"K": intrinsics[0] if intrinsics else np.eye(3, dtype=np.float32),
}
def _load_droid_style(scene_dir: Path, frame_indices: list, z_far: float, use_depth_mask: bool = True, pose_scale: float = 1.0):
"""Load DROID-style data (shared by droid, tum, bonn, nrgbd, 7scenes, tanks).
pose_scale: multiplier for pose translation. 1.0 (default) for most datasets.
0.001 for DTU where poses are in mm but depth /1000 converts to meters.
"""
rgb_dir = scene_dir / "images" / "left"
depth_dir = scene_dir / "depth_npy"
depth_mask_dir = scene_dir / "depth_mask"
rgb_paths = sorted(rgb_dir.glob("*.png"), key=lambda p: int(p.stem))
depth_paths = sorted(depth_dir.glob("*.png"), key=lambda p: int(p.stem.replace("_depth", "")))
depth_mask_paths = sorted(depth_mask_dir.glob("*.png")) if depth_mask_dir.exists() else []
# Poses
pose_path = scene_dir / "poses_ma" / "poses_depth_ba.npy"
if not pose_path.exists():
pose_path = scene_dir / "poses_ma" / "poses.npy"
all_poses = np.load(str(pose_path)).astype(np.float32)
print(f"using pose from {pose_path}")
# Intrinsics
intr_dir = scene_dir / "intrinsics"
K_path = list(intr_dir.glob("*left.npy")) or list(intr_dir.glob("*.npy"))
K = np.load(str(K_path[0])).astype(np.float32) if K_path else np.eye(3, dtype=np.float32)
images, depths, extrinsics = [], [], []
for idx in frame_indices:
if idx >= len(rgb_paths) or idx >= len(depth_paths):
continue
# RGB
img = cv2.imread(str(rgb_paths[idx]))
if img is not None:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
else:
img = np.zeros((480, 640, 3), dtype=np.uint8)
# Depth
d_raw = cv2.imread(str(depth_paths[idx]), cv2.IMREAD_UNCHANGED)
if d_raw is not None:
depth = d_raw.astype(np.float32) / 1000.0
depth[~np.isfinite(depth)] = 0
# Apply depth mask if available
if use_depth_mask and depth_mask_paths and idx < len(depth_mask_paths):
mask = cv2.imread(str(depth_mask_paths[idx]), cv2.IMREAD_UNCHANGED)
if mask is not None:
depth[mask == 0] = 0
depth[depth > z_far] = 0
else:
depth = np.zeros((480, 640), dtype=np.float32)
images.append(img)
depths.append(depth)
pose = all_poses[min(idx, len(all_poses) - 1)].copy()
if pose_scale != 1.0:
pose[:3, 3] *= pose_scale
extrinsics.append(pose)
return {
"images": images, "depths": depths,
"extrinsics": extrinsics, "K": K,
}
def _load_ropedia(scene_dir: Path, frame_indices: list, z_far: float, use_depth_mask: bool = True, conf_threshold: float = 0.0):
"""Load Ropedia/ViPE format data."""
rgb_dir = scene_dir / "images" / "left"
# Prefer depths_ropedia/ (raw), fall back to depths/ (cleaned)
depth_dir = scene_dir / "depths_ropedia"
if not depth_dir.exists():
depth_dir = scene_dir / "depths"
depth_mask_dir = scene_dir / "depth_mask"
conf_mask_dir = scene_dir / "conf_mask"
has_conf = conf_mask_dir.is_dir()
rgb_paths = sorted(rgb_dir.glob("*.png"))
depth_paths = sorted(depth_dir.glob("*.png"))
depth_mask_paths = sorted(depth_mask_dir.glob("*.png")) if depth_mask_dir.exists() else []
# Try loading poses: prefer pose/ (refined), fall back to pose_from_hdf5/
pose_file = scene_dir / "pose" / "left.npz"
if not pose_file.exists():
pose_file = scene_dir / "pose_from_hdf5" / "left.npz"
pose_data = np.load(str(pose_file))
all_poses = pose_data["data"].astype(np.float32)
pose_inds = pose_data.get("inds", None)
if all_poses.ndim == 3 and all_poses.shape[1] == 4 and all_poses.shape[2] == 4:
all_poses = all_poses[:, :3, :]
# Intrinsics: read from annotation.hdf5 if available, else hardcode
ann_path = scene_dir / "annotation.hdf5"
if ann_path.exists():
with h5py.File(str(ann_path), "r") as f:
k_vals = f["calibration/cam01/K"][:].tolist() # [fx, fy, cx, cy]
K = np.array([[k_vals[0], 0, k_vals[2]],
[0, k_vals[1], k_vals[3]],
[0, 0, 1]], dtype=np.float32)
else:
K = np.array([[200, 0, 256], [0, 200, 256], [0, 0, 1]], dtype=np.float32)
images, depths, extrinsics = [], [], []
for idx in frame_indices:
if idx >= len(all_poses):
continue
# Determine file names based on pose_inds if available
if pose_inds is not None and idx < len(pose_inds):
rgb_fname = f"frame_{int(pose_inds[idx]):05d}_rgb.png"
depth_fname = f"{int(pose_inds[idx]):06d}.png"
else:
rgb_fname = None
depth_fname = None
# RGB
if rgb_fname and (rgb_dir / rgb_fname).exists():
img = cv2.cvtColor(cv2.imread(str(rgb_dir / rgb_fname)), cv2.COLOR_BGR2RGB)
elif idx < len(rgb_paths):
img = cv2.cvtColor(cv2.imread(str(rgb_paths[idx])), cv2.COLOR_BGR2RGB)
else:
continue
# Depth
if depth_fname and (depth_dir / depth_fname).exists():
d_raw = cv2.imread(str(depth_dir / depth_fname), cv2.IMREAD_ANYDEPTH)
elif idx < len(depth_paths):
d_raw = cv2.imread(str(depth_paths[idx]), cv2.IMREAD_ANYDEPTH)
else:
continue
depth = d_raw.astype(np.float32) / 1000.0
depth[~np.isfinite(depth)] = 0
# Apply depth mask if available
if use_depth_mask and depth_mask_paths:
dm_path = depth_mask_dir / rgb_fname if rgb_fname else None
if dm_path and dm_path.exists():
mask = cv2.imread(str(dm_path), cv2.IMREAD_UNCHANGED)
depth[mask == 0] = 0
elif idx < len(depth_mask_paths):
mask = cv2.imread(str(depth_mask_paths[idx]), cv2.IMREAD_UNCHANGED)
depth[mask == 0] = 0
depth[depth > z_far] = 0
# Confidence mask filtering
if has_conf and conf_threshold > 0:
conf_fname = rgb_fname if rgb_fname else None
conf_path = conf_mask_dir / conf_fname if conf_fname else None
if conf_path and conf_path.exists():
conf_raw = cv2.imread(str(conf_path), cv2.IMREAD_GRAYSCALE)
if conf_raw is not None:
conf = conf_raw.astype(np.float32) / 255.0
depth[conf < conf_threshold] = 0
# Center crop RGB to depth size if needed
H_d, W_d = depth.shape
H_r, W_r = img.shape[:2]
if H_r != H_d or W_r != W_d:
if H_r >= H_d and W_r >= W_d:
t = (H_r - H_d) // 2
l = (W_r - W_d) // 2
img = img[t:t + H_d, l:l + W_d]
images.append(img)
depths.append(depth)
extrinsics.append(all_poses[min(idx, len(all_poses) - 1)])
return {
"images": images, "depths": depths,
"extrinsics": extrinsics, "K": K,
}
def _load_adt(scene_dir: Path, frame_indices: list, z_far: float, use_depth_mask: bool = True):
"""Load ADT (Aria Digital Twin) format data.
Layout:
rgb_rectified/*.png — timestamp-named RGB images
depth_rectified/*.png — uint16 PNG depth (mm), timestamp-named
depth_mask/*.png — optional binary mask from depth cleaning
intrinsic.npy — 3x3 camera intrinsic matrix
camera_to_world/*.npy — per-frame 3x4 cam-to-world poses
"""
rgb_dir = scene_dir / "rgb_rectified"
depth_dir = scene_dir / "depth_rectified"
depth_mask_dir = scene_dir / "depth_mask"
pose_dir = scene_dir / "camera_to_world"
rgb_paths = sorted(rgb_dir.glob("*.png"))
depth_paths = sorted(depth_dir.glob("*.png"))
pose_paths = sorted(pose_dir.glob("*.npy"))
depth_mask_paths = sorted(depth_mask_dir.glob("*.png")) if depth_mask_dir.exists() else []
# Intrinsics
K_path = scene_dir / "intrinsic.npy"
K = np.load(str(K_path)).astype(np.float32) if K_path.exists() else np.eye(3, dtype=np.float32)
images, depths, extrinsics = [], [], []
for idx in frame_indices:
if idx >= len(rgb_paths) or idx >= len(depth_paths) or idx >= len(pose_paths):
continue
# RGB
img = cv2.imread(str(rgb_paths[idx]))
if img is not None:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
else:
img = np.zeros((512, 512, 3), dtype=np.uint8)
# Depth (uint16 mm -> metres)
d_raw = cv2.imread(str(depth_paths[idx]), cv2.IMREAD_UNCHANGED)
if d_raw is not None:
depth = d_raw.astype(np.float32) / 1000.0
depth[~np.isfinite(depth)] = 0
# Apply depth mask if available
if use_depth_mask and depth_mask_paths and idx < len(depth_mask_paths):
mask = cv2.imread(str(depth_mask_paths[idx]), cv2.IMREAD_UNCHANGED)
if mask is not None:
depth[mask == 0] = 0
depth[depth > z_far] = 0
else:
depth = np.zeros((512, 512), dtype=np.float32)
# Pose (3x4 cam-to-world)
pose = np.load(str(pose_paths[idx])).astype(np.float32)
if pose.shape == (4, 4):
pose = pose[:3, :]
images.append(img)
depths.append(depth)
extrinsics.append(pose)
return {
"images": images, "depths": depths,
"extrinsics": extrinsics, "K": K,
}
def _load_robotwin(scene_dir: Path, frame_indices: list, z_far: float, use_depth_mask: bool = True):
"""Load RoboTwin format data.
Layout:
camera_data/images/*.png — RGB images
camera_data/depths/*.png — uint16 PNG depth (mm)
camera_data/extrinsics/*.npy — per-frame 3x4 cam-to-world poses
camera_data/intrinsics/*.npy — per-frame 3x3 intrinsics
"""
rgb_dir = scene_dir / "camera_data" / "images"
depth_dir = scene_dir / "camera_data" / "depths"
depth_mask_dir = scene_dir / "depth_mask"
extrinsic_dir = scene_dir / "camera_data" / "extrinsics"
intrinsic_dir = scene_dir / "camera_data" / "intrinsics"
rgb_paths = sorted(rgb_dir.glob("*.png"))
depth_paths = sorted(depth_dir.glob("*.png"))
depth_mask_paths = sorted(depth_mask_dir.glob("*.png")) if depth_mask_dir.exists() else []
extrinsic_paths = sorted(extrinsic_dir.glob("*.npy"))
intrinsic_paths = sorted(intrinsic_dir.glob("*.npy"))
# Use first frame's intrinsic as shared K (they are typically identical)
K = np.load(str(intrinsic_paths[0])).astype(np.float32) if intrinsic_paths else np.eye(3, dtype=np.float32)
images, depths, extrinsics = [], [], []
for idx in frame_indices:
if idx >= len(rgb_paths) or idx >= len(depth_paths) or idx >= len(extrinsic_paths):
continue
# RGB
img = cv2.imread(str(rgb_paths[idx]))
if img is not None:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
else:
img = np.zeros((720, 1280, 3), dtype=np.uint8)
# Depth (uint16 mm -> metres)
d_raw = cv2.imread(str(depth_paths[idx]), cv2.IMREAD_ANYDEPTH)
if d_raw is not None:
depth = d_raw.astype(np.float32) / 1000.0
depth[~np.isfinite(depth)] = 0
# Apply depth mask if available
if use_depth_mask and depth_mask_paths and idx < len(depth_mask_paths):
mask = cv2.imread(str(depth_mask_paths[idx]), cv2.IMREAD_UNCHANGED)
if mask is not None:
depth[mask == 0] = 0
depth[depth > z_far] = 0
else:
depth = np.zeros((720, 1280), dtype=np.float32)
# Pose (3x4 cam-to-world)
pose = np.load(str(extrinsic_paths[idx])).astype(np.float32)
if pose.shape == (4, 4):
pose = pose[:3, :]
images.append(img)
depths.append(depth)
extrinsics.append(pose)
return {
"images": images, "depths": depths,
"extrinsics": extrinsics, "K": K,
}
def _load_robolab(scene_dir: Path, frame_indices: list, z_far: float):
"""Load RoboLab (Isaac Sim) format data.
Layout:
rgb/{XXXXXX}.png — RGB images (1280x720)
depth.npy — float32 (T, H, W), z-depth in meters (invalid=0)
c2w.npy — float32 (T, 4, 4), cam2world (OpenCV convention)
K.npy — float32 (3, 3), shared intrinsics
"""
rgb_dir = scene_dir / "rgb"
rgb_paths = sorted(rgb_dir.glob("*.png"))
K = np.load(str(scene_dir / "K.npy")).astype(np.float32)
all_depth = np.load(str(scene_dir / "depth.npy")) # (T, H, W) float32
all_c2w = np.load(str(scene_dir / "c2w.npy")).astype(np.float32) # (T, 4, 4)
images, depths, extrinsics = [], [], []
for idx in frame_indices:
if idx >= len(rgb_paths) or idx >= len(all_depth) or idx >= len(all_c2w):
continue
# RGB
img = cv2.imread(str(rgb_paths[idx]))
if img is not None:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
else:
img = np.zeros((720, 1280, 3), dtype=np.uint8)
# Depth: 已为米, 直接使用
depth = np.ascontiguousarray(all_depth[idx].astype(np.float32))
depth[~np.isfinite(depth)] = 0
depth[depth > z_far] = 0
# Pose: 4x4 cam2world -> (3, 4)
pose = all_c2w[idx][:3, :].astype(np.float32)
images.append(img)
depths.append(depth)
extrinsics.append(pose)
return {
"images": images, "depths": depths,
"extrinsics": extrinsics, "K": K,
}
def _load_rlbench(scene_dir: Path, frame_indices: list, z_far: float, use_depth_mask: bool = True):
"""Load RLBench format data.
Layout:
images/frame_XXXX.png — RGB images
depth/frame_XXXX.png — uint16 PNG depth (mm)
pose/frame_XXXX.npy — per-frame 4x4 cam-to-world poses
intrinsic/frame_XXXX.npy — per-frame 3x3 intrinsics (PyRep convention)
"""
rgb_dir = scene_dir / "images"
depth_dir = scene_dir / "depth"
depth_mask_dir = scene_dir / "depth_mask"
pose_dir = scene_dir / "pose"
intrinsic_dir = scene_dir / "intrinsic"
rgb_paths = sorted(rgb_dir.glob("*.png"))
depth_paths = sorted(depth_dir.glob("*.png"))
depth_mask_paths = sorted(depth_mask_dir.glob("*.png")) if depth_mask_dir.exists() else []
pose_paths = sorted(pose_dir.glob("*.npy"))
intrinsic_paths = sorted(intrinsic_dir.glob("*.npy"))
# Use first frame's intrinsic as shared K for visualization (after abs correction)
K = np.load(str(intrinsic_paths[0])).astype(np.float32) if intrinsic_paths else np.eye(3, dtype=np.float32)
K[0, 0] = abs(K[0, 0])
K[1, 1] = abs(K[1, 1])
images, depths, extrinsics = [], [], []
for idx in frame_indices:
if idx >= len(rgb_paths) or idx >= len(depth_paths) or idx >= len(pose_paths):
continue
# RGB
img = cv2.imread(str(rgb_paths[idx]))
if img is not None:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
else:
img = np.zeros((720, 1280, 3), dtype=np.uint8)
# Depth (uint16 mm -> metres)
d_raw = cv2.imread(str(depth_paths[idx]), cv2.IMREAD_ANYDEPTH)
if d_raw is not None:
depth = d_raw.astype(np.float32) / 1000.0
depth[~np.isfinite(depth)] = 0
# Apply depth mask if available
if use_depth_mask and depth_mask_paths and idx < len(depth_mask_paths):
mask = cv2.imread(str(depth_mask_paths[idx]), cv2.IMREAD_UNCHANGED)
if mask is not None:
depth[mask == 0] = 0
depth[depth > z_far] = 0
else:
depth = np.zeros((720, 1280), dtype=np.float32)
# Per-frame intrinsic: handle PyRep negative fx/fy by flipping image
K_frame = np.load(str(intrinsic_paths[idx])).astype(np.float32) if idx < len(intrinsic_paths) else K.copy()
if K_frame[0, 0] < 0:
img = img[:, ::-1, :].copy()
depth = depth[:, ::-1].copy()
K_frame[0, 2] = (img.shape[1] - 1) - K_frame[0, 2]
K_frame[0, 0] = abs(K_frame[0, 0])
if K_frame[1, 1] < 0:
img = img[::-1, :, :].copy()
depth = depth[::-1, :].copy()
K_frame[1, 2] = (img.shape[0] - 1) - K_frame[1, 2]
K_frame[1, 1] = abs(K_frame[1, 1])
# Pose (4x4 cam-to-world -> 3x4)
pose = np.load(str(pose_paths[idx])).astype(np.float32)
if pose.shape == (4, 4):
pose = pose[:3, :]
images.append(img)
depths.append(depth)
extrinsics.append(pose)
return {
"images": images, "depths": depths,
"extrinsics": extrinsics, "K": K,
}
def _load_tanks_raw(scene_dir: Path, frame_indices: list, z_far: float, use_depth_mask: bool = True):
"""Load Tanks & Temples raw format data.
Layout:
images/*.jpg — RGB images
depth/*.npz — float32 depth maps (key='arr_0')
{scene_name}_COLMAP_SfM.log — extrinsics (4x4 per frame)
"""
rgb_dir = scene_dir / "images"
depth_dir = scene_dir / "depth"
depth_mask_dir = scene_dir / "depth_mask"
rgb_paths = sorted(rgb_dir.glob("*.jpg"))
depth_paths = sorted(depth_dir.glob("*.npz"))
depth_mask_paths = sorted(depth_mask_dir.glob("*.png")) if depth_mask_dir.exists() else []
# Read extrinsics from COLMAP log
log_files = list(scene_dir.glob("*_COLMAP_SfM.log"))
if not log_files:
raise FileNotFoundError(f"No *_COLMAP_SfM.log in {scene_dir}")
all_extrinsics = []
with open(str(log_files[0]), 'r') as f:
lines = f.readlines()
i = 0
while i < len(lines):
line = lines[i].strip()
if not line:
i += 1
continue
if len(line.split()) == 3:
i += 1
mat_lines = lines[i:i + 4]
mat = np.array([[float(x) for x in l.split()] for l in mat_lines], dtype=np.float32)
all_extrinsics.append(mat)
i += 4
else:
i += 1
# Estimate intrinsics from first image size
SCENE_IMAGE_SIZES = {
'Barn': (1920, 1080),
'Church': (1961, 1091),
'Courthouse': (1962, 1091),
'Ignatius': (1961, 1091),
}
scene_name = scene_dir.name
if scene_name in SCENE_IMAGE_SIZES:
W, H = SCENE_IMAGE_SIZES[scene_name]
elif rgb_paths:
img_tmp = cv2.imread(str(rgb_paths[0]))
H, W = img_tmp.shape[:2]
else:
W, H = 1920, 1080
fx = fy = 0.7 * W
K = np.array([[fx, 0, W / 2], [0, fy, H / 2], [0, 0, 1]], dtype=np.float32)
images, depths, extrinsics = [], [], []
for idx in frame_indices:
if idx >= len(rgb_paths) or idx >= len(depth_paths) or idx >= len(all_extrinsics):
continue
# RGB
img = cv2.imread(str(rgb_paths[idx]))
if img is not None:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
else:
img = np.zeros((H, W, 3), dtype=np.uint8)
# Depth: npz float32
depth = np.load(str(depth_paths[idx]))['arr_0'].astype(np.float32)
depth[~np.isfinite(depth)] = 0
# Apply depth mask if available
if use_depth_mask and depth_mask_paths and idx < len(depth_mask_paths):
mask = cv2.imread(str(depth_mask_paths[idx]), cv2.IMREAD_UNCHANGED)
if mask is not None:
depth[mask == 0] = 0
depth[depth > z_far] = 0
# Extrinsic: (4, 4) -> (3, 4)
pose = all_extrinsics[idx]
if pose.shape == (4, 4):
pose = pose[:3, :]
images.append(img)
depths.append(depth)
extrinsics.append(pose)
return {
"images": images, "depths": depths,
"extrinsics": extrinsics, "K": K,
}
def _load_omniworld(scene_dir: Path, scene_path: str, frame_indices: list, z_far: float, use_depth_mask: bool = True):
"""Load OmniWorld-Game data (metric depth, metric poses).
scene_dir 实际上是 data_root/scene_id,scene_path = "scene_id/split_N"。
深度和位姿均乘以 metric_scale 转为米制。
"""
import csv as _csv
import json as _json
from scipy.spatial.transform import Rotation as _R
parts = scene_path.split('/')
scene_id = parts[0]
split_idx = int(parts[1].replace('split_', ''))
# 加载 metric_scale
csv_path = scene_dir.parent / "omniworld_game_metadata.csv"
metric_scale = 1.0
if csv_path.exists():
with open(str(csv_path), 'r', encoding='utf-8', newline='') as f:
reader = _csv.DictReader(f)
for row in reader:
if row["UID"] == scene_id:
metric_scale = float(row["Metric Scale"])
break
# scene_dir 已经是 data_root / scene_id
with open(str(scene_dir / "split_info.json"), 'r') as f:
split_info = _json.load(f)
global_indices = split_info["split"][split_idx]
# 加载相机参数
cam_file = scene_dir / "camera" / f"split_{split_idx}.json"
with open(str(cam_file), 'r') as f:
cam = _json.load(f)
# 内参 (取均值 focal)
focal_mean = float(np.mean(cam["focals"]))
K = np.array([
[focal_mean, 0, cam["cx"]],
[0, focal_mean, cam["cy"]],
[0, 0, 1],
], dtype=np.float32)
# 外参 w2c -> c2w, c2w 平移 × metric_scale
quat_wxyz = np.array(cam["quats"], dtype=np.float64)
trans = np.array(cam["trans"], dtype=np.float64)
norms = np.linalg.norm(quat_wxyz, axis=1, keepdims=True)
norms = np.maximum(norms, 1e-8)
quat_wxyz = quat_wxyz / norms
quat_xyzw = np.concatenate([quat_wxyz[:, 1:], quat_wxyz[:, :1]], axis=1)
rotations = _R.from_quat(quat_xyzw).as_matrix()
S = len(cam["quats"])
w2c = np.repeat(np.eye(4, dtype=np.float64)[None], S, axis=0)
w2c[:, :3, :3] = rotations
w2c[:, :3, 3] = trans
c2w = np.linalg.inv(w2c)
c2w[:, :3, 3] *= metric_scale
depth_mask_dir = scene_dir / "depth_mask"
sky_mask_dir = scene_dir / "sky_mask"
images, depths, extrinsics = [], [], []
for idx in frame_indices:
if idx >= len(global_indices):
continue
gi = global_indices[idx]
# RGB
img = cv2.imread(str(scene_dir / "color" / f"{gi:06d}.png"))
if img is not None:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
else:
img = np.zeros((720, 1280, 3), dtype=np.uint8)
# Depth (反深度解码 × metric_scale = 米)
d_raw = cv2.imread(str(scene_dir / "depth" / f"{gi:06d}.png"), cv2.IMREAD_UNCHANGED)
if d_raw is not None:
depthmap = d_raw.astype(np.float32) / 65535.0
near_mask = depthmap < 0.0015
depth_sky_mask = depthmap > (65500.0 / 65535.0)
near, far = 1.0, 1000.0
depthmap = depthmap / (far - depthmap * (far - near)) / 0.004
valid = ~(near_mask | depth_sky_mask)
depthmap[~valid] = 0
depthmap[valid] *= metric_scale
# 应用 depth_mask (飞点过滤)
if use_depth_mask and depth_mask_dir.exists():
mask_path = depth_mask_dir / f"{gi:06d}.png"
if mask_path.exists():
mask = cv2.imread(str(mask_path), cv2.IMREAD_UNCHANGED)
if mask is not None:
depthmap[mask == 0] = 0
# 应用 sky_mask (天空区域置零)
if use_depth_mask and sky_mask_dir.exists():
sky_path = sky_mask_dir / f"{gi:06d}.png"
if sky_path.exists():
sky_m = cv2.imread(str(sky_path), cv2.IMREAD_UNCHANGED)
if sky_m is not None:
depthmap[sky_m > 0] = 0
depthmap[depthmap > z_far] = 0
else:
depthmap = np.zeros((720, 1280), dtype=np.float32)
pose = c2w[idx, :3, :].astype(np.float32)
images.append(img)
depths.append(depthmap)
extrinsics.append(pose)
return {
"images": images, "depths": depths,
"extrinsics": extrinsics, "K": K,
}
def _load_spatialvid(scene_dir: Path, frame_indices: list, z_far: float, use_depth_mask: bool = True):
"""Load SpatialVID scene data.
Layout:
images/000001.jpg ... — RGB images (1-indexed)
depth/{ann_idx:06d}.png — inverse depth (uint16)
indexes.txt — annotation_idx -> video_frame_idx
poses.npy — (N, 7) [tx, ty, tz, qx, qy, qz, qw] w2c
intrinsics.npy — (N, 4) [fx, fy, cx, cy] normalized
depth_mask/{ann_idx:06d}.png — flying point mask (optional)
sky_mask/{ann_idx:06d}.png — sky mask (optional)
"""
from scipy.spatial.transform import Rotation as R
# Parse indexes.txt
ann_to_video = {}
idx_path = scene_dir / "indexes.txt"
if idx_path.exists():
for line in idx_path.read_text().strip().split('\n'):
line = line.strip()
if not line or line.startswith('#'):
continue
parts = line.split()
if len(parts) >= 2:
ann_to_video[int(parts[0])] = int(parts[1])
# Load poses (N, 7): w2c -> c2w
all_poses = np.load(str(scene_dir / "poses.npy")).astype(np.float64)
N = len(all_poses)
quat_xyzw = all_poses[:, 3:7]
rotations = R.from_quat(quat_xyzw).as_matrix()
translations = all_poses[:, :3]
w2c = np.repeat(np.eye(4, dtype=np.float64)[None], N, axis=0)
w2c[:, :3, :3] = rotations
w2c[:, :3, 3] = translations
c2w = np.linalg.inv(w2c)
all_c2w = c2w[:, :3, :].astype(np.float32)
# Load intrinsics (N, 4): normalized -> pixel
all_intrin = np.load(str(scene_dir / "intrinsics.npy")).astype(np.float32)
# Get image size from first image
img_dir = scene_dir / "images"
sample_imgs = sorted(img_dir.glob("*.jpg"))
if not sample_imgs:
sample_imgs = sorted(img_dir.glob("*.png"))
first_img = cv2.imread(str(sample_imgs[0]))
img_H, img_W = first_img.shape[:2]
# Build shared K from first frame
fx_n, fy_n, cx_n, cy_n = all_intrin[0]
K = np.array([
[fx_n * img_W, 0, cx_n * img_W],
[0, fy_n * img_H, cy_n * img_H],
[0, 0, 1],
], dtype=np.float32)
depth_dir = scene_dir / "depth"
has_depth = depth_dir.is_dir()
depth_mask_dir = scene_dir / "depth_mask"
sky_mask_dir = scene_dir / "sky_mask"
images, depths, extrinsics = [], [], []
for idx in frame_indices:
video_frame_idx = ann_to_video.get(idx, idx)
# RGB (1-indexed filenames)
rgb_path = img_dir / f"{video_frame_idx + 1:06d}.jpg"
if not rgb_path.exists():
rgb_path = img_dir / f"{video_frame_idx + 1:06d}.png"
img = cv2.imread(str(rgb_path))
if img is not None:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
else:
img = np.zeros((img_H, img_W, 3), dtype=np.uint8)
# Depth (inverse depth)
if has_depth:
dp = depth_dir / f"{idx:06d}.png"
if dp.exists():
d_raw = cv2.imread(str(dp), cv2.IMREAD_UNCHANGED)
disp = d_raw.astype(np.float32) / 65535.0
valid = disp > 1e-6
depth = np.zeros_like(disp)
depth[valid] = 1.0 / disp[valid]
depth[~np.isfinite(depth)] = 0
else:
depth = np.zeros((img_H, img_W), dtype=np.float32)
else:
depth = np.zeros((img_H, img_W), dtype=np.float32)
# Apply masks
if use_depth_mask:
mask_path = depth_mask_dir / f"{idx:06d}.png"
if mask_path.exists():
mask = cv2.imread(str(mask_path), cv2.IMREAD_UNCHANGED)
if mask is not None:
depth[mask == 0] = 0
sky_path = sky_mask_dir / f"{idx:06d}.png"
if sky_path.exists():
sky_mask = cv2.imread(str(sky_path), cv2.IMREAD_UNCHANGED)
if sky_mask is not None:
depth[sky_mask > 0] = 0
depth[depth > z_far] = 0
images.append(img)
depths.append(depth)
extrinsics.append(all_c2w[idx])
return {
"images": images, "depths": depths,
"extrinsics": extrinsics, "K": K,
}
def _load_vkitti(scene_dir: Path, frame_indices: list, z_far: float, use_depth_mask: bool = True):
"""Load Virtual KITTI 2 scene data.
Layout (scene_dir = {data_root}/{scene}/{sub_scene}/Camera_0):
{XXXXX}_rgb.jpg — RGB 1242×375
{XXXXX}_depth.png — uint16, /100 -> meters, sky=65535
{XXXXX}_cam.npz — camera_pose (4×4 w2c), camera_intrinsics (3×3)
depth_mask/*.png — binary mask (optional)
"""
rgb_paths = sorted(scene_dir.glob("*_rgb.jpg"))
depth_paths = sorted(scene_dir.glob("*_depth.png"))
cam_paths = sorted(scene_dir.glob("*_cam.npz"))
depth_mask_dir = scene_dir / "depth_mask"
depth_mask_paths = sorted(depth_mask_dir.glob("*.png")) if depth_mask_dir.is_dir() else []
# 从第一帧加载内参 (共享)
cam0 = np.load(str(cam_paths[0]))
K = cam0['camera_intrinsics'].astype(np.float32)
images, depths, extrinsics = [], [], []
for idx in frame_indices:
if idx >= len(rgb_paths) or idx >= len(depth_paths) or idx >= len(cam_paths):
continue
# RGB
img = cv2.imread(str(rgb_paths[idx]))