3d-belief-dev / 3d-belief /scripts /data_prep /verify_arkitscenes_pose_convention.py
SCAI-JHU's picture
Add files using upload-large-folder tool
62a5484 verified
Raw
History Blame Contribute Delete
9.18 kB
"""
Verify the camera-pose convention + adapter schema for preprocessed ARKitScenes.
ARKitScenes is the single most important convention to get right here, because
ARKit raw poses are OpenGL-ish (x right, y up, z BACK) and CUT3R's
preprocess_arkitscenes.py applies a non-trivial `pose_cam_to_world @
rotated_to_cam` (an in-plane sky-direction rotation), so we must NOT assume the
result is OpenCV — we test it on real geometry.
The Cut3rAdapter feeds view["camera_pose"] downstream AS c2w OpenCV (x right,
y down, z forward). This script answers: is that actually true?
Three tests, in increasing rigor:
(1) Camera-Y world-axis. ARKitScenes' world frame is Z-up (preprocess uses
up_world = [0,0,1]). For an upright handheld camera looking roughly
horizontally, the OpenCV camera +Y axis (down) should point toward world
-Z. If c2w[:3,1] is dominantly +Z, the pose is OpenGL (Y up).
(2) Multi-view point-cloud consistency (the definitive test). Backproject two
time-separated frames' depth into the world under two hypotheses:
- OpenCV : use c2w as-is, OpenCV pinhole unprojection.
- OpenGL : use c2w @ diag(1,-1,-1,1), same unprojection.
Whichever hypothesis makes the two frames' surfaces OVERLAP (small median
nearest-neighbor distance) is the true convention. Mismatched conventions
send the two clouds to different/ mirrored places -> large NN distance.
(3) ctxt->trgt pose drift over many samples, to validate max_interval against
SPOC's bounds (mean translation < 1 m, mean rotation ~45 deg).
Run:
cd <repo_root>
PYTHONPATH=$PWD:$PWD/splat_belief \
.../envs/3d-belief-release/bin/python \
scripts/data_prep/verify_arkitscenes_pose_convention.py \
--root /home/ubuntu/tianmin-neurips/zwen19/data/ARKitScenes/processed_arkitscenes \
--scene 40958756
"""
from __future__ import annotations
import argparse
import os
import sys
from pathlib import Path
import numpy as np
# Make `import data_io...` work whether or not PYTHONPATH was set.
_REPO = Path(__file__).resolve().parents[2]
for p in (str(_REPO), str(_REPO / "splat_belief")):
if p not in sys.path:
sys.path.insert(0, p)
from data_io.cut3r_adapter import build_cut3r_dataset, Cut3rAdapter # noqa: E402
OPENGL_FLIP = np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float64)
def unproject_opencv(depth_m, K):
"""Backproject valid depth pixels with the OpenCV pinhole model -> (N,3) cam."""
H, W = depth_m.shape
us, vs = np.meshgrid(np.arange(W), np.arange(H))
valid = depth_m > 0
u = us[valid].astype(np.float64)
v = vs[valid].astype(np.float64)
d = depth_m[valid].astype(np.float64)
fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2]
x = (u - cx) * d / fx
y = (v - cy) * d / fy
return np.stack([x, y, d], axis=-1)
def cam_to_world(pts_cam, c2w):
ones = np.ones((pts_cam.shape[0], 1))
return (c2w @ np.concatenate([pts_cam, ones], axis=-1).T).T[:, :3]
def median_nn(a, b, max_pts=4000, seed=0):
"""Median nearest-neighbor distance from a -> b (subsampled)."""
from scipy.spatial import cKDTree
rng = np.random.default_rng(seed)
if a.shape[0] > max_pts:
a = a[rng.choice(a.shape[0], max_pts, replace=False)]
if b.shape[0] > max_pts:
b = b[rng.choice(b.shape[0], max_pts, replace=False)]
d, _ = cKDTree(b).query(a, k=1)
return float(np.median(d))
def rot_angle_deg(Ra, Rb):
R = Ra.T @ Rb
c = (np.trace(R) - 1.0) / 2.0
return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
def find_scene_idx(cut3r, scene):
"""Return a dataset index whose sampled sequence is from `scene`."""
for i in range(min(len(cut3r), 50)):
v = cut3r[i]
if v[0]["label"].split("_")[0] == scene:
return i
return 0
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--root", required=True)
ap.add_argument("--scene", default="40958756")
ap.add_argument("--num_views", type=int, default=5) # 1 ctxt + 1 trgt + 3 intm
ap.add_argument("--image_size", type=int, default=128)
ap.add_argument("--drift_samples", type=int, default=40)
args = ap.parse_args()
res = (args.image_size, args.image_size)
# seed -> deterministic sampling (mirrors overfit's cut3r_seed=42)
cut3r = build_cut3r_dataset("arkitscenes", root=args.root, split="train",
num_views=args.num_views, resolution=res, seed=42)
print(f"[verify] dataset len (groups) = {len(cut3r)}; scenes = "
f"{list(getattr(cut3r, 'scenes', []))}")
idx = find_scene_idx(cut3r, args.scene)
views = cut3r[idx]
print(f"[verify] using idx={idx}, scene={views[0]['label'].split('_')[0]}, "
f"{len(views)} views; labels={[v['label'] for v in views]}")
# ---- intrinsics report (fills the yaml fx/fy fallback) ----
K = views[0]["camera_intrinsics"].astype(np.float64)
th, tw = views[0]["true_shape"]
print(f"\n[verify] first-view K (pixel, true_shape={int(th)}x{int(tw)}):\n{np.round(K,2)}")
print(f" normalized: fx/W={K[0,0]/tw:.3f} fy/H={K[1,1]/th:.3f} "
f"cx/W={K[0,2]/tw:.3f} cy/H={K[1,2]/th:.3f}")
# ---- (1) camera-Y world axis (Z-up world) ----
print("\n[verify] TEST 1 — camera +Y world axis (Z-up world):")
for i, v in enumerate(views):
c2w = v["camera_pose"].astype(np.float64)
y = c2w[:3, 1]; z = c2w[:3, 2]
print(f" view{i}: cam+Y_world=({y[0]:+.2f},{y[1]:+.2f},{y[2]:+.2f}) "
f"cam+Z_world(fwd)=({z[0]:+.2f},{z[1]:+.2f},{z[2]:+.2f})")
meanY = np.mean([v["camera_pose"][:3, 1] for v in views], axis=0)
print(f" mean cam+Y world = ({meanY[0]:+.2f},{meanY[1]:+.2f},{meanY[2]:+.2f}) "
f"-> dominant {'−Z (OpenCV, Y-down)' if meanY[2] < 0 else '+Z (OpenGL, Y-up)'}")
# ---- (2) multi-view point-cloud consistency ----
# Use ADJACENT views (high overlap) — comparing ctxt vs trgt (far apart)
# gives an unreliable verdict because they barely overlap. With adjacent
# frames the correct convention is cm-scale; the wrong one degrades clearly
# (and degrades MORE as inter-frame rotation grows).
print("\n[verify] TEST 2 — multi-view consistency, ADJACENT views (OpenCV vs OpenGL flip):")
va, vb = views[0], views[1]
Ka, Kb = va["camera_intrinsics"].astype(np.float64), vb["camera_intrinsics"].astype(np.float64)
da, db = va["depthmap"].astype(np.float64), vb["depthmap"].astype(np.float64)
pa, pb = unproject_opencv(da, Ka), unproject_opencv(db, Kb)
for tag, M in (("OpenCV (as-is)", np.eye(4)), ("OpenGL (@diag(1,-1,-1,1))", OPENGL_FLIP)):
wa = cam_to_world(pa, va["camera_pose"].astype(np.float64) @ M)
wb = cam_to_world(pb, vb["camera_pose"].astype(np.float64) @ M)
nn = median_nn(wa, wb)
print(f" {tag:32s}: median cross-frame NN dist = {nn:.3f} m")
# ---- (3) ctxt->trgt drift ----
print("\n[verify] TEST 3 — ctxt->trgt pose drift "
f"({args.drift_samples} samples, max_interval={cut3r.max_interval}):")
trans, rots = [], []
for i in range(args.drift_samples):
v = cut3r[i % len(cut3r)]
c0 = v[0]["camera_pose"].astype(np.float64)
c1 = v[-1]["camera_pose"].astype(np.float64)
trans.append(np.linalg.norm(c1[:3, 3] - c0[:3, 3]))
rots.append(rot_angle_deg(c0[:3, :3], c1[:3, :3]))
trans, rots = np.array(trans), np.array(rots)
print(f" translation: mean={trans.mean():.2f} m median={np.median(trans):.2f} max={trans.max():.2f}")
print(f" rotation : mean={rots.mean():.1f}° median={np.median(rots):.1f} max={rots.max():.1f}")
print(f" SPOC bounds: adjacent_distance=1.0 m, adjacent_angle=45° "
f"-> {'OK' if trans.mean()<1.0 and rots.mean()<60 else 'TOO WIDE: lower max_interval'}")
# ---- adapter schema check ----
print("\n[verify] adapter schema (language_encoder=None -> lang is None):")
ad = Cut3rAdapter(cut3r_dataset=cut3r, num_context=1, num_target=1,
image_size=args.image_size, language_encoder=None,
use_depth_supervision=True, intermediate=True,
num_intermediate=3, z_near=0.1, z_far=10.0,
overfit_to_index=idx)
d, trgt = ad[0]
for k in ("ctxt_rgb", "trgt_rgb", "intm_rgb", "ctxt_c2w", "trgt_c2w",
"intm_c2w", "ctxt_abs_camera_poses", "intrinsics",
"ctxt_depth", "ctxt_depth_mask", "near", "far", "image_shape"):
if k in d:
val = d[k]
shp = tuple(val.shape) if hasattr(val, "shape") else val
print(f" {k:24s}: {shp}")
else:
print(f" {k:24s}: MISSING")
rgb = d["ctxt_rgb"]
print(f" ctxt_rgb range = [{rgb.min():.2f}, {rgb.max():.2f}] (expect ~[-1,1])")
import torch
assert torch.allclose(d["ctxt_c2w"][0], torch.eye(4), atol=1e-4), "ctxt_c2w[0] != identity!"
print(" ctxt_c2w[0] == identity ✓")
cm = d["ctxt_depth_mask"]
print(f" ctxt_depth valid fraction = {cm.float().mean().item():.1%}")
print("\n[verify] DONE.")
if __name__ == "__main__":
main()