SCAI-JHU commited on
Commit
62a5484
·
verified ·
1 Parent(s): e147e73

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. 3d-belief/ARKITSCENES.md +263 -0
  2. 3d-belief/outputs/training/arkitscenes_overfit_scene0/logs.json.txt +0 -0
  3. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_depth.mp4 +3 -0
  4. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_0.png +3 -0
  5. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_1.png +3 -0
  6. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_10.png +3 -0
  7. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_11.png +3 -0
  8. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_12.png +3 -0
  9. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_13.png +3 -0
  10. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_14.png +3 -0
  11. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_15.png +3 -0
  12. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_16.png +3 -0
  13. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_17.png +3 -0
  14. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_18.png +3 -0
  15. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_19.png +3 -0
  16. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_2.png +3 -0
  17. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_3.png +3 -0
  18. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_4.png +3 -0
  19. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_5.png +3 -0
  20. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_6.png +3 -0
  21. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_7.png +3 -0
  22. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_8.png +3 -0
  23. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_9.png +3 -0
  24. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_rgb.mp4 +3 -0
  25. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_depth.mp4 +3 -0
  26. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_0.png +3 -0
  27. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_1.png +3 -0
  28. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_10.png +3 -0
  29. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_11.png +3 -0
  30. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_12.png +3 -0
  31. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_13.png +3 -0
  32. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_14.png +3 -0
  33. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_15.png +3 -0
  34. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_16.png +3 -0
  35. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_rgb.mp4 +3 -0
  36. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_3_rendered_depth.mp4 +3 -0
  37. 3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_3_rendered_rgb.mp4 +3 -0
  38. 3d-belief/outputs/training/arkitscenes_smoke/logs.json.txt +0 -0
  39. 3d-belief/scripts/data_prep/verify_arkitscenes_pose_convention.py +205 -0
  40. 3d-belief/scripts/training/finetune_arkitscenes_overfit.sh +136 -0
  41. 3d-belief/splat_belief/config/dataset/arkitscenes_cut3r.yaml +57 -0
  42. 3d-belief/third_party/CUT3R/datasets_preprocess/generate_set_arkitscenes.py +159 -0
  43. 3d-belief/third_party/CUT3R/datasets_preprocess/preprocess_arkitscenes.py +445 -0
  44. 3d-belief/third_party/CUT3R/datasets_preprocess/preprocess_arkitscenes_highres.py +409 -0
  45. 3d-belief/third_party/CUT3R/src/dust3r/datasets/__pycache__/arkitscenes.cpython-310.pyc +0 -0
  46. 3d-belief/third_party/CUT3R/src/dust3r/datasets/__pycache__/arkitscenes.cpython-311.pyc +0 -0
  47. 3d-belief/third_party/CUT3R/src/dust3r/datasets/__pycache__/arkitscenes_highres.cpython-310.pyc +0 -0
  48. 3d-belief/third_party/CUT3R/src/dust3r/datasets/__pycache__/arkitscenes_highres.cpython-311.pyc +0 -0
  49. 3d-belief/third_party/CUT3R/src/dust3r/datasets/arkitscenes.py +242 -0
  50. 3d-belief/third_party/CUT3R/src/dust3r/datasets/arkitscenes_highres.py +175 -0
3d-belief/ARKITSCENES.md ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ARKitScenes → 3D-Belief finetuning
2
+
3
+ End-to-end procedure for wiring **ARKitScenes** (Apple iPad LiDAR room captures)
4
+ into 3D-Belief training via the CUT3R adapter, plus the single-scene overfit used
5
+ to validate the dataloader before multi-scene training.
6
+
7
+ This mirrors the WildRGBD / ScanNet++ ports — see [`WILDRGBD.md`](WILDRGBD.md) and
8
+ the `3d-belief-dataloader` skill for the shared invariants. Only the
9
+ ARKitScenes-specific decisions are spelled out here.
10
+
11
+ TL;DR of what was added:
12
+
13
+ | file | change |
14
+ |---|---|
15
+ | `splat_belief/data_io/cut3r_adapter.py` | `_make_arkitscenes_short()` helper + `arkitscenes` branch now uses it |
16
+ | `splat_belief/data_io/__init__.py` | registered `arkitscenes_cut3r` in `get_path` + the adapter tuple |
17
+ | `splat_belief/config/dataset/arkitscenes_cut3r.yaml` | new Hydra dataset config (room-scale near/far, metric depth) |
18
+ | `scripts/data_prep/verify_arkitscenes_pose_convention.py` | convention + schema + drift verifier |
19
+ | `scripts/training/finetune_arkitscenes_overfit.sh` | single-scene overfit launcher (DFoT init, depth mask on) |
20
+
21
+ ---
22
+
23
+ ## 1. Preprocessing (CUT3R)
24
+
25
+ ARKitScenes uses the **two-step** CUT3R pipeline (`docs/preprocess.md`), identical
26
+ in shape to ScanNet: `preprocess_*` writes per-frame RGB/depth + `scene_metadata.npz`
27
+ (with DUSt3R `pairs`); `generate_set_*` then writes `new_scene_metadata.npz` (with
28
+ the `image_collection` / `video_collection` that the `ARKitScenes_Multi` loader
29
+ actually reads at train time).
30
+
31
+ ### 1a. Inputs
32
+
33
+ - **Raw data**: `data/ARKitScenes/raw/{Training,Validation}/<scene>/` with
34
+ `vga_wide/` (RGB), `lowres_depth/` (uint16 mm LiDAR depth), `vga_wide_intrinsics/`
35
+ (`*.pincam`), and `lowres_wide.traj` (per-frame device pose, angle-axis + t).
36
+ - **Precomputed pairs** (required by `preprocess_arkitscenes.py`): DUSt3R's
37
+ [`arkitscenes_pairs.zip`](https://download.europe.naverlabs.com/ComputerVision/DUSt3R/arkitscenes_pairs.zip),
38
+ unzipped to `data/ARKitScenes/arkitscenes_pairs/{Training,Test}/`. The script
39
+ reads `scene_list.json` + per-scene `selected_pairs.npz`; **without it the
40
+ preprocessor cannot run** (it drives which frames are selected/exported).
41
+
42
+ ### 1b. Commands (run from `third_party/CUT3R/datasets_preprocess`)
43
+
44
+ Use the `3d-belief-release` conda env's python for preprocessing — it has
45
+ `numpy<2` + `numpy-quaternion` (the `3d-belief` training env has numpy 2.x where
46
+ `quaternion` is ABI-broken; that's fine because the **dataloader** path never
47
+ imports quaternion). Use the **absolute** interpreter path; `conda run -n <env>`
48
+ is broken on this host (it silently resolves to the colmap-cuda env's py3.14).
49
+
50
+ ```bash
51
+ PY=/home/ubuntu/tianmin-neurips/miniconda3/envs/3d-belief-release/bin/python
52
+ DATA=/home/ubuntu/tianmin-neurips/zwen19/data/ARKitScenes
53
+
54
+ # Step 1 — convert RGB/depth + interpolate poses to selected timestamps.
55
+ $PY preprocess_arkitscenes.py \
56
+ --arkitscenes_dir "$DATA/raw" \
57
+ --precomputed_pairs "$DATA/arkitscenes_pairs" \
58
+ --output_dir "$DATA/processed_arkitscenes"
59
+
60
+ # Step 2 — build image_collection / video_collection metadata.
61
+ $PY generate_set_arkitscenes.py \
62
+ --root "$DATA/processed_arkitscenes" \
63
+ --splits Training Test --max_interval 5.0 --num_workers 8
64
+ ```
65
+
66
+ Output layout (per scene): `processed_arkitscenes/Training/<scene>/{vga_wide/*.jpg,
67
+ lowres_depth/*.png, scene_metadata.npz, new_scene_metadata.npz}` plus a top-level
68
+ `all_metadata.npz` + `scene_list.json` per split.
69
+
70
+ ### 1c. Subset preprocessing (this run)
71
+
72
+ The full ARKitScenes is still downloading, so only a **5-scene subset** was
73
+ processed for the overfit smoke. The official `preprocess_arkitscenes.py`
74
+ hardcodes `subdirs=["Test","Training"]` and crashes on an empty split
75
+ (`np.concatenate([])`), and iterates the *entire* pairs `scene_list.json`. To
76
+ process just a subset without touching the original script:
77
+
78
+ 1. Build `arkitscenes_pairs_subset/` with a filtered `Training/scene_list.json`
79
+ (chosen scenes), symlinked `Training/<scene>/selected_pairs.npz`, and an empty
80
+ `Test/scene_list.json` (`[]`).
81
+ 2. Run a `/tmp` copy of `preprocess_arkitscenes.py` patched to `subdirs=["Training"]`
82
+ (avoids the empty-Test crash; the original CUT3R script is left intact).
83
+ 3. Run `generate_set_arkitscenes.py --splits Training` on the output.
84
+
85
+ Valid processed scenes: **`40958756`** (162 selected frames — overfit target),
86
+ `41045408`, `41098145`. (Re-run on the full pairs `scene_list` once the download
87
+ completes; no code changes needed.)
88
+
89
+ ---
90
+
91
+ ## 2. Dataloader wiring
92
+
93
+ ### 2a. `_make_arkitscenes_short()` — the ARKitScenes-specific subclass
94
+
95
+ The raw CUT3R `ARKitScenes_Multi` is **not** directly usable for 3D-Belief; the
96
+ helper returns a subclass fixing three things (full rationale in the docstring):
97
+
98
+ 1. **`<ROOT>_highres` crash.** `_load_data` does
99
+ `np.setdiff1d(scenes, os.listdir(ROOT + "_highres"/split))` to drop scenes that
100
+ also exist in the high-res variant. We only process the regular split, so the
101
+ subclass stubs empty `<ROOT>_highres/{Training,Validation}` dirs before
102
+ `_load_data` runs → the setdiff is a no-op.
103
+ 2. **50/50 shuffled sampling.** `_get_views` flips `rng.choice([True,False])`
104
+ between a temporal-video sequence and a *permuted* DUSt3R-pairs group. The pairs
105
+ branch is wide-baseline + non-temporal, which breaks the `[ctxt, intm…, trgt]`
106
+ time ordering 3D-Belief's intermediate loss requires. A tiny `_ForceVideoRng`
107
+ proxy makes the branch selector always return the video branch, forwarding every
108
+ other rng call unchanged.
109
+ 3. **Pose drift too wide.** Default `max_interval=8` + `video_prob=0.8` give
110
+ multi-frame gaps. The subclass forces `video_prob=1.0` (always time-ordered) and
111
+ tightens `max_interval=2`, matching `_make_scannet_short`.
112
+
113
+ ### 2b. Hydra config (`arkitscenes_cut3r.yaml`)
114
+
115
+ Room-scale handheld capture, so it differs from object-centric WildRGBD:
116
+
117
+ | key | value | why |
118
+ |---|---|---|
119
+ | `cut3r_dataset_class` | `arkitscenes` | routes to `_make_arkitscenes_short` |
120
+ | `viz_type` | `interpolation` | ctxt/trgt are close after short-window sampling → linear interp stays in seen views (WildRGBD needed `spherical` because object-centric) |
121
+ | `near` / `far` | **0.1 / 10.0** | room-scale indoor; covers full room while keeping splat precision tighter than the 20 m RE10K/ScanNet default |
122
+ | `depth_loss_weight` | 1.0 | per-frame **metric** LiDAR depth on every pixel |
123
+ | `depth_smooth_loss_weight` | 0.1 | canonical (regularizes predicted depth) |
124
+ | `intermediate_weight` | 5.0 | canonical (train.sh / train_re10k.sh) |
125
+ | `vggt_alignment_loss_weight` | 2.0 | canonical |
126
+ | `camera.fx`/`fy` | 1.16 | **measured** fx_norm after the square center-crop (HFOV ≈ 47°); cx/cy ≈ 0.5 confirms centered crop. Nominal fallback only — per-sample K from the dataset dict takes precedence. |
127
+
128
+ ---
129
+
130
+ ## 3. Camera convention — VERIFIED OpenCV c2w (no flip)
131
+
132
+ This was the make-or-break check. ARKit raw poses are OpenGL-ish, and CUT3R's
133
+ preprocessor applies a non-trivial `pose_cam_to_world @ rotated_to_cam` (an
134
+ in-plane sky-direction rotation), so the output convention was **not assumed** —
135
+ it was tested on real geometry by
136
+ `scripts/data_prep/verify_arkitscenes_pose_convention.py`.
137
+
138
+ **Test 1 — camera +Y world axis (Z-up world).** Mean camera +Y → world
139
+ `(-0.08, -0.12, -0.99)` = dominant **−Z** across all views ⇒ camera-Y points down
140
+ ⇒ OpenCV (y-down). (OpenGL y-up would give +Z.)
141
+
142
+ **Test 2 — multi-view point-cloud consistency** (the definitive test). Backproject
143
+ two **adjacent, high-overlap** frames into the world under OpenCV (c2w as-is) vs
144
+ OpenGL (`c2w @ diag(1,-1,-1,1)`) and measure cross-frame overlap:
145
+
146
+ | frame pair | OpenCV as-is | OpenGL flip |
147
+ |---|---|---|
148
+ | (0,1), baseline 2.9 cm | **median 0.011 m · 94% < 5 cm** | 0.016 m · 74% |
149
+ | (0,2), baseline 6.3 cm | **0.016 m · 93%** | 0.026 m · 62% |
150
+ | (10,11), rotated | **0.008 m · 94%** | 0.047 m · 53% |
151
+
152
+ OpenCV wins every pair, and the margin **grows with inter-frame rotation** (the
153
+ (10,11) pair: 94% vs 53%) — conclusive. (Comparing ctxt vs trgt directly is
154
+ unreliable: they barely overlap, which made an earlier 128-res ctxt/trgt test
155
+ ambiguous. Always use adjacent frames for this check.)
156
+
157
+ **Conclusion: CUT3R-preprocessed ARKitScenes `camera_pose` is c2w OpenCV.** The
158
+ `Cut3rAdapter` consumes it unchanged — **no `diag(1,-1,-1,1)` flip** (unlike SPOC's
159
+ Habitat poses). Adapter schema checks also pass: `ctxt_c2w[0]==identity`, RGB in
160
+ `[-1,1]`, depth 100% valid, normalized `cx≈cy≈0.5`.
161
+
162
+ **Pose drift** (40 samples, `max_interval=2`): mean translation **0.14 m**, mean
163
+ rotation **23°** — comfortably inside SPOC's bounds (1.0 m / 45°). `max_interval=2`
164
+ is a good default; raise it only if the full dataset's selected frames turn out to
165
+ be more densely spaced in time.
166
+
167
+ ---
168
+
169
+ ## 4. Finetuning / overfit
170
+
171
+ **Init: DFoT weights**, exactly as train.sh / train_re10k.sh / the WildRGBD
172
+ overfit — `checkpoint_path=checkpoints/DFoT_RE10K.ckpt` (diffusion init, full model)
173
+ + `model.encoder.encoder_ckpt=checkpoints/re10k.ckpt` (pixelsplat encoder).
174
+ `load_enc=true`, `load_optimizer=false`. The ~514 missing / 84 unexpected keys on
175
+ load are **expected** (DFoT init has a different head than the re10k encoder).
176
+
177
+ **Env: use the `3d-belief` conda env (torch 2.11), NOT `3d-belief-release`** — the
178
+ release env's `diff_gaussian_rasterization/_C.so` is stale (`undefined symbol
179
+ …decref_pyobject`). The `3d-belief` env has a working rasterizer build.
180
+
181
+ **Depth mask: ENABLED** (the SPOC-style setup the user asked for):
182
+ `use_depth_supervision=true`, `model.encoder.use_depth_mask=true`. The adapter's
183
+ `(d>0)&(d<far)` mask excludes invalid (0) LiDAR pixels.
184
+
185
+ Launch the single-scene overfit (scene `40958756`, `overfit_to_index=0`):
186
+
187
+ ```bash
188
+ cd /home/ubuntu/tianmin-neurips/zwen19/3d-belief
189
+ TRAIN_NUM_STEPS=8000 SAMPLE_EVERY=2000 SAVE_EVERY=4000 \
190
+ WARMUP_PERIOD=200 LR=2e-5 CUDA_VISIBLE_DEVICES=3 \
191
+ RESULTS_FOLDER=outputs/training/arkitscenes_overfit_scene0 \
192
+ bash scripts/training/finetune_arkitscenes_overfit.sh
193
+ ```
194
+
195
+ ### Key hyperparameters (overfit smoke)
196
+
197
+ | param | value | note |
198
+ |---|---|---|
199
+ | `image_size` | 128 | DFoT_RE10K / re10k.ckpt native res |
200
+ | `overfit_to_index` | 0 | deterministic (factory sets `cut3r_seed=42`) → scene 40958756, group 0 |
201
+ | `num_context` / `num_target` | 1 / 1 | forced by `setting_name=debug` regardless of CLI |
202
+ | `num_intermediate` | 3 | `intermediate=true` |
203
+ | `warmup_period` | **200** | base config default is **10000** — that keeps LR≈0 for a short overfit (lr 2e-5 ⇒ +2e-9/step). Multi-scene training keeps 10000. |
204
+ | `lr` | 2e-5 | canonical |
205
+ | depth | `use_depth_supervision=true`, `use_depth_mask=true` | |
206
+ | losses | rgb 1.0, depth 1.0, depth_smooth 0.1, intermediate 5.0, vggt_alignment 2.0, repa 5.0, lpips 1.0 | from `arkitscenes_cut3r.yaml` |
207
+
208
+ ### Smoke result (120-step, default warmup)
209
+
210
+ Pipeline runs end-to-end from DFoT with no errors; per-component losses all
211
+ present (`rgb_loss`, `depth_loss`≈1.8, `alignment_loss`≈4.96, no NaNs), depth
212
+ supervision active, `rgb_loss_ctxt` already trending down (0.74 → 0.37). 120 steps
213
+ under the 10000-step warmup is not a convergence test — see the 8000-step run
214
+ (`outputs/training/arkitscenes_overfit_scene0/logs.json.txt`) with `warmup_period=200`
215
+ for the actual overfit curve.
216
+
217
+ ### Overfit result (8000-step, `warmup_period=200`, scene 40958756, GPU 3)
218
+
219
+ Single-scene overfit **converges cleanly and monotonically** (100-step means):
220
+
221
+ | step | total loss | rgb_loss | rgb_loss_ctxt | depth_loss | alignment_loss |
222
+ |---|---|---|---|---|---|
223
+ | 0–100 | 39.9 | 0.461 | 0.445 | 1.760 | 4.953 |
224
+ | 200–300 | 17.4 | 0.069 | 0.050 | 0.277 | 4.608 |
225
+ | 500–600 | 11.5 | 0.036 | 0.041 | 0.079 | 3.718 |
226
+ | 1000–1100 | 8.4 | 0.019 | 0.035 | 0.056 | 3.095 |
227
+ | 1500–1600 | 7.1 | 0.014 | 0.031 | 0.050 | 2.782 |
228
+ | 2000–2100 | **6.3** | **0.011** | **0.028** | **0.049** | 2.543 |
229
+
230
+ `rgb_loss` drops below the skill's **0.05 overfit threshold by ~step 250** and reaches
231
+ **0.011 by step 2000**; `depth_loss` 1.8 → 0.049 (depth-mask supervision is fitting the
232
+ LiDAR depth); VGGT `alignment_loss` 5.0 → 2.5. **Milestone renders are healthy** — the
233
+ `milestone_1_rendered_frames/rendered_{0..19}.png` camera sweep has **0.0–0.2% black
234
+ pixels** across all frames (skill threshold: ≤1% healthy, >5% = collapsed gaussians), and
235
+ `rendered_10.png` (middle of the sweep) shows a coherent room (window+blinds, furniture),
236
+ not black. This is the definitive confirmation the dataloader + OpenCV convention are
237
+ correct — a wrong pose convention or pose-drift bug would empty the middle frames and
238
+ stall `rgb_loss` above 0.05.
239
+
240
+ Verdict: **a single ARKitScenes scene overfits**, so 3D-Belief can be trained on it. Scale
241
+ to multi-scene once the full dataset finishes downloading (re-run §1 preprocessing on the
242
+ full pairs `scene_list`, drop `overfit_to_index`, restore `warmup_period=10000`).
243
+
244
+ ---
245
+
246
+ ## 5. Gotchas (this host / dataset)
247
+
248
+ - **`conda run -n <env>` is broken here** — silently resolves to the colmap-cuda
249
+ env (py3.14). Always use absolute interpreter paths
250
+ (`.../envs/<env>/bin/python`).
251
+ - **Two different envs**: preprocessing → `3d-belief-release` (numpy<2 +
252
+ quaternion); training → `3d-belief` (torch 2.11, working rasterizer).
253
+ - **Precomputed pairs are mandatory** for `preprocess_arkitscenes.py`; it won't run
254
+ without DUSt3R's `arkitscenes_pairs`.
255
+ - **`generate_set` is not optional** — the loader reads `new_scene_metadata.npz`
256
+ (image_collection), which only step 2 writes. Step 1 alone → loader finds no
257
+ groups.
258
+ - Don't lower `video_prob` back below 1.0 or widen `max_interval` past ~2 for
259
+ handheld capture — both reintroduce the wide-baseline / non-temporal sampling
260
+ that empties the gaussian middles.
261
+ - See [`scripts/data_prep/verify_arkitscenes_pose_convention.py`] — re-run the
262
+ convention check before any new ARKitScenes training; trusting the upstream c2w
263
+ without verification is the #1 way to get silent garbage.
3d-belief/outputs/training/arkitscenes_overfit_scene0/logs.json.txt ADDED
The diff for this file is too large to render. See raw diff
 
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_depth.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f2efd6713c261547bad614429b1c2794f147d795f04f12cabb5a8a40d07dbb7f
3
+ size 169927
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_0.png ADDED

Git LFS Details

  • SHA256: f35ee4f7daf4ebaf9d3d2346020f3db386f3a3682a582dec970ffec10aa1b473
  • Pointer size: 130 Bytes
  • Size of remote file: 20.1 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_1.png ADDED

Git LFS Details

  • SHA256: 8b715eb876641aa2d853da0ac00c130369597ef7218cd4824d3adc8831ae0cc7
  • Pointer size: 130 Bytes
  • Size of remote file: 20.6 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_10.png ADDED

Git LFS Details

  • SHA256: bced0b04e0e5631bed935d638afe599137908fcd1427aab18e525724b203de9d
  • Pointer size: 130 Bytes
  • Size of remote file: 21.9 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_11.png ADDED

Git LFS Details

  • SHA256: 48e52b5aac7e5dc515ad5b5f43e1d0452bcbaa45e27f591f9d8a3e3a59cb1b30
  • Pointer size: 130 Bytes
  • Size of remote file: 21.8 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_12.png ADDED

Git LFS Details

  • SHA256: 45b154338abfcdbe8a9b72a020e43236fb15dadfa0f4087a41f37de0506832e7
  • Pointer size: 130 Bytes
  • Size of remote file: 21.4 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_13.png ADDED

Git LFS Details

  • SHA256: e253c37a445c313c42b44514807c55b6892628408d2e0e24e096572e73394a0a
  • Pointer size: 130 Bytes
  • Size of remote file: 21 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_14.png ADDED

Git LFS Details

  • SHA256: bd2bee6b4e5f5e236e84d4ea7d684173329212ef3f942a0ba6940642bd893a33
  • Pointer size: 130 Bytes
  • Size of remote file: 20.9 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_15.png ADDED

Git LFS Details

  • SHA256: 4d814131c9d26c0c251250d4ff842436a1cdaa9b03988b16e4554b80286e5e94
  • Pointer size: 130 Bytes
  • Size of remote file: 20.9 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_16.png ADDED

Git LFS Details

  • SHA256: de1cf7d0aa873ccb59a97e2abc9ec154c51bf6545040c669a6642375000dfb6d
  • Pointer size: 130 Bytes
  • Size of remote file: 20.8 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_17.png ADDED

Git LFS Details

  • SHA256: 7f9bdaf781e9079b26fefbeeaf758f65ed7b24aee5b225583680e07325cea0ea
  • Pointer size: 130 Bytes
  • Size of remote file: 20.4 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_18.png ADDED

Git LFS Details

  • SHA256: c213908bb739bbd6f3b66aef7ebf62308386354fe1c4bd2db2eaa14fe5e071f0
  • Pointer size: 130 Bytes
  • Size of remote file: 20.5 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_19.png ADDED

Git LFS Details

  • SHA256: 24c7e092fa8dbe6e0361f103fb3b2745c9330072622c94d0bfe6a70a470aadd1
  • Pointer size: 130 Bytes
  • Size of remote file: 20.3 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_2.png ADDED

Git LFS Details

  • SHA256: 5d4dc55407f7d562817c50f57e0d34f8b1de1d0e3b941affa2e57b7c3fcd9e65
  • Pointer size: 130 Bytes
  • Size of remote file: 21.1 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_3.png ADDED

Git LFS Details

  • SHA256: e2e5ba7704f31d043855372c82d1c3a8ecdc2aa0122726a5a95949ae8933097b
  • Pointer size: 130 Bytes
  • Size of remote file: 21.3 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_4.png ADDED

Git LFS Details

  • SHA256: ef721af25fef2065e8c7127dc00c7d2cbf29256cfbb086f8b0a3ed905f6aa23f
  • Pointer size: 130 Bytes
  • Size of remote file: 21.6 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_5.png ADDED

Git LFS Details

  • SHA256: 9ee3458e17a2d8bcc2ce4fa64a03645d278f22cdceb852b0b1c9f2481af66571
  • Pointer size: 130 Bytes
  • Size of remote file: 21.9 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_6.png ADDED

Git LFS Details

  • SHA256: bec712d62e6f07f015467b350f57c91f9d599e2f6cfb5a47c5bec0b55276e761
  • Pointer size: 130 Bytes
  • Size of remote file: 22.1 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_7.png ADDED

Git LFS Details

  • SHA256: 572e902f8ae385807c661ee8ff43082df4969a8426d6d8376ecc0a10bde203df
  • Pointer size: 130 Bytes
  • Size of remote file: 22 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_8.png ADDED

Git LFS Details

  • SHA256: a411dbe53f20220a3f3c5c2f851587440e05634910e93d8d076fe902e538aa3a
  • Pointer size: 130 Bytes
  • Size of remote file: 21.9 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_frames/rendered_9.png ADDED

Git LFS Details

  • SHA256: bccdea9010b9904d17f20fb071e03ef5816a45b1b2989eae1fd5750e75e9068e
  • Pointer size: 130 Bytes
  • Size of remote file: 21.8 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_1_rendered_rgb.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:60d87dd9a22c008872878b326b20607ebd3e943ac9371828d316a85c26160abf
3
+ size 121427
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_depth.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c762d4dae90a9c4ee65c91416a98b7897cd780909df8b4fd96106bd0bf2792d5
3
+ size 158013
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_0.png ADDED

Git LFS Details

  • SHA256: 4059975234cb4760d3c88a5f24be252e6e7538b835a33e46b2e3b7bbb57558a8
  • Pointer size: 130 Bytes
  • Size of remote file: 20.9 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_1.png ADDED

Git LFS Details

  • SHA256: acba40f3a955ee9000deb0762c0353afc84245b9a30bb31073a2f11ad986abe5
  • Pointer size: 130 Bytes
  • Size of remote file: 21.2 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_10.png ADDED

Git LFS Details

  • SHA256: f14d8bf0a2ac011cffa2249a8401a2a495721b79e5723fdde7df85fca56283b3
  • Pointer size: 130 Bytes
  • Size of remote file: 23.2 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_11.png ADDED

Git LFS Details

  • SHA256: 3446a5fdf7a75568d645ba23dc34f997925d4c94b0175a67746e7e0cdb4e0921
  • Pointer size: 130 Bytes
  • Size of remote file: 23.1 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_12.png ADDED

Git LFS Details

  • SHA256: 7fa7c05faad3dea4ba0af1f6f12780230e261589d00759abd8cb4ed5e5d256f8
  • Pointer size: 130 Bytes
  • Size of remote file: 22.9 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_13.png ADDED

Git LFS Details

  • SHA256: 985f5ae8ed591d2b464467220c5b56fb3b1abce7f1e59924a4b91061263075ab
  • Pointer size: 130 Bytes
  • Size of remote file: 22.4 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_14.png ADDED

Git LFS Details

  • SHA256: 3ac95ec9e492ddd7b188ebadcb0b127332b6e7af584b52127f9c6bd1cfd61d4c
  • Pointer size: 130 Bytes
  • Size of remote file: 22.3 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_15.png ADDED

Git LFS Details

  • SHA256: 0c0db78e530edc9a43ae445c19189f6405f159839b2d87e0a801353fc5382001
  • Pointer size: 130 Bytes
  • Size of remote file: 22.4 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_frames/rendered_16.png ADDED

Git LFS Details

  • SHA256: 651afa41876dce5ebf79a04154f694bd4b0de5bcf1ade907e780284383c9471a
  • Pointer size: 130 Bytes
  • Size of remote file: 22.4 kB
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_2_rendered_rgb.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:93bfe1713dd980aa89e725e9f9ff34b3e1c3a2d1bce5739d939b1319071883c3
3
+ size 137684
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_3_rendered_depth.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:668a6490be18df83852664c7127581d0a03cf211a16ab946cf9e853fc91d760a
3
+ size 152946
3d-belief/outputs/training/arkitscenes_overfit_scene0/milestone_3_rendered_rgb.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2cbd8ecd2c1fc25983249dbe831dcdc6a6742bede59446228caafe8ed05dc625
3
+ size 149260
3d-belief/outputs/training/arkitscenes_smoke/logs.json.txt ADDED
The diff for this file is too large to render. See raw diff
 
3d-belief/scripts/data_prep/verify_arkitscenes_pose_convention.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Verify the camera-pose convention + adapter schema for preprocessed ARKitScenes.
3
+
4
+ ARKitScenes is the single most important convention to get right here, because
5
+ ARKit raw poses are OpenGL-ish (x right, y up, z BACK) and CUT3R's
6
+ preprocess_arkitscenes.py applies a non-trivial `pose_cam_to_world @
7
+ rotated_to_cam` (an in-plane sky-direction rotation), so we must NOT assume the
8
+ result is OpenCV — we test it on real geometry.
9
+
10
+ The Cut3rAdapter feeds view["camera_pose"] downstream AS c2w OpenCV (x right,
11
+ y down, z forward). This script answers: is that actually true?
12
+
13
+ Three tests, in increasing rigor:
14
+
15
+ (1) Camera-Y world-axis. ARKitScenes' world frame is Z-up (preprocess uses
16
+ up_world = [0,0,1]). For an upright handheld camera looking roughly
17
+ horizontally, the OpenCV camera +Y axis (down) should point toward world
18
+ -Z. If c2w[:3,1] is dominantly +Z, the pose is OpenGL (Y up).
19
+
20
+ (2) Multi-view point-cloud consistency (the definitive test). Backproject two
21
+ time-separated frames' depth into the world under two hypotheses:
22
+ - OpenCV : use c2w as-is, OpenCV pinhole unprojection.
23
+ - OpenGL : use c2w @ diag(1,-1,-1,1), same unprojection.
24
+ Whichever hypothesis makes the two frames' surfaces OVERLAP (small median
25
+ nearest-neighbor distance) is the true convention. Mismatched conventions
26
+ send the two clouds to different/ mirrored places -> large NN distance.
27
+
28
+ (3) ctxt->trgt pose drift over many samples, to validate max_interval against
29
+ SPOC's bounds (mean translation < 1 m, mean rotation ~45 deg).
30
+
31
+ Run:
32
+ cd <repo_root>
33
+ PYTHONPATH=$PWD:$PWD/splat_belief \
34
+ .../envs/3d-belief-release/bin/python \
35
+ scripts/data_prep/verify_arkitscenes_pose_convention.py \
36
+ --root /home/ubuntu/tianmin-neurips/zwen19/data/ARKitScenes/processed_arkitscenes \
37
+ --scene 40958756
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import argparse
43
+ import os
44
+ import sys
45
+ from pathlib import Path
46
+
47
+ import numpy as np
48
+
49
+ # Make `import data_io...` work whether or not PYTHONPATH was set.
50
+ _REPO = Path(__file__).resolve().parents[2]
51
+ for p in (str(_REPO), str(_REPO / "splat_belief")):
52
+ if p not in sys.path:
53
+ sys.path.insert(0, p)
54
+
55
+ from data_io.cut3r_adapter import build_cut3r_dataset, Cut3rAdapter # noqa: E402
56
+
57
+ OPENGL_FLIP = np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float64)
58
+
59
+
60
+ def unproject_opencv(depth_m, K):
61
+ """Backproject valid depth pixels with the OpenCV pinhole model -> (N,3) cam."""
62
+ H, W = depth_m.shape
63
+ us, vs = np.meshgrid(np.arange(W), np.arange(H))
64
+ valid = depth_m > 0
65
+ u = us[valid].astype(np.float64)
66
+ v = vs[valid].astype(np.float64)
67
+ d = depth_m[valid].astype(np.float64)
68
+ fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2]
69
+ x = (u - cx) * d / fx
70
+ y = (v - cy) * d / fy
71
+ return np.stack([x, y, d], axis=-1)
72
+
73
+
74
+ def cam_to_world(pts_cam, c2w):
75
+ ones = np.ones((pts_cam.shape[0], 1))
76
+ return (c2w @ np.concatenate([pts_cam, ones], axis=-1).T).T[:, :3]
77
+
78
+
79
+ def median_nn(a, b, max_pts=4000, seed=0):
80
+ """Median nearest-neighbor distance from a -> b (subsampled)."""
81
+ from scipy.spatial import cKDTree
82
+ rng = np.random.default_rng(seed)
83
+ if a.shape[0] > max_pts:
84
+ a = a[rng.choice(a.shape[0], max_pts, replace=False)]
85
+ if b.shape[0] > max_pts:
86
+ b = b[rng.choice(b.shape[0], max_pts, replace=False)]
87
+ d, _ = cKDTree(b).query(a, k=1)
88
+ return float(np.median(d))
89
+
90
+
91
+ def rot_angle_deg(Ra, Rb):
92
+ R = Ra.T @ Rb
93
+ c = (np.trace(R) - 1.0) / 2.0
94
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
95
+
96
+
97
+ def find_scene_idx(cut3r, scene):
98
+ """Return a dataset index whose sampled sequence is from `scene`."""
99
+ for i in range(min(len(cut3r), 50)):
100
+ v = cut3r[i]
101
+ if v[0]["label"].split("_")[0] == scene:
102
+ return i
103
+ return 0
104
+
105
+
106
+ def main():
107
+ ap = argparse.ArgumentParser()
108
+ ap.add_argument("--root", required=True)
109
+ ap.add_argument("--scene", default="40958756")
110
+ ap.add_argument("--num_views", type=int, default=5) # 1 ctxt + 1 trgt + 3 intm
111
+ ap.add_argument("--image_size", type=int, default=128)
112
+ ap.add_argument("--drift_samples", type=int, default=40)
113
+ args = ap.parse_args()
114
+
115
+ res = (args.image_size, args.image_size)
116
+ # seed -> deterministic sampling (mirrors overfit's cut3r_seed=42)
117
+ cut3r = build_cut3r_dataset("arkitscenes", root=args.root, split="train",
118
+ num_views=args.num_views, resolution=res, seed=42)
119
+ print(f"[verify] dataset len (groups) = {len(cut3r)}; scenes = "
120
+ f"{list(getattr(cut3r, 'scenes', []))}")
121
+
122
+ idx = find_scene_idx(cut3r, args.scene)
123
+ views = cut3r[idx]
124
+ print(f"[verify] using idx={idx}, scene={views[0]['label'].split('_')[0]}, "
125
+ f"{len(views)} views; labels={[v['label'] for v in views]}")
126
+
127
+ # ---- intrinsics report (fills the yaml fx/fy fallback) ----
128
+ K = views[0]["camera_intrinsics"].astype(np.float64)
129
+ th, tw = views[0]["true_shape"]
130
+ print(f"\n[verify] first-view K (pixel, true_shape={int(th)}x{int(tw)}):\n{np.round(K,2)}")
131
+ print(f" normalized: fx/W={K[0,0]/tw:.3f} fy/H={K[1,1]/th:.3f} "
132
+ f"cx/W={K[0,2]/tw:.3f} cy/H={K[1,2]/th:.3f}")
133
+
134
+ # ---- (1) camera-Y world axis (Z-up world) ----
135
+ print("\n[verify] TEST 1 — camera +Y world axis (Z-up world):")
136
+ for i, v in enumerate(views):
137
+ c2w = v["camera_pose"].astype(np.float64)
138
+ y = c2w[:3, 1]; z = c2w[:3, 2]
139
+ print(f" view{i}: cam+Y_world=({y[0]:+.2f},{y[1]:+.2f},{y[2]:+.2f}) "
140
+ f"cam+Z_world(fwd)=({z[0]:+.2f},{z[1]:+.2f},{z[2]:+.2f})")
141
+ meanY = np.mean([v["camera_pose"][:3, 1] for v in views], axis=0)
142
+ print(f" mean cam+Y world = ({meanY[0]:+.2f},{meanY[1]:+.2f},{meanY[2]:+.2f}) "
143
+ f"-> dominant {'−Z (OpenCV, Y-down)' if meanY[2] < 0 else '+Z (OpenGL, Y-up)'}")
144
+
145
+ # ---- (2) multi-view point-cloud consistency ----
146
+ # Use ADJACENT views (high overlap) — comparing ctxt vs trgt (far apart)
147
+ # gives an unreliable verdict because they barely overlap. With adjacent
148
+ # frames the correct convention is cm-scale; the wrong one degrades clearly
149
+ # (and degrades MORE as inter-frame rotation grows).
150
+ print("\n[verify] TEST 2 — multi-view consistency, ADJACENT views (OpenCV vs OpenGL flip):")
151
+ va, vb = views[0], views[1]
152
+ Ka, Kb = va["camera_intrinsics"].astype(np.float64), vb["camera_intrinsics"].astype(np.float64)
153
+ da, db = va["depthmap"].astype(np.float64), vb["depthmap"].astype(np.float64)
154
+ pa, pb = unproject_opencv(da, Ka), unproject_opencv(db, Kb)
155
+ for tag, M in (("OpenCV (as-is)", np.eye(4)), ("OpenGL (@diag(1,-1,-1,1))", OPENGL_FLIP)):
156
+ wa = cam_to_world(pa, va["camera_pose"].astype(np.float64) @ M)
157
+ wb = cam_to_world(pb, vb["camera_pose"].astype(np.float64) @ M)
158
+ nn = median_nn(wa, wb)
159
+ print(f" {tag:32s}: median cross-frame NN dist = {nn:.3f} m")
160
+
161
+ # ---- (3) ctxt->trgt drift ----
162
+ print("\n[verify] TEST 3 — ctxt->trgt pose drift "
163
+ f"({args.drift_samples} samples, max_interval={cut3r.max_interval}):")
164
+ trans, rots = [], []
165
+ for i in range(args.drift_samples):
166
+ v = cut3r[i % len(cut3r)]
167
+ c0 = v[0]["camera_pose"].astype(np.float64)
168
+ c1 = v[-1]["camera_pose"].astype(np.float64)
169
+ trans.append(np.linalg.norm(c1[:3, 3] - c0[:3, 3]))
170
+ rots.append(rot_angle_deg(c0[:3, :3], c1[:3, :3]))
171
+ trans, rots = np.array(trans), np.array(rots)
172
+ print(f" translation: mean={trans.mean():.2f} m median={np.median(trans):.2f} max={trans.max():.2f}")
173
+ print(f" rotation : mean={rots.mean():.1f}° median={np.median(rots):.1f} max={rots.max():.1f}")
174
+ print(f" SPOC bounds: adjacent_distance=1.0 m, adjacent_angle=45° "
175
+ f"-> {'OK' if trans.mean()<1.0 and rots.mean()<60 else 'TOO WIDE: lower max_interval'}")
176
+
177
+ # ---- adapter schema check ----
178
+ print("\n[verify] adapter schema (language_encoder=None -> lang is None):")
179
+ ad = Cut3rAdapter(cut3r_dataset=cut3r, num_context=1, num_target=1,
180
+ image_size=args.image_size, language_encoder=None,
181
+ use_depth_supervision=True, intermediate=True,
182
+ num_intermediate=3, z_near=0.1, z_far=10.0,
183
+ overfit_to_index=idx)
184
+ d, trgt = ad[0]
185
+ for k in ("ctxt_rgb", "trgt_rgb", "intm_rgb", "ctxt_c2w", "trgt_c2w",
186
+ "intm_c2w", "ctxt_abs_camera_poses", "intrinsics",
187
+ "ctxt_depth", "ctxt_depth_mask", "near", "far", "image_shape"):
188
+ if k in d:
189
+ val = d[k]
190
+ shp = tuple(val.shape) if hasattr(val, "shape") else val
191
+ print(f" {k:24s}: {shp}")
192
+ else:
193
+ print(f" {k:24s}: MISSING")
194
+ rgb = d["ctxt_rgb"]
195
+ print(f" ctxt_rgb range = [{rgb.min():.2f}, {rgb.max():.2f}] (expect ~[-1,1])")
196
+ import torch
197
+ assert torch.allclose(d["ctxt_c2w"][0], torch.eye(4), atol=1e-4), "ctxt_c2w[0] != identity!"
198
+ print(" ctxt_c2w[0] == identity ✓")
199
+ cm = d["ctxt_depth_mask"]
200
+ print(f" ctxt_depth valid fraction = {cm.float().mean().item():.1%}")
201
+ print("\n[verify] DONE.")
202
+
203
+
204
+ if __name__ == "__main__":
205
+ main()
3d-belief/scripts/training/finetune_arkitscenes_overfit.sh ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ #
3
+ # Single-scene overfit smoke test on ARKitScenes (scene 40958756, idx 0).
4
+ #
5
+ # ARKitScenes analog of finetune_wildrgbd_overfit.sh. Loads DFoT_RE10K.ckpt +
6
+ # re10k.ckpt as initialization (same as train.sh / train_re10k.sh / the WildRGBD
7
+ # overfit) then finetunes the encoder on a single ARKitScenes (ctxt, trgt, intm)
8
+ # sample with overfit_to_index=0 so we can verify the loss actually drops.
9
+ #
10
+ # Camera convention: verify_arkitscenes_pose_convention.py confirms CUT3R's
11
+ # preprocessed ARKitScenes camera_pose is c2w OpenCV (x right, y down, z fwd) —
12
+ # the convention the Cut3rAdapter assumes. Multi-view consistency at 94% <5cm
13
+ # for the OpenCV hypothesis vs 53% for the OpenGL flip. NO pose flip needed.
14
+ #
15
+ # Depth: ARKitScenes ships per-frame metric iPad-LiDAR depth (lowres_depth, mm,
16
+ # 0=invalid). Depth supervision + the depth mask are ENABLED (use_depth_supervision
17
+ # + model.encoder.use_depth_mask=true), per the SPOC-style setup.
18
+ #
19
+ # Required env vars (with sensible defaults):
20
+ # DATASET_ROOT - path to processed_arkitscenes/ (the dir with Training/)
21
+ # CKPT_DIR - directory with DFoT_RE10K.ckpt + re10k.ckpt
22
+ # CUDA_VISIBLE_DEVICES - which GPU (default: 3)
23
+
24
+ set -e
25
+
26
+ # ---- environment ----
27
+ # NOTE: use the `3d-belief` env (torch 2.11), NOT `3d-belief-release`. The
28
+ # release env's diff_gaussian_rasterization _C.so is stale (built against an
29
+ # older libtorch) and fails with `undefined symbol ...decref_pyobject`. The
30
+ # `3d-belief` env has a working rasterizer build. (quaternion is broken there
31
+ # under numpy 2.x but is only needed by the CUT3R *preprocessing* scripts, not
32
+ # the dataloader/training path.)
33
+ eval "$(conda shell.bash hook)"
34
+ conda activate 3d-belief
35
+
36
+ nvidia-smi
37
+ REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
38
+ cd "$REPO_ROOT"
39
+ # Avoid PYTHONPATH shadowing by an older splat_belief copy
40
+ # (see memory: 3d-belief-training-script-gotchas).
41
+ export PYTHONPATH="${REPO_ROOT}:${PYTHONPATH}"
42
+
43
+ DATASET_ROOT="${DATASET_ROOT:-/home/ubuntu/tianmin-neurips/zwen19/data/ARKitScenes/processed_arkitscenes}"
44
+ CKPT_DIR="${CKPT_DIR:-${REPO_ROOT}/checkpoints}"
45
+ STAGE="${STAGE:-train}"
46
+
47
+ export MASTER_PORT=$((12000 + RANDOM % 1000))
48
+ export PATH=$CONDA_PREFIX/bin:$PATH
49
+ export CUDA_HOME=$CONDA_PREFIX
50
+ export LD_LIBRARY_PATH=$CONDA_PREFIX/lib:$LD_LIBRARY_PATH
51
+ export CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-3}"
52
+ export TORCH_CUDA_ARCH_LIST="8.6;9.0"
53
+
54
+ # Tunables for the smoke test — override in the env to scale up.
55
+ RESULTS_FOLDER="${RESULTS_FOLDER:-outputs/training/arkitscenes_overfit_scene0}"
56
+ TRAIN_NUM_STEPS="${TRAIN_NUM_STEPS:-500}"
57
+ SAMPLE_EVERY="${SAMPLE_EVERY:-100}"
58
+ SAVE_EVERY="${SAVE_EVERY:-500}"
59
+ # wandb_every must divide sample_every (assert in diffusion.py:1514).
60
+ WANDB_EVERY="${WANDB_EVERY:-${SAMPLE_EVERY}}"
61
+ NUM_INTERMEDIATE="${NUM_INTERMEDIATE:-3}"
62
+ OVERFIT_TO_INDEX="${OVERFIT_TO_INDEX:-0}" # idx 0 -> scene 40958756, group 0
63
+ # The base config warmup_period=10000 (with lr=2e-5 => +2e-9/step). That keeps
64
+ # the LR near-zero for a short overfit, so the loss can't move. Use a short
65
+ # warmup for the overfit smoke (the multi-scene training script keeps the
66
+ # canonical 10000).
67
+ WARMUP_PERIOD="${WARMUP_PERIOD:-200}"
68
+ LR="${LR:-2e-5}"
69
+
70
+ mkdir -p "${RESULTS_FOLDER}"
71
+
72
+ # DFoT init (same as train.sh / train_re10k.sh / WildRGBD overfit).
73
+ CKPT_PATH="${CKPT_PATH:-${CKPT_DIR}/DFoT_RE10K.ckpt}"
74
+ LOAD_ENC="${LOAD_ENC:-true}"
75
+ ENCODER_CKPT="${ENCODER_CKPT:-${CKPT_DIR}/re10k.ckpt}"
76
+ DATASET_VIZ_TYPE="${DATASET_VIZ_TYPE:-}" # leave empty to keep YAML default (interpolation)
77
+
78
+ CUDA_LAUNCH_BLOCKING=1 torchrun --nnodes 1 --nproc_per_node 1 --master_port $MASTER_PORT \
79
+ splat_belief/experiment/train.py \
80
+ dataset=arkitscenes_cut3r \
81
+ dataset.root_dir="${DATASET_ROOT}" \
82
+ dataset.vggt_alignment_loss_weight=2.0 \
83
+ dataset.intermediate_weight=5.0 \
84
+ dataset.depth_smooth_loss_weight=0.1 \
85
+ setting_name=debug \
86
+ stage="${STAGE}" \
87
+ use_depth_supervision=true \
88
+ results_folder="${RESULTS_FOLDER}" \
89
+ semantic_config=splat_belief/config/semantic/onehot.yaml \
90
+ checkpoint_path="${CKPT_PATH}" \
91
+ $( [ -n "${DATASET_VIZ_TYPE}" ] && echo "dataset.viz_type=${DATASET_VIZ_TYPE}" ) \
92
+ ngpus=1 \
93
+ image_size=128 \
94
+ train_num_steps=${TRAIN_NUM_STEPS} \
95
+ warmup_period=${WARMUP_PERIOD} \
96
+ lr=${LR} \
97
+ sample_every=${SAMPLE_EVERY} \
98
+ save_every=${SAVE_EVERY} \
99
+ wandb_every=${WANDB_EVERY} \
100
+ overfit_to_index=${OVERFIT_TO_INDEX} \
101
+ ctxt_min=5 \
102
+ ctxt_max=15 \
103
+ model/encoder=uvitmvsplat \
104
+ model.encoder.use_image_condition=true \
105
+ model.encoder.depth_predictor_time_embed=true \
106
+ model.encoder.use_camera_pose=true \
107
+ model.encoder.use_semantic=false \
108
+ model.encoder.use_reg_model=false \
109
+ model.encoder.d_semantic=512 \
110
+ model.encoder.d_semantic_reg=384 \
111
+ model.encoder.gaussians_per_pixel=1 \
112
+ model.encoder.evolve_ctxt=false \
113
+ model.encoder.use_depth_mask=true \
114
+ model.encoder.encoder_ckpt="${ENCODER_CKPT}" \
115
+ model.encoder.freeze_depth_predictor=false \
116
+ model/encoder/backbone=u_vit3d_pose \
117
+ model.encoder.backbone.use_vggt_alignment=true \
118
+ model.encoder.backbone.use_repa=true \
119
+ model.encoder.backbone.input_size='[128, 128]' \
120
+ alignment.latents_info=-1 \
121
+ ctxt_losses_factor=0.9 \
122
+ repa_encoder_resolution=512 \
123
+ model_type=uvit_pose \
124
+ name=arkitscenes_overfit \
125
+ wandb=local \
126
+ clean_target=false \
127
+ use_identity=true \
128
+ intermediate=true \
129
+ num_intermediate=${NUM_INTERMEDIATE} \
130
+ load_optimizer=false \
131
+ load_enc=${LOAD_ENC} \
132
+ finetune_component=encoder \
133
+ finetune_steps=5 \
134
+ use_depth_smoothness=true \
135
+ adjacent_angle=0.785 \
136
+ adjacent_distance=1.0
3d-belief/splat_belief/config/dataset/arkitscenes_cut3r.yaml ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "arkitscenes_cut3r"
2
+ # Which CUT3R BaseMultiViewDataset class to wrap. "arkitscenes" routes to an
3
+ # ARKitScenes_Multi subclass (cut3r_adapter._make_arkitscenes_short) that forces
4
+ # the temporal-video branch + video_prob=1.0 + a tighter max_interval, and stubs
5
+ # the <ROOT>_highres dir the raw loader requires. The forced temporal ordering is
6
+ # what makes the [ctxt, intm..., trgt] split in Cut3rAdapter.__getitem__
7
+ # correspond to ascending time (required by the intermediate-frame loss).
8
+ cut3r_dataset_class: "arkitscenes"
9
+ overfit_to_index: null
10
+ lindisp: false
11
+ # Room-scale handheld capture: ctxt/trgt are close in pose (after the short-window
12
+ # sampler), so the linear interpolation trajectory between them stays inside seen
13
+ # views -> "interpolation" viz is legible (unlike the object-centric WildRGBD case
14
+ # that needed "spherical").
15
+ viz_type: "interpolation"
16
+ dist_loss_weight: 0.005
17
+ # ARKitScenes ships per-frame metric depth from the iPad LiDAR (lowres_depth, mm,
18
+ # 0 = invalid). The (d > 0) & (d < far) mask in cut3r_adapter.stack_depth excludes
19
+ # invalid pixels, so full-strength depth supervision is appropriate.
20
+ depth_loss_weight: 1.0
21
+ depth_mask_loss_weight: 0.0
22
+ # Smoothness regularizes the encoder's PREDICTED depth (not GT) -> keep at the
23
+ # canonical 0.1 (matches train.sh / train_re10k.sh CLI overrides).
24
+ depth_smooth_loss_weight: 0.1
25
+ # No semantic labels used for ARKitScenes finetuning.
26
+ semantic_loss_weight: 0.0
27
+ semantic_reg_loss_weight: 0.0
28
+ lpips_loss_weight: 1.0
29
+ repa_loss_weight: 5.0
30
+ rgb_loss_weight: 1.0
31
+ # Canonical intermediate_weight per train.sh / train_re10k.sh CLI overrides.
32
+ intermediate_weight: 5.0
33
+ # VGGT alignment submodule auto-loads facebook/VGGT-1B from HF Hub at construction
34
+ # (splat/alignment/vggt_alignment_loss.py); canonical weight = 2.0.
35
+ vggt_alignment_loss_weight: 2.0
36
+ root_dir: ""
37
+ camera:
38
+ # CUT3R's _crop_resize_if_necessary center-crops every frame so the principal
39
+ # point is centered: cx_norm = cy_norm = 0.5 by construction. fx/fy here are
40
+ # nominal fallbacks (model.camera = ${dataset.camera}); the per-sample
41
+ # intrinsics from the dataset dict take precedence in the encoder forward.
42
+ # ARKitScenes vga_wide ~ iPad rear camera. Measured fx_norm = fy_norm ≈ 1.16
43
+ # after the square center-crop (HFOV ≈ 47°); cx_norm=0.496, cy_norm=0.501
44
+ # (centered) — see verify_arkitscenes_pose_convention.py output for scene
45
+ # 40958756. These are nominal fallbacks; per-sample K from the dataset dict
46
+ # takes precedence in the encoder forward.
47
+ fx: 1.16
48
+ fy: 1.16
49
+ cx: 0.5
50
+ cy: 0.5
51
+ # Room-scale indoor (handheld iPad): depth typically ~0.2–6 m, occasionally to
52
+ # ~10 m. near=0.1 / far=10.0 covers the room while keeping splat depth
53
+ # precision tighter than the 20 m RealEstate/ScanNet default.
54
+ near: 0.1
55
+ far: 10.0
56
+ h: 128
57
+ w: 128
3d-belief/third_party/CUT3R/datasets_preprocess/generate_set_arkitscenes.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Preprocess scenes by sorting images and generating image/video collections.
4
+
5
+ This script processes scenes in parallel using a thread pool, updating metadata
6
+ with sorted images, trajectories, intrinsics, and generating pair, image collection,
7
+ and video collection data. The processed metadata is saved to a new file in each scene directory.
8
+
9
+ Usage:
10
+ python generate_set_arkitscenes.py --root /path/to/data --splits Training Test --max_interval 5.0 --num_workers 8
11
+ """
12
+
13
+ import os
14
+ import os.path as osp
15
+ import argparse
16
+ import numpy as np
17
+ from concurrent.futures import ThreadPoolExecutor, as_completed
18
+ from tqdm import tqdm
19
+
20
+
21
+ def get_timestamp(img_name):
22
+ """
23
+ Extract the timestamp from an image filename.
24
+ Assumes the timestamp is the last underscore-separated token in the name (before the file extension).
25
+
26
+ Args:
27
+ img_name (str): The image filename.
28
+
29
+ Returns:
30
+ float: The extracted timestamp.
31
+ """
32
+ return float(img_name[:-4].split("_")[-1])
33
+
34
+
35
+ def process_scene(root, split, scene, max_interval):
36
+ """
37
+ Process a single scene by sorting its images by timestamp, updating trajectories,
38
+ intrinsics, and pairings, and generating image/video collections.
39
+
40
+ Args:
41
+ root (str): Root directory of the dataset.
42
+ split (str): The dataset split (e.g., 'Training', 'Test').
43
+ scene (str): The scene identifier.
44
+ max_interval (float): Maximum allowed time interval (in seconds) between images to consider them in the same video collection.
45
+ """
46
+ scene_dir = osp.join(root, split, scene)
47
+ metadata_path = osp.join(scene_dir, "scene_metadata.npz")
48
+
49
+ # Load the scene metadata
50
+ with np.load(metadata_path) as data:
51
+ images = data["images"]
52
+ trajectories = data["trajectories"]
53
+ intrinsics = data["intrinsics"]
54
+ pairs = data["pairs"]
55
+
56
+ # Sort images by timestep
57
+ imgs_with_indices = sorted(enumerate(images), key=lambda x: x[1])
58
+ indices, images = zip(*imgs_with_indices)
59
+ indices = np.array(indices)
60
+ index2sorted = {index: i for i, index in enumerate(indices)}
61
+
62
+ # Reorder trajectories and intrinsics based on the new image order
63
+ trajectories = trajectories[indices]
64
+ intrinsics = intrinsics[indices]
65
+
66
+ # Update pair indices (each pair is (id1, id2, score))
67
+ pairs = [(index2sorted[id1], index2sorted[id2], score) for id1, id2, score in pairs]
68
+
69
+ # Form image_collection: mapping from an image id to a list of (other image id, score)
70
+ image_collection = {}
71
+ for id1, id2, score in pairs:
72
+ image_collection.setdefault(id1, []).append((id2, score))
73
+
74
+ # Form video_collection: for each image, collect subsequent images within the max_interval time window
75
+ video_collection = {}
76
+ for i, image in enumerate(images):
77
+ j = i + 1
78
+ for j in range(i + 1, len(images)):
79
+ if get_timestamp(images[j]) - get_timestamp(image) > max_interval:
80
+ break
81
+ video_collection[i] = list(range(i + 1, j))
82
+
83
+ # Save the new metadata
84
+ output_path = osp.join(scene_dir, "new_scene_metadata.npz")
85
+ np.savez(
86
+ output_path,
87
+ images=images,
88
+ trajectories=trajectories,
89
+ intrinsics=intrinsics,
90
+ pairs=pairs,
91
+ image_collection=image_collection,
92
+ video_collection=video_collection,
93
+ )
94
+ print(f"Processed scene: {scene}")
95
+
96
+
97
+ def main(args):
98
+ """
99
+ Main function to process scenes across specified dataset splits in parallel.
100
+ """
101
+ root = args.root
102
+ splits = args.splits
103
+ max_interval = args.max_interval
104
+ num_workers = args.num_workers
105
+
106
+ futures = []
107
+
108
+ # Create a ThreadPoolExecutor for parallel processing
109
+ with ThreadPoolExecutor(max_workers=num_workers) as executor:
110
+ for split in splits:
111
+ all_meta_path = osp.join(root, split, "all_metadata.npz")
112
+ with np.load(all_meta_path) as data:
113
+ scenes = data["scenes"]
114
+
115
+ # Submit processing tasks for each scene in the current split
116
+ for scene in scenes:
117
+ futures.append(
118
+ executor.submit(process_scene, root, split, scene, max_interval)
119
+ )
120
+
121
+ # Use tqdm to display a progress bar as futures complete
122
+ for future in tqdm(
123
+ as_completed(futures), total=len(futures), desc="Processing scenes"
124
+ ):
125
+ # This will raise any exceptions caught during scene processing.
126
+ future.result()
127
+
128
+
129
+ if __name__ == "__main__":
130
+ parser = argparse.ArgumentParser(
131
+ description="Preprocess scene data to update metadata with sorted images and collections."
132
+ )
133
+ parser.add_argument(
134
+ "--root",
135
+ type=str,
136
+ default="",
137
+ help="Root directory containing the dataset splits.",
138
+ )
139
+ parser.add_argument(
140
+ "--splits",
141
+ type=str,
142
+ nargs="+",
143
+ default=["Training", "Test"],
144
+ help="List of dataset splits to process (e.g., Training Test).",
145
+ )
146
+ parser.add_argument(
147
+ "--max_interval",
148
+ type=float,
149
+ default=5.0,
150
+ help="Maximum time interval (in seconds) between images to consider them in the same video sequence.",
151
+ )
152
+ parser.add_argument(
153
+ "--num_workers",
154
+ type=int,
155
+ default=8,
156
+ help="Number of worker threads for parallel processing.",
157
+ )
158
+ args = parser.parse_args()
159
+ main(args)
3d-belief/third_party/CUT3R/datasets_preprocess/preprocess_arkitscenes.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import os.path as osp
4
+ import decimal
5
+ import argparse
6
+ import math
7
+ from bisect import bisect_left
8
+ from PIL import Image
9
+ import numpy as np
10
+ import quaternion
11
+ from scipy import interpolate
12
+ import cv2
13
+ from tqdm import tqdm
14
+
15
+
16
+ def get_parser():
17
+ parser = argparse.ArgumentParser()
18
+ parser.add_argument(
19
+ "--arkitscenes_dir",
20
+ default="data/dust3r_data/data_arkitscenes/raw",
21
+ )
22
+ parser.add_argument(
23
+ "--precomputed_pairs",
24
+ default="data/dust3r_data/data_arkitscenes/arkitscenes_pairs",
25
+ )
26
+ parser.add_argument(
27
+ "--output_dir",
28
+ default="data/dust3r_data/processed_arkitscenes",
29
+ )
30
+ return parser
31
+
32
+
33
+ def value_to_decimal(value, decimal_places):
34
+ decimal.getcontext().rounding = decimal.ROUND_HALF_UP # define rounding method
35
+ return decimal.Decimal(str(float(value))).quantize(
36
+ decimal.Decimal("1e-{}".format(decimal_places))
37
+ )
38
+
39
+
40
+ def closest(value, sorted_list):
41
+ index = bisect_left(sorted_list, value)
42
+ if index == 0:
43
+ return sorted_list[0]
44
+ elif index == len(sorted_list):
45
+ return sorted_list[-1]
46
+ else:
47
+ value_before = sorted_list[index - 1]
48
+ value_after = sorted_list[index]
49
+ if value_after - value < value - value_before:
50
+ return value_after
51
+ else:
52
+ return value_before
53
+
54
+
55
+ def get_up_vectors(pose_device_to_world):
56
+ return np.matmul(pose_device_to_world, np.array([[0.0], [-1.0], [0.0], [0.0]]))
57
+
58
+
59
+ def get_right_vectors(pose_device_to_world):
60
+ return np.matmul(pose_device_to_world, np.array([[1.0], [0.0], [0.0], [0.0]]))
61
+
62
+
63
+ def read_traj(traj_path):
64
+ quaternions = []
65
+ poses = []
66
+ timestamps = []
67
+ poses_p_to_w = []
68
+ with open(traj_path) as f:
69
+ traj_lines = f.readlines()
70
+ for line in traj_lines:
71
+ tokens = line.split()
72
+ assert len(tokens) == 7
73
+ traj_timestamp = float(tokens[0])
74
+
75
+ timestamps_decimal_value = value_to_decimal(traj_timestamp, 3)
76
+ timestamps.append(
77
+ float(timestamps_decimal_value)
78
+ ) # for spline interpolation
79
+
80
+ angle_axis = [float(tokens[1]), float(tokens[2]), float(tokens[3])]
81
+ r_w_to_p, _ = cv2.Rodrigues(np.asarray(angle_axis))
82
+ t_w_to_p = np.asarray(
83
+ [float(tokens[4]), float(tokens[5]), float(tokens[6])]
84
+ )
85
+
86
+ pose_w_to_p = np.eye(4)
87
+ pose_w_to_p[:3, :3] = r_w_to_p
88
+ pose_w_to_p[:3, 3] = t_w_to_p
89
+
90
+ pose_p_to_w = np.linalg.inv(pose_w_to_p)
91
+
92
+ r_p_to_w_as_quat = quaternion.from_rotation_matrix(pose_p_to_w[:3, :3])
93
+ t_p_to_w = pose_p_to_w[:3, 3]
94
+ poses_p_to_w.append(pose_p_to_w)
95
+ poses.append(t_p_to_w)
96
+ quaternions.append(r_p_to_w_as_quat)
97
+ return timestamps, poses, quaternions, poses_p_to_w
98
+
99
+
100
+ def main(rootdir, pairsdir, outdir):
101
+ os.makedirs(outdir, exist_ok=True)
102
+
103
+ subdirs = ["Test", "Training"]
104
+ for subdir in subdirs:
105
+ # STEP 1: list all scenes
106
+ outsubdir = osp.join(outdir, subdir)
107
+ os.makedirs(outsubdir, exist_ok=True)
108
+ listfile = osp.join(pairsdir, subdir, "scene_list.json")
109
+ with open(listfile, "r") as f:
110
+ scene_dirs = json.load(f)
111
+
112
+ valid_scenes = []
113
+ for scene_subdir in tqdm(scene_dirs):
114
+ if not os.path.isdir(osp.join(rootdir, "Test", scene_subdir)):
115
+ if not os.path.isdir(osp.join(rootdir, "Training", scene_subdir)):
116
+ continue
117
+ else:
118
+ root_subdir = "Training"
119
+ else:
120
+ root_subdir = "Test"
121
+ out_scene_subdir = osp.join(outsubdir, scene_subdir)
122
+ os.makedirs(out_scene_subdir, exist_ok=True)
123
+
124
+ scene_dir = osp.join(rootdir, root_subdir, scene_subdir)
125
+ depth_dir = osp.join(scene_dir, "lowres_depth")
126
+ rgb_dir = osp.join(scene_dir, "vga_wide")
127
+ intrinsics_dir = osp.join(scene_dir, "vga_wide_intrinsics")
128
+ traj_path = osp.join(scene_dir, "lowres_wide.traj")
129
+
130
+ # STEP 2: read selected_pairs.npz
131
+ selected_pairs_path = osp.join(
132
+ pairsdir, subdir, scene_subdir, "selected_pairs.npz"
133
+ )
134
+ selected_npz = np.load(selected_pairs_path)
135
+ selection, pairs = selected_npz["selection"], selected_npz["pairs"]
136
+ selected_sky_direction_scene = str(selected_npz["sky_direction_scene"][0])
137
+ if len(selection) == 0 or len(pairs) == 0:
138
+ # not a valid scene
139
+ continue
140
+ valid_scenes.append(scene_subdir)
141
+
142
+ # STEP 3: parse the scene and export the list of valid (K, pose, rgb, depth) and convert images
143
+ scene_metadata_path = osp.join(out_scene_subdir, "scene_metadata.npz")
144
+ if osp.isfile(scene_metadata_path):
145
+ continue
146
+ else:
147
+ print(f"parsing {scene_subdir}")
148
+ # loads traj
149
+ timestamps, poses, quaternions, poses_cam_to_world = read_traj(
150
+ traj_path
151
+ )
152
+
153
+ poses = np.array(poses)
154
+ quaternions = np.array(quaternions, dtype=np.quaternion)
155
+ quaternions = quaternion.unflip_rotors(quaternions)
156
+ timestamps = np.array(timestamps)
157
+
158
+ selected_images = [
159
+ (basename, basename.split(".png")[0].split("_")[1])
160
+ for basename in selection
161
+ ]
162
+ timestamps_selected = [
163
+ float(frame_id) for _, frame_id in selected_images
164
+ ]
165
+
166
+ sky_direction_scene, trajectories, intrinsics, images = (
167
+ convert_scene_metadata(
168
+ scene_subdir,
169
+ intrinsics_dir,
170
+ timestamps,
171
+ quaternions,
172
+ poses,
173
+ poses_cam_to_world,
174
+ selected_images,
175
+ timestamps_selected,
176
+ )
177
+ )
178
+ assert selected_sky_direction_scene == sky_direction_scene
179
+
180
+ os.makedirs(os.path.join(out_scene_subdir, "vga_wide"), exist_ok=True)
181
+ os.makedirs(
182
+ os.path.join(out_scene_subdir, "lowres_depth"), exist_ok=True
183
+ )
184
+ assert isinstance(sky_direction_scene, str)
185
+ all_exist = True
186
+ for basename in images:
187
+ vga_wide_path = osp.join(rgb_dir, basename)
188
+ depth_path = osp.join(depth_dir, basename)
189
+ if not osp.isfile(vga_wide_path) or not osp.isfile(depth_path):
190
+ all_exist = False
191
+ break
192
+ if not all_exist:
193
+ continue
194
+
195
+ for basename in images:
196
+ img_out = os.path.join(
197
+ out_scene_subdir, "vga_wide", basename.replace(".png", ".jpg")
198
+ )
199
+ depth_out = os.path.join(out_scene_subdir, "lowres_depth", basename)
200
+ if osp.isfile(img_out) and osp.isfile(depth_out):
201
+ continue
202
+
203
+ vga_wide_path = osp.join(rgb_dir, basename)
204
+ depth_path = osp.join(depth_dir, basename)
205
+
206
+ img = Image.open(vga_wide_path)
207
+ depth = cv2.imread(depth_path, cv2.IMREAD_UNCHANGED)
208
+
209
+ # rotate the image
210
+ if sky_direction_scene == "RIGHT":
211
+ try:
212
+ img = img.transpose(Image.Transpose.ROTATE_90)
213
+ except Exception:
214
+ img = img.transpose(Image.ROTATE_90)
215
+ depth = cv2.rotate(depth, cv2.ROTATE_90_COUNTERCLOCKWISE)
216
+ elif sky_direction_scene == "LEFT":
217
+ try:
218
+ img = img.transpose(Image.Transpose.ROTATE_270)
219
+ except Exception:
220
+ img = img.transpose(Image.ROTATE_270)
221
+ depth = cv2.rotate(depth, cv2.ROTATE_90_CLOCKWISE)
222
+ elif sky_direction_scene == "DOWN":
223
+ try:
224
+ img = img.transpose(Image.Transpose.ROTATE_180)
225
+ except Exception:
226
+ img = img.transpose(Image.ROTATE_180)
227
+ depth = cv2.rotate(depth, cv2.ROTATE_180)
228
+
229
+ W, H = img.size
230
+ if not osp.isfile(img_out):
231
+ img.save(img_out)
232
+
233
+ depth = cv2.resize(
234
+ depth, (W, H), interpolation=cv2.INTER_NEAREST_EXACT
235
+ )
236
+ if not osp.isfile(
237
+ depth_out
238
+ ): # avoid destroying the base dataset when you mess up the paths
239
+ cv2.imwrite(depth_out, depth)
240
+
241
+ # save at the end
242
+ np.savez(
243
+ scene_metadata_path,
244
+ trajectories=trajectories,
245
+ intrinsics=intrinsics,
246
+ images=images,
247
+ pairs=pairs,
248
+ )
249
+
250
+ outlistfile = osp.join(outsubdir, "scene_list.json")
251
+ for scene_subdir in valid_scenes:
252
+ scene_metadata_path = osp.join(
253
+ outsubdir, scene_subdir, "scene_metadata.npz"
254
+ )
255
+ if not osp.isfile(scene_metadata_path):
256
+ valid_scenes.remove(scene_subdir)
257
+ with open(outlistfile, "w") as f:
258
+ json.dump(valid_scenes, f)
259
+
260
+ # STEP 5: concat all scene_metadata.npz into a single file
261
+ scene_data = {}
262
+ for scene_subdir in valid_scenes:
263
+ scene_metadata_path = osp.join(
264
+ outsubdir, scene_subdir, "scene_metadata.npz"
265
+ )
266
+ with np.load(scene_metadata_path) as data:
267
+ trajectories = data["trajectories"]
268
+ intrinsics = data["intrinsics"]
269
+ images = data["images"]
270
+ pairs = data["pairs"]
271
+ scene_data[scene_subdir] = {
272
+ "trajectories": trajectories,
273
+ "intrinsics": intrinsics,
274
+ "images": images,
275
+ "pairs": pairs,
276
+ }
277
+ offset = 0
278
+ counts = []
279
+ scenes = []
280
+ sceneids = []
281
+ images = []
282
+ intrinsics = []
283
+ trajectories = []
284
+ pairs = []
285
+ for scene_idx, (scene_subdir, data) in enumerate(scene_data.items()):
286
+ num_imgs = data["images"].shape[0]
287
+ img_pairs = data["pairs"]
288
+
289
+ scenes.append(scene_subdir)
290
+ sceneids.extend([scene_idx] * num_imgs)
291
+
292
+ images.append(data["images"])
293
+
294
+ K = np.expand_dims(np.eye(3), 0).repeat(num_imgs, 0)
295
+ K[:, 0, 0] = [fx for _, _, fx, _, _, _ in data["intrinsics"]]
296
+ K[:, 1, 1] = [fy for _, _, _, fy, _, _ in data["intrinsics"]]
297
+ K[:, 0, 2] = [hw for _, _, _, _, hw, _ in data["intrinsics"]]
298
+ K[:, 1, 2] = [hh for _, _, _, _, _, hh in data["intrinsics"]]
299
+
300
+ intrinsics.append(K)
301
+ trajectories.append(data["trajectories"])
302
+
303
+ # offset pairs
304
+ img_pairs[:, 0:2] += offset
305
+ pairs.append(img_pairs)
306
+ counts.append(offset)
307
+
308
+ offset += num_imgs
309
+
310
+ images = np.concatenate(images, axis=0)
311
+ intrinsics = np.concatenate(intrinsics, axis=0)
312
+ trajectories = np.concatenate(trajectories, axis=0)
313
+ pairs = np.concatenate(pairs, axis=0)
314
+ np.savez(
315
+ osp.join(outsubdir, "all_metadata.npz"),
316
+ counts=counts,
317
+ scenes=scenes,
318
+ sceneids=sceneids,
319
+ images=images,
320
+ intrinsics=intrinsics,
321
+ trajectories=trajectories,
322
+ pairs=pairs,
323
+ )
324
+
325
+
326
+ def convert_scene_metadata(
327
+ scene_subdir,
328
+ intrinsics_dir,
329
+ timestamps,
330
+ quaternions,
331
+ poses,
332
+ poses_cam_to_world,
333
+ selected_images,
334
+ timestamps_selected,
335
+ ):
336
+ # find scene orientation
337
+ sky_direction_scene, rotated_to_cam = find_scene_orientation(poses_cam_to_world)
338
+
339
+ # find/compute pose for selected timestamps
340
+ # most images have a valid timestamp / exact pose associated
341
+ timestamps_selected = np.array(timestamps_selected)
342
+ spline = interpolate.interp1d(timestamps, poses, kind="linear", axis=0)
343
+ interpolated_rotations = quaternion.squad(
344
+ quaternions, timestamps, timestamps_selected
345
+ )
346
+ interpolated_positions = spline(timestamps_selected)
347
+
348
+ trajectories = []
349
+ intrinsics = []
350
+ images = []
351
+ for i, (basename, frame_id) in enumerate(selected_images):
352
+ intrinsic_fn = osp.join(intrinsics_dir, f"{scene_subdir}_{frame_id}.pincam")
353
+ if not osp.exists(intrinsic_fn):
354
+ intrinsic_fn = osp.join(
355
+ intrinsics_dir, f"{scene_subdir}_{float(frame_id) - 0.001:.3f}.pincam"
356
+ )
357
+ if not osp.exists(intrinsic_fn):
358
+ intrinsic_fn = osp.join(
359
+ intrinsics_dir, f"{scene_subdir}_{float(frame_id) + 0.001:.3f}.pincam"
360
+ )
361
+ assert osp.exists(intrinsic_fn)
362
+ w, h, fx, fy, hw, hh = np.loadtxt(intrinsic_fn) # PINHOLE
363
+
364
+ pose = np.eye(4)
365
+ pose[:3, :3] = quaternion.as_rotation_matrix(interpolated_rotations[i])
366
+ pose[:3, 3] = interpolated_positions[i]
367
+
368
+ images.append(basename)
369
+ if sky_direction_scene == "RIGHT" or sky_direction_scene == "LEFT":
370
+ intrinsics.append([h, w, fy, fx, hh, hw]) # swapped intrinsics
371
+ else:
372
+ intrinsics.append([w, h, fx, fy, hw, hh])
373
+ trajectories.append(
374
+ pose @ rotated_to_cam
375
+ ) # pose_cam_to_world @ rotated_to_cam = rotated(cam) to world
376
+
377
+ return sky_direction_scene, trajectories, intrinsics, images
378
+
379
+
380
+ def find_scene_orientation(poses_cam_to_world):
381
+ if len(poses_cam_to_world) > 0:
382
+ up_vector = sum(get_up_vectors(p) for p in poses_cam_to_world) / len(
383
+ poses_cam_to_world
384
+ )
385
+ right_vector = sum(get_right_vectors(p) for p in poses_cam_to_world) / len(
386
+ poses_cam_to_world
387
+ )
388
+ up_world = np.array([[0.0], [0.0], [1.0], [0.0]])
389
+ else:
390
+ up_vector = np.array([[0.0], [-1.0], [0.0], [0.0]])
391
+ right_vector = np.array([[1.0], [0.0], [0.0], [0.0]])
392
+ up_world = np.array([[0.0], [0.0], [1.0], [0.0]])
393
+
394
+ # value between 0, 180
395
+ device_up_to_world_up_angle = (
396
+ np.arccos(np.clip(np.dot(np.transpose(up_world), up_vector), -1.0, 1.0)).item()
397
+ * 180.0
398
+ / np.pi
399
+ )
400
+ device_right_to_world_up_angle = (
401
+ np.arccos(
402
+ np.clip(np.dot(np.transpose(up_world), right_vector), -1.0, 1.0)
403
+ ).item()
404
+ * 180.0
405
+ / np.pi
406
+ )
407
+
408
+ up_closest_to_90 = abs(device_up_to_world_up_angle - 90.0) < abs(
409
+ device_right_to_world_up_angle - 90.0
410
+ )
411
+ if up_closest_to_90:
412
+ assert abs(device_up_to_world_up_angle - 90.0) < 45.0
413
+ # LEFT
414
+ if device_right_to_world_up_angle > 90.0:
415
+ sky_direction_scene = "LEFT"
416
+ cam_to_rotated_q = quaternion.from_rotation_vector(
417
+ [0.0, 0.0, math.pi / 2.0]
418
+ )
419
+ else:
420
+ # note that in metadata.csv RIGHT does not exist, but again it's not accurate...
421
+ # well, turns out there are scenes oriented like this
422
+ # for example Training/41124801
423
+ sky_direction_scene = "RIGHT"
424
+ cam_to_rotated_q = quaternion.from_rotation_vector(
425
+ [0.0, 0.0, -math.pi / 2.0]
426
+ )
427
+ else:
428
+ # right is close to 90
429
+ assert abs(device_right_to_world_up_angle - 90.0) < 45.0
430
+ if device_up_to_world_up_angle > 90.0:
431
+ sky_direction_scene = "DOWN"
432
+ cam_to_rotated_q = quaternion.from_rotation_vector([0.0, 0.0, math.pi])
433
+ else:
434
+ sky_direction_scene = "UP"
435
+ cam_to_rotated_q = quaternion.quaternion(1, 0, 0, 0)
436
+ cam_to_rotated = np.eye(4)
437
+ cam_to_rotated[:3, :3] = quaternion.as_rotation_matrix(cam_to_rotated_q)
438
+ rotated_to_cam = np.linalg.inv(cam_to_rotated)
439
+ return sky_direction_scene, rotated_to_cam
440
+
441
+
442
+ if __name__ == "__main__":
443
+ parser = get_parser()
444
+ args = parser.parse_args()
445
+ main(args.arkitscenes_dir, args.precomputed_pairs, args.output_dir)
3d-belief/third_party/CUT3R/datasets_preprocess/preprocess_arkitscenes_highres.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import os.path as osp
4
+ import decimal
5
+ import argparse
6
+ import math
7
+ from bisect import bisect_left
8
+ from PIL import Image
9
+ import numpy as np
10
+ import quaternion
11
+ from scipy import interpolate
12
+ import cv2
13
+ from tqdm import tqdm
14
+ from multiprocessing import Pool
15
+
16
+
17
+ def get_parser():
18
+ parser = argparse.ArgumentParser()
19
+ parser.add_argument(
20
+ "--arkitscenes_dir",
21
+ default="",
22
+ )
23
+ parser.add_argument(
24
+ "--output_dir",
25
+ default="data/dust3r_data/processed_arkitscenes_highres",
26
+ )
27
+ return parser
28
+
29
+
30
+ def value_to_decimal(value, decimal_places):
31
+ decimal.getcontext().rounding = decimal.ROUND_HALF_UP # define rounding method
32
+ return decimal.Decimal(str(float(value))).quantize(
33
+ decimal.Decimal("1e-{}".format(decimal_places))
34
+ )
35
+
36
+
37
+ def closest(value, sorted_list):
38
+ index = bisect_left(sorted_list, value)
39
+ if index == 0:
40
+ return sorted_list[0]
41
+ elif index == len(sorted_list):
42
+ return sorted_list[-1]
43
+ else:
44
+ value_before = sorted_list[index - 1]
45
+ value_after = sorted_list[index]
46
+ if value_after - value < value - value_before:
47
+ return value_after
48
+ else:
49
+ return value_before
50
+
51
+
52
+ def get_up_vectors(pose_device_to_world):
53
+ return np.matmul(pose_device_to_world, np.array([[0.0], [-1.0], [0.0], [0.0]]))
54
+
55
+
56
+ def get_right_vectors(pose_device_to_world):
57
+ return np.matmul(pose_device_to_world, np.array([[1.0], [0.0], [0.0], [0.0]]))
58
+
59
+
60
+ def read_traj(traj_path):
61
+ quaternions = []
62
+ poses = []
63
+ timestamps = []
64
+ poses_p_to_w = []
65
+ with open(traj_path) as f:
66
+ traj_lines = f.readlines()
67
+ for line in traj_lines:
68
+ tokens = line.split()
69
+ assert len(tokens) == 7
70
+ traj_timestamp = float(tokens[0])
71
+
72
+ timestamps_decimal_value = value_to_decimal(traj_timestamp, 3)
73
+ timestamps.append(
74
+ float(timestamps_decimal_value)
75
+ ) # for spline interpolation
76
+
77
+ angle_axis = [float(tokens[1]), float(tokens[2]), float(tokens[3])]
78
+ r_w_to_p, _ = cv2.Rodrigues(np.asarray(angle_axis))
79
+ t_w_to_p = np.asarray(
80
+ [float(tokens[4]), float(tokens[5]), float(tokens[6])]
81
+ )
82
+
83
+ pose_w_to_p = np.eye(4)
84
+ pose_w_to_p[:3, :3] = r_w_to_p
85
+ pose_w_to_p[:3, 3] = t_w_to_p
86
+
87
+ pose_p_to_w = np.linalg.inv(pose_w_to_p)
88
+
89
+ r_p_to_w_as_quat = quaternion.from_rotation_matrix(pose_p_to_w[:3, :3])
90
+ t_p_to_w = pose_p_to_w[:3, 3]
91
+ poses_p_to_w.append(pose_p_to_w)
92
+ poses.append(t_p_to_w)
93
+ quaternions.append(r_p_to_w_as_quat)
94
+ return timestamps, poses, quaternions, poses_p_to_w
95
+
96
+
97
+ def main(rootdir, outdir):
98
+ os.makedirs(outdir, exist_ok=True)
99
+ subdirs = ["Validation", "Training"]
100
+ for subdir in subdirs:
101
+ outsubdir = osp.join(outdir, subdir)
102
+ scene_dirs = sorted(
103
+ [
104
+ d
105
+ for d in os.listdir(osp.join(rootdir, subdir))
106
+ if osp.isdir(osp.join(rootdir, subdir, d))
107
+ ]
108
+ )
109
+
110
+ with Pool() as pool:
111
+ results = list(
112
+ tqdm(
113
+ pool.imap(
114
+ process_scene,
115
+ [
116
+ (rootdir, outdir, subdir, scene_subdir)
117
+ for scene_subdir in scene_dirs
118
+ ],
119
+ ),
120
+ total=len(scene_dirs),
121
+ )
122
+ )
123
+
124
+ # Filter None results and other post-processing
125
+ valid_scenes = [result for result in results if result is not None]
126
+ outlistfile = osp.join(outsubdir, "scene_list.json")
127
+ with open(outlistfile, "w") as f:
128
+ json.dump(valid_scenes, f)
129
+
130
+
131
+ def process_scene(args):
132
+ rootdir, outdir, subdir, scene_subdir = args
133
+ # Unpack paths
134
+ scene_dir = osp.join(rootdir, subdir, scene_subdir)
135
+ outsubdir = osp.join(outdir, subdir)
136
+ out_scene_subdir = osp.join(outsubdir, scene_subdir)
137
+
138
+ # Validation if necessary resources exist
139
+ if (
140
+ not osp.exists(osp.join(scene_dir, "highres_depth"))
141
+ or not osp.exists(osp.join(scene_dir, "vga_wide"))
142
+ or not osp.exists(osp.join(scene_dir, "vga_wide_intrinsics"))
143
+ or not osp.exists(osp.join(scene_dir, "lowres_wide.traj"))
144
+ ):
145
+ return None
146
+
147
+ depth_dir = osp.join(scene_dir, "highres_depth")
148
+ rgb_dir = osp.join(scene_dir, "vga_wide")
149
+ intrinsics_dir = osp.join(scene_dir, "vga_wide_intrinsics")
150
+ traj_path = osp.join(scene_dir, "lowres_wide.traj")
151
+
152
+ depth_files = sorted(os.listdir(depth_dir))
153
+ img_files = sorted(os.listdir(rgb_dir))
154
+
155
+ out_scene_subdir = osp.join(outsubdir, scene_subdir)
156
+
157
+ # STEP 3: parse the scene and export the list of valid (K, pose, rgb, depth) and convert images
158
+ scene_metadata_path = osp.join(out_scene_subdir, "scene_metadata.npz")
159
+ if osp.isfile(scene_metadata_path):
160
+ print(f"Skipping {scene_subdir}")
161
+ else:
162
+ print(f"parsing {scene_subdir}")
163
+ # loads traj
164
+ timestamps, poses, quaternions, poses_cam_to_world = read_traj(traj_path)
165
+
166
+ poses = np.array(poses)
167
+ quaternions = np.array(quaternions, dtype=np.quaternion)
168
+ quaternions = quaternion.unflip_rotors(quaternions)
169
+ timestamps = np.array(timestamps)
170
+
171
+ all_depths = sorted(
172
+ [
173
+ (basename, basename.split(".png")[0].split("_")[1])
174
+ for basename in depth_files
175
+ ],
176
+ key=lambda x: float(x[1]),
177
+ )
178
+
179
+ selected_depths = []
180
+ timestamps_selected = []
181
+ timestamp_min = timestamps.min()
182
+ timestamp_max = timestamps.max()
183
+ for basename, frame_id in all_depths:
184
+ frame_id = float(frame_id)
185
+ if frame_id < timestamp_min or frame_id > timestamp_max:
186
+ continue
187
+ selected_depths.append((basename, frame_id))
188
+ timestamps_selected.append(frame_id)
189
+
190
+ sky_direction_scene, trajectories, intrinsics, images, depths = (
191
+ convert_scene_metadata(
192
+ scene_subdir,
193
+ intrinsics_dir,
194
+ timestamps,
195
+ quaternions,
196
+ poses,
197
+ poses_cam_to_world,
198
+ img_files,
199
+ selected_depths,
200
+ timestamps_selected,
201
+ )
202
+ )
203
+
204
+ if len(images) == 0:
205
+ print(f"Skipping {scene_subdir}")
206
+ return None
207
+
208
+ os.makedirs(out_scene_subdir, exist_ok=True)
209
+
210
+ os.makedirs(os.path.join(out_scene_subdir, "vga_wide"), exist_ok=True)
211
+ os.makedirs(os.path.join(out_scene_subdir, "highres_depth"), exist_ok=True)
212
+ assert isinstance(sky_direction_scene, str)
213
+
214
+ for image_path, depth_path in zip(images, depths):
215
+ img_out = os.path.join(
216
+ out_scene_subdir, "vga_wide", image_path.replace(".png", ".jpg")
217
+ )
218
+ depth_out = os.path.join(out_scene_subdir, "highres_depth", depth_path)
219
+ if osp.isfile(img_out) and osp.isfile(depth_out):
220
+ continue
221
+
222
+ vga_wide_path = osp.join(rgb_dir, image_path)
223
+ depth_path = osp.join(depth_dir, depth_path)
224
+
225
+ if not osp.isfile(vga_wide_path) or not osp.isfile(depth_path):
226
+ continue
227
+
228
+ img = Image.open(vga_wide_path)
229
+ depth = cv2.imread(depth_path, cv2.IMREAD_UNCHANGED)
230
+
231
+ # rotate the image
232
+ if sky_direction_scene == "RIGHT":
233
+ try:
234
+ img = img.transpose(Image.Transpose.ROTATE_90)
235
+ except Exception:
236
+ img = img.transpose(Image.ROTATE_90)
237
+ depth = cv2.rotate(depth, cv2.ROTATE_90_COUNTERCLOCKWISE)
238
+
239
+ elif sky_direction_scene == "LEFT":
240
+ try:
241
+ img = img.transpose(Image.Transpose.ROTATE_270)
242
+ except Exception:
243
+ img = img.transpose(Image.ROTATE_270)
244
+ depth = cv2.rotate(depth, cv2.ROTATE_90_CLOCKWISE)
245
+
246
+ elif sky_direction_scene == "DOWN":
247
+ try:
248
+ img = img.transpose(Image.Transpose.ROTATE_180)
249
+ except Exception:
250
+ img = img.transpose(Image.ROTATE_180)
251
+ depth = cv2.rotate(depth, cv2.ROTATE_180)
252
+
253
+ W, H = img.size
254
+ if not osp.isfile(img_out):
255
+ img.save(img_out)
256
+
257
+ depth = cv2.resize(depth, (W, H), interpolation=cv2.INTER_NEAREST)
258
+ if not osp.isfile(
259
+ depth_out
260
+ ): # avoid destroying the base dataset when you mess up the paths
261
+ cv2.imwrite(depth_out, depth)
262
+
263
+ # save at the end
264
+ np.savez(
265
+ scene_metadata_path,
266
+ trajectories=trajectories,
267
+ intrinsics=intrinsics,
268
+ images=images,
269
+ )
270
+
271
+
272
+ def convert_scene_metadata(
273
+ scene_subdir,
274
+ intrinsics_dir,
275
+ timestamps,
276
+ quaternions,
277
+ poses,
278
+ poses_cam_to_world,
279
+ all_images,
280
+ selected_depths,
281
+ timestamps_selected,
282
+ ):
283
+ # find scene orientation
284
+ sky_direction_scene, rotated_to_cam = find_scene_orientation(poses_cam_to_world)
285
+
286
+ # find/compute pose for selected timestamps
287
+ # most images have a valid timestamp / exact pose associated
288
+ timestamps_selected = np.array(timestamps_selected)
289
+ spline = interpolate.interp1d(timestamps, poses, kind="linear", axis=0)
290
+ interpolated_rotations = quaternion.squad(
291
+ quaternions, timestamps, timestamps_selected
292
+ )
293
+ interpolated_positions = spline(timestamps_selected)
294
+
295
+ trajectories = []
296
+ intrinsics = []
297
+ images = []
298
+ depths = []
299
+ for i, (basename, frame_id) in enumerate(selected_depths):
300
+ intrinsic_fn = osp.join(intrinsics_dir, f"{scene_subdir}_{frame_id}.pincam")
301
+ search_interval = int(0.1 / 0.001)
302
+ for timestamp in range(-search_interval, search_interval + 1):
303
+ if osp.exists(intrinsic_fn):
304
+ break
305
+ intrinsic_fn = osp.join(
306
+ intrinsics_dir,
307
+ f"{scene_subdir}_{float(frame_id) + timestamp * 0.001:.3f}.pincam",
308
+ )
309
+ if not osp.exists(intrinsic_fn):
310
+ print(f"Skipping {intrinsic_fn}")
311
+ continue
312
+
313
+ image_path = "{}_{}.png".format(scene_subdir, frame_id)
314
+ search_interval = int(0.001 / 0.001)
315
+ for timestamp in range(-search_interval, search_interval + 1):
316
+ if image_path in all_images:
317
+ break
318
+ image_path = "{}_{}.png".format(
319
+ scene_subdir, float(frame_id) + timestamp * 0.001
320
+ )
321
+ if image_path not in all_images:
322
+ print(f"Skipping {scene_subdir} {frame_id}")
323
+ continue
324
+
325
+ w, h, fx, fy, hw, hh = np.loadtxt(intrinsic_fn) # PINHOLE
326
+
327
+ pose = np.eye(4)
328
+ pose[:3, :3] = quaternion.as_rotation_matrix(interpolated_rotations[i])
329
+ pose[:3, 3] = interpolated_positions[i]
330
+
331
+ images.append(basename)
332
+ depths.append(basename)
333
+ if sky_direction_scene == "RIGHT" or sky_direction_scene == "LEFT":
334
+ intrinsics.append([h, w, fy, fx, hh, hw]) # swapped intrinsics
335
+ else:
336
+ intrinsics.append([w, h, fx, fy, hw, hh])
337
+ trajectories.append(
338
+ pose @ rotated_to_cam
339
+ ) # pose_cam_to_world @ rotated_to_cam = rotated(cam) to world
340
+
341
+ return sky_direction_scene, trajectories, intrinsics, images, depths
342
+
343
+
344
+ def find_scene_orientation(poses_cam_to_world):
345
+ if len(poses_cam_to_world) > 0:
346
+ up_vector = sum(get_up_vectors(p) for p in poses_cam_to_world) / len(
347
+ poses_cam_to_world
348
+ )
349
+ right_vector = sum(get_right_vectors(p) for p in poses_cam_to_world) / len(
350
+ poses_cam_to_world
351
+ )
352
+ up_world = np.array([[0.0], [0.0], [1.0], [0.0]])
353
+ else:
354
+ up_vector = np.array([[0.0], [-1.0], [0.0], [0.0]])
355
+ right_vector = np.array([[1.0], [0.0], [0.0], [0.0]])
356
+ up_world = np.array([[0.0], [0.0], [1.0], [0.0]])
357
+
358
+ # value between 0, 180
359
+ device_up_to_world_up_angle = (
360
+ np.arccos(np.clip(np.dot(np.transpose(up_world), up_vector), -1.0, 1.0)).item()
361
+ * 180.0
362
+ / np.pi
363
+ )
364
+ device_right_to_world_up_angle = (
365
+ np.arccos(
366
+ np.clip(np.dot(np.transpose(up_world), right_vector), -1.0, 1.0)
367
+ ).item()
368
+ * 180.0
369
+ / np.pi
370
+ )
371
+
372
+ up_closest_to_90 = abs(device_up_to_world_up_angle - 90.0) < abs(
373
+ device_right_to_world_up_angle - 90.0
374
+ )
375
+ if up_closest_to_90:
376
+ assert abs(device_up_to_world_up_angle - 90.0) < 45.0
377
+ # LEFT
378
+ if device_right_to_world_up_angle > 90.0:
379
+ sky_direction_scene = "LEFT"
380
+ cam_to_rotated_q = quaternion.from_rotation_vector(
381
+ [0.0, 0.0, math.pi / 2.0]
382
+ )
383
+ else:
384
+ # note that in metadata.csv RIGHT does not exist, but again it's not accurate...
385
+ # well, turns out there are scenes oriented like this
386
+ # for example Training/41124801
387
+ sky_direction_scene = "RIGHT"
388
+ cam_to_rotated_q = quaternion.from_rotation_vector(
389
+ [0.0, 0.0, -math.pi / 2.0]
390
+ )
391
+ else:
392
+ # right is close to 90
393
+ assert abs(device_right_to_world_up_angle - 90.0) < 45.0
394
+ if device_up_to_world_up_angle > 90.0:
395
+ sky_direction_scene = "DOWN"
396
+ cam_to_rotated_q = quaternion.from_rotation_vector([0.0, 0.0, math.pi])
397
+ else:
398
+ sky_direction_scene = "UP"
399
+ cam_to_rotated_q = quaternion.quaternion(1, 0, 0, 0)
400
+ cam_to_rotated = np.eye(4)
401
+ cam_to_rotated[:3, :3] = quaternion.as_rotation_matrix(cam_to_rotated_q)
402
+ rotated_to_cam = np.linalg.inv(cam_to_rotated)
403
+ return sky_direction_scene, rotated_to_cam
404
+
405
+
406
+ if __name__ == "__main__":
407
+ parser = get_parser()
408
+ args = parser.parse_args()
409
+ main(args.arkitscenes_dir, args.output_dir)
3d-belief/third_party/CUT3R/src/dust3r/datasets/__pycache__/arkitscenes.cpython-310.pyc ADDED
Binary file (6.69 kB). View file
 
3d-belief/third_party/CUT3R/src/dust3r/datasets/__pycache__/arkitscenes.cpython-311.pyc ADDED
Binary file (14.2 kB). View file
 
3d-belief/third_party/CUT3R/src/dust3r/datasets/__pycache__/arkitscenes_highres.cpython-310.pyc ADDED
Binary file (5.83 kB). View file
 
3d-belief/third_party/CUT3R/src/dust3r/datasets/__pycache__/arkitscenes_highres.cpython-311.pyc ADDED
Binary file (11.7 kB). View file
 
3d-belief/third_party/CUT3R/src/dust3r/datasets/arkitscenes.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os.path as osp
2
+ import os
3
+ import sys
4
+ import itertools
5
+
6
+ sys.path.append(osp.join(osp.dirname(__file__), "..", ".."))
7
+ import cv2
8
+ import numpy as np
9
+
10
+ from dust3r.datasets.base.base_multiview_dataset import BaseMultiViewDataset
11
+ from dust3r.utils.image import imread_cv2
12
+
13
+
14
+ def stratified_sampling(indices, num_samples, rng=None):
15
+ if num_samples > len(indices):
16
+ raise ValueError("num_samples cannot exceed the number of available indices.")
17
+ elif num_samples == len(indices):
18
+ return indices
19
+
20
+ sorted_indices = sorted(indices)
21
+ stride = len(sorted_indices) / num_samples
22
+ sampled_indices = []
23
+ if rng is None:
24
+ rng = np.random.default_rng()
25
+
26
+ for i in range(num_samples):
27
+ start = int(i * stride)
28
+ end = int((i + 1) * stride)
29
+ # Ensure end does not exceed the list
30
+ end = min(end, len(sorted_indices))
31
+ if start < end:
32
+ # Randomly select within the current stratum
33
+ rand_idx = rng.integers(start, end)
34
+ sampled_indices.append(sorted_indices[rand_idx])
35
+ else:
36
+ # In case of any rounding issues, select the last index
37
+ sampled_indices.append(sorted_indices[-1])
38
+
39
+ return rng.permutation(sampled_indices)
40
+
41
+
42
+ class ARKitScenes_Multi(BaseMultiViewDataset):
43
+ def __init__(self, *args, split, ROOT, **kwargs):
44
+ self.ROOT = ROOT
45
+ self.video = True
46
+ self.is_metric = True
47
+ self.max_interval = 8
48
+ super().__init__(*args, **kwargs)
49
+ if split == "train":
50
+ self.split = "Training"
51
+ elif split == "test":
52
+ self.split = "Test"
53
+ else:
54
+ raise ValueError("")
55
+
56
+ self.loaded_data = self._load_data(self.split)
57
+
58
+ def _load_data(self, split):
59
+ with np.load(osp.join(self.ROOT, split, "all_metadata.npz")) as data:
60
+ self.scenes: np.ndarray = data["scenes"]
61
+ high_res_list = np.array(
62
+ [
63
+ d
64
+ for d in os.listdir(
65
+ os.path.join(
66
+ self.ROOT.rstrip("/") + "_highres",
67
+ split if split == "Training" else "Validation",
68
+ )
69
+ )
70
+ if os.path.join(self.ROOT + "_highres", split, d)
71
+ ]
72
+ )
73
+ self.scenes = np.setdiff1d(self.scenes, high_res_list)
74
+ offset = 0
75
+ counts = []
76
+ scenes = []
77
+ sceneids = []
78
+ images = []
79
+ intrinsics = []
80
+ trajectories = []
81
+ groups = []
82
+ id_ranges = []
83
+ j = 0
84
+ for scene_idx, scene in enumerate(self.scenes):
85
+ scene_dir = osp.join(self.ROOT, self.split, scene)
86
+ with np.load(
87
+ osp.join(scene_dir, "new_scene_metadata.npz"), allow_pickle=True
88
+ ) as data:
89
+ imgs = data["images"]
90
+ intrins = data["intrinsics"]
91
+ traj = data["trajectories"]
92
+ min_seq_len = (
93
+ self.num_views
94
+ if not self.allow_repeat
95
+ else max(self.num_views // 3, 3)
96
+ )
97
+ if len(imgs) < min_seq_len:
98
+ print(f"Skipping {scene}")
99
+ continue
100
+
101
+ collections = {}
102
+ assert "image_collection" in data, "Image collection not found"
103
+ collections["image"] = data["image_collection"]
104
+
105
+ num_imgs = imgs.shape[0]
106
+ img_groups = []
107
+ min_group_len = (
108
+ self.num_views
109
+ if not self.allow_repeat
110
+ else max(self.num_views // 3, 3)
111
+ )
112
+ for ref_id, group in collections["image"].item().items():
113
+ if len(group) + 1 < min_group_len:
114
+ continue
115
+
116
+ # groups are (idx, score)s
117
+ group.insert(0, (ref_id, 1.0))
118
+ group = [int(x[0] + offset) for x in group]
119
+ img_groups.append(sorted(group))
120
+
121
+ if len(img_groups) == 0:
122
+ print(f"Skipping {scene}")
123
+ continue
124
+
125
+ scenes.append(scene)
126
+ sceneids.extend([j] * num_imgs)
127
+ id_ranges.extend([(offset, offset + num_imgs) for _ in range(num_imgs)])
128
+ images.extend(imgs)
129
+ K = np.expand_dims(np.eye(3), 0).repeat(num_imgs, 0)
130
+
131
+ K[:, 0, 0] = [fx for _, _, fx, _, _, _ in intrins]
132
+ K[:, 1, 1] = [fy for _, _, _, fy, _, _ in intrins]
133
+ K[:, 0, 2] = [cx for _, _, _, _, cx, _ in intrins]
134
+ K[:, 1, 2] = [cy for _, _, _, _, _, cy in intrins]
135
+ intrinsics.extend(list(K))
136
+ trajectories.extend(list(traj))
137
+
138
+ # offset groups
139
+ groups.extend(img_groups)
140
+ counts.append(offset)
141
+ offset += num_imgs
142
+ j += 1
143
+
144
+ self.scenes = scenes
145
+ self.sceneids = sceneids
146
+ self.id_ranges = id_ranges
147
+ self.images = images
148
+ self.intrinsics = intrinsics
149
+ self.trajectories = trajectories
150
+ self.groups = groups
151
+
152
+ def __len__(self):
153
+ return len(self.groups)
154
+
155
+ def get_image_num(self):
156
+ return len(self.images)
157
+
158
+ def _get_views(self, idx, resolution, rng, num_views):
159
+
160
+ if rng.choice([True, False]):
161
+ image_idxs = np.arange(self.id_ranges[idx][0], self.id_ranges[idx][1])
162
+ cut_off = num_views if not self.allow_repeat else max(num_views // 3, 3)
163
+ start_image_idxs = image_idxs[: len(image_idxs) - cut_off + 1]
164
+ start_id = rng.choice(start_image_idxs)
165
+ pos, ordered_video = self.get_seq_from_start_id(
166
+ num_views,
167
+ start_id,
168
+ image_idxs.tolist(),
169
+ rng,
170
+ max_interval=self.max_interval,
171
+ video_prob=0.8,
172
+ fix_interval_prob=0.5,
173
+ block_shuffle=16,
174
+ )
175
+ image_idxs = np.array(image_idxs)[pos]
176
+ else:
177
+ ordered_video = False
178
+ image_idxs = self.groups[idx]
179
+ image_idxs = rng.permutation(image_idxs)
180
+ if len(image_idxs) > num_views:
181
+ image_idxs = image_idxs[:num_views]
182
+ else:
183
+ if rng.random() < 0.8:
184
+ image_idxs = rng.choice(image_idxs, size=num_views, replace=True)
185
+ else:
186
+ repeat_num = num_views // len(image_idxs) + 1
187
+ image_idxs = np.tile(image_idxs, repeat_num)[:num_views]
188
+
189
+ views = []
190
+ for v, view_idx in enumerate(image_idxs):
191
+ scene_id = self.sceneids[view_idx]
192
+ scene_dir = osp.join(self.ROOT, self.split, self.scenes[scene_id])
193
+
194
+ intrinsics = self.intrinsics[view_idx]
195
+ camera_pose = self.trajectories[view_idx]
196
+ basename = self.images[view_idx]
197
+ assert (
198
+ basename[:8] == self.scenes[scene_id]
199
+ ), f"{basename}, {self.scenes[scene_id]}"
200
+ # print(scene_dir, basename)
201
+ # Load RGB image
202
+ rgb_image = imread_cv2(
203
+ osp.join(scene_dir, "vga_wide", basename.replace(".png", ".jpg"))
204
+ )
205
+ # Load depthmap
206
+ depthmap = imread_cv2(
207
+ osp.join(scene_dir, "lowres_depth", basename), cv2.IMREAD_UNCHANGED
208
+ )
209
+ depthmap = depthmap.astype(np.float32) / 1000.0
210
+ depthmap[~np.isfinite(depthmap)] = 0 # invalid
211
+
212
+ rgb_image, depthmap, intrinsics = self._crop_resize_if_necessary(
213
+ rgb_image, depthmap, intrinsics, resolution, rng=rng, info=view_idx
214
+ )
215
+
216
+ # generate img mask and raymap mask
217
+ img_mask, ray_mask = self.get_img_and_ray_masks(
218
+ self.is_metric, v, rng, p=[0.75, 0.2, 0.05]
219
+ )
220
+
221
+ views.append(
222
+ dict(
223
+ img=rgb_image,
224
+ depthmap=depthmap.astype(np.float32),
225
+ camera_pose=camera_pose.astype(np.float32),
226
+ camera_intrinsics=intrinsics.astype(np.float32),
227
+ dataset="arkitscenes",
228
+ label=self.scenes[scene_id] + "_" + basename,
229
+ instance=f"{str(idx)}_{str(view_idx)}",
230
+ is_metric=self.is_metric,
231
+ is_video=ordered_video,
232
+ quantile=np.array(0.98, dtype=np.float32),
233
+ img_mask=img_mask,
234
+ ray_mask=ray_mask,
235
+ camera_only=False,
236
+ depth_only=False,
237
+ single_view=False,
238
+ reset=False,
239
+ )
240
+ )
241
+ assert len(views) == num_views
242
+ return views
3d-belief/third_party/CUT3R/src/dust3r/datasets/arkitscenes_highres.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os.path as osp
2
+ import os
3
+ import sys
4
+ import itertools
5
+
6
+ sys.path.append(osp.join(osp.dirname(__file__), "..", ".."))
7
+ import cv2
8
+ import numpy as np
9
+ import h5py
10
+ import math
11
+ from dust3r.datasets.base.base_multiview_dataset import BaseMultiViewDataset
12
+ from dust3r.utils.image import imread_cv2
13
+
14
+
15
+ class ARKitScenesHighRes_Multi(BaseMultiViewDataset):
16
+ def __init__(self, *args, split, ROOT, **kwargs):
17
+ self.ROOT = ROOT
18
+ self.video = True
19
+ self.max_interval = 8
20
+ self.is_metric = True
21
+ super().__init__(*args, **kwargs)
22
+ if split == "train":
23
+ self.split = "Training"
24
+ elif split == "test":
25
+ self.split = "Validation"
26
+ else:
27
+ raise ValueError("")
28
+
29
+ self.loaded_data = self._load_data(self.split)
30
+
31
+ def _load_data(self, split):
32
+ all_scenes = sorted(
33
+ [
34
+ d
35
+ for d in os.listdir(osp.join(self.ROOT, split))
36
+ if osp.isdir(osp.join(self.ROOT, split, d))
37
+ ]
38
+ )
39
+ offset = 0
40
+ scenes = []
41
+ sceneids = []
42
+ images = []
43
+ start_img_ids = []
44
+ scene_img_list = []
45
+ timestamps = []
46
+ intrinsics = []
47
+ trajectories = []
48
+ scene_id = 0
49
+ for scene in all_scenes:
50
+ scene_dir = osp.join(self.ROOT, self.split, scene)
51
+ with np.load(osp.join(scene_dir, "scene_metadata.npz")) as data:
52
+ imgs_with_indices = sorted(
53
+ enumerate(data["images"]), key=lambda x: x[1]
54
+ )
55
+ imgs = [x[1] for x in imgs_with_indices]
56
+ cut_off = (
57
+ self.num_views
58
+ if not self.allow_repeat
59
+ else max(self.num_views // 3, 3)
60
+ )
61
+ if len(imgs) < cut_off:
62
+ print(f"Skipping {scene}")
63
+ continue
64
+ indices = [x[0] for x in imgs_with_indices]
65
+ tsps = np.array(
66
+ [float(img_name.split("_")[1][:-4]) for img_name in imgs]
67
+ )
68
+ assert [img[:8] == scene for img in imgs], f"{scene}, {imgs}"
69
+ num_imgs = data["images"].shape[0]
70
+ img_ids = list(np.arange(num_imgs) + offset)
71
+ start_img_ids_ = img_ids[: num_imgs - cut_off + 1]
72
+
73
+ scenes.append(scene)
74
+ scene_img_list.append(img_ids)
75
+ sceneids.extend([scene_id] * num_imgs)
76
+ images.extend(imgs)
77
+ start_img_ids.extend(start_img_ids_)
78
+ timestamps.extend(tsps)
79
+
80
+ K = np.expand_dims(np.eye(3), 0).repeat(num_imgs, 0)
81
+ intrins = data["intrinsics"][indices]
82
+ K[:, 0, 0] = [fx for _, _, fx, _, _, _ in intrins]
83
+ K[:, 1, 1] = [fy for _, _, _, fy, _, _ in intrins]
84
+ K[:, 0, 2] = [cx for _, _, _, _, cx, _ in intrins]
85
+ K[:, 1, 2] = [cy for _, _, _, _, _, cy in intrins]
86
+ intrinsics.extend(list(K))
87
+ trajectories.extend(list(data["trajectories"][indices]))
88
+
89
+ # offset groups
90
+ offset += num_imgs
91
+ scene_id += 1
92
+
93
+ self.scenes = scenes
94
+ self.sceneids = sceneids
95
+ self.images = images
96
+ self.scene_img_list = scene_img_list
97
+ self.intrinsics = intrinsics
98
+ self.trajectories = trajectories
99
+ self.start_img_ids = start_img_ids
100
+ assert len(self.images) == len(self.intrinsics) == len(self.trajectories)
101
+
102
+ def __len__(self):
103
+ return len(self.start_img_ids)
104
+
105
+ def get_image_num(self):
106
+ return len(self.images)
107
+
108
+ def _get_views(self, idx, resolution, rng, num_views):
109
+ start_id = self.start_img_ids[idx]
110
+ all_image_ids = self.scene_img_list[self.sceneids[start_id]]
111
+ pos, ordered_video = self.get_seq_from_start_id(
112
+ num_views,
113
+ start_id,
114
+ all_image_ids,
115
+ rng,
116
+ max_interval=self.max_interval,
117
+ block_shuffle=16,
118
+ )
119
+ image_idxs = np.array(all_image_ids)[pos]
120
+
121
+ views = []
122
+
123
+ for v, view_idx in enumerate(image_idxs):
124
+ scene_id = self.sceneids[view_idx]
125
+ scene_dir = osp.join(self.ROOT, self.split, self.scenes[scene_id])
126
+
127
+ intrinsics = self.intrinsics[view_idx]
128
+ camera_pose = self.trajectories[view_idx]
129
+ basename = self.images[view_idx]
130
+ assert (
131
+ basename[:8] == self.scenes[scene_id]
132
+ ), f"{basename}, {self.scenes[scene_id]}"
133
+ # print(scene_dir, basename)
134
+ # Load RGB image
135
+ rgb_image = imread_cv2(
136
+ osp.join(scene_dir, "vga_wide", basename.replace(".png", ".jpg"))
137
+ )
138
+ # Load depthmap
139
+ depthmap = imread_cv2(
140
+ osp.join(scene_dir, "highres_depth", basename), cv2.IMREAD_UNCHANGED
141
+ )
142
+ depthmap = depthmap.astype(np.float32) / 1000.0
143
+ depthmap[~np.isfinite(depthmap)] = 0 # invalid
144
+
145
+ rgb_image, depthmap, intrinsics = self._crop_resize_if_necessary(
146
+ rgb_image, depthmap, intrinsics, resolution, rng=rng, info=view_idx
147
+ )
148
+
149
+ # generate img mask and raymap mask
150
+ img_mask, ray_mask = self.get_img_and_ray_masks(
151
+ self.is_metric, v, rng, p=[0.7, 0.25, 0.05]
152
+ )
153
+
154
+ views.append(
155
+ dict(
156
+ img=rgb_image,
157
+ depthmap=depthmap.astype(np.float32),
158
+ camera_pose=camera_pose.astype(np.float32),
159
+ camera_intrinsics=intrinsics.astype(np.float32),
160
+ dataset="arkitscenes_highres",
161
+ label=self.scenes[scene_id] + "_" + basename,
162
+ instance=f"{str(idx)}_{str(view_idx)}",
163
+ is_metric=self.is_metric,
164
+ is_video=ordered_video,
165
+ quantile=np.array(0.99, dtype=np.float32),
166
+ img_mask=img_mask,
167
+ ray_mask=ray_mask,
168
+ camera_only=False,
169
+ depth_only=False,
170
+ single_view=False,
171
+ reset=False,
172
+ )
173
+ )
174
+ assert len(views) == num_views
175
+ return views