"""Standalone reader for Diffraction human egocentric RGB and RGB-D samples. Dependencies: numpy, polars, opencv-python. No pipeline or robot software needed. """ from __future__ import annotations import json import zipfile from pathlib import Path import cv2 import numpy as np import polars as pl class ObservationDataset: def __init__(self, root): self.root = Path(root) self.info = json.loads((self.root / "dataset.json").read_text(encoding="utf-8")) self.episodes = {e["capture_id"]: e for e in self.info["episodes"]} def table(self, capture_id, name): e = self.episodes[capture_id] return pl.read_parquet(self.root / e["signals"][name]) def frame(self, capture_id, frame_index): """Return RGB and available sensor measurements; absent modalities are None. ARKit pose is device VIO; no ground-truth or robot-action claim is implied. Depth zero is invalid. Confidence filtering is explicit and reproducible. """ e = self.episodes[capture_id] if not isinstance(frame_index, int) or not 0 <= frame_index < e["frame_count"]: raise IndexError(frame_index) mapping = self.table(capture_id, "frame_mapping").filter(pl.col("rgb_frame_index") == frame_index).row(0, named=True) source_frame_index = mapping["source_frame_index"] cap = cv2.VideoCapture(str(self.root / e["video"])) try: cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index) ok, bgr = cap.read() finally: cap.release() if not ok: raise RuntimeError(f"RGB decode failed at frame {frame_index}") if e.get("modalities", {}).get("depth") is False: return {"rgb":cv2.cvtColor(bgr,cv2.COLOR_BGR2RGB),"depth_m":None,"depth_valid":None,"confidence":None, "K_rgb":None,"camera_pose_xyzw":None,"timestamp_s":mapping["t_s"],"sensor_timestamp_s":None, "source_timestamp_s":mapping["source_timestamp_s"],"instruction":e["instruction"], "source_frame_index":source_frame_index,"rgb_frame_index":frame_index,"modalities":e["modalities"]} intr = self.table(capture_id, "camera_intrinsics").filter(pl.col("source_frame_index") == source_frame_index).row(0, named=True) pose = self.table(capture_id, "arkit_poses").filter(pl.col("t_s") == mapping["t_s"]).row(0, named=True) stem = f"{source_frame_index:06d}.png" with zipfile.ZipFile(self.root / e["sensors"]) as z: depth_raw = cv2.imdecode(np.frombuffer(z.read("depth/" + stem), np.uint8), cv2.IMREAD_UNCHANGED) conf = cv2.imdecode(np.frombuffer(z.read("confidence/" + stem), np.uint8), cv2.IMREAD_UNCHANGED) if depth_raw is None or conf is None or depth_raw.shape != conf.shape: raise ValueError("Invalid depth/confidence pair") depth = depth_raw.astype(np.float32) / 1000. valid = (depth > 0) & (conf >= self.info["min_depth_confidence"]) depth[~valid] = 0 K = np.array([[intr["fx"], 0, intr["cx"]], [0, intr["fy"], intr["cy"]], [0, 0, 1]], np.float64) return {"rgb": cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB), "depth_m": depth, "depth_valid": valid, "confidence": conf, "K_rgb": K, "camera_pose_xyzw": np.array([pose[k] for k in ("tx", "ty", "tz", "qx", "qy", "qz", "qw")]), "timestamp_s": mapping["t_s"], "sensor_timestamp_s": mapping["sensor_timestamp_s"], "instruction": e["instruction"], "source_frame_index": source_frame_index, "rgb_frame_index": frame_index} def annotations_near(self, capture_id, channel, timestamp_s, max_age_s=0.05): """Sparse annotations stay absent beyond the caller's explicit age gate.""" df = self.table(capture_id, channel) if df.is_empty(): return df distance = (pl.col("t_s") - timestamp_s).abs() nearby = df.filter(distance <= max_age_s) if nearby.is_empty(): return nearby nearest = nearby.select((pl.col("t_s") - timestamp_s).abs().arg_min()).item() return nearby.filter(pl.col("t_s") == nearby["t_s"][nearest]) def camera_points(frame): """Valid depth pixels backprojected in OpenCV camera axes (+x right,+y down,+z forward).""" if frame.get("depth_m") is None or frame.get("K_rgb") is None: raise ValueError("Metric depth and calibrated intrinsics are unavailable for this RGB-only observation") depth, K = frame["depth_m"], frame["K_rgb"].copy() dh, dw = depth.shape; rh, rw = frame["rgb"].shape[:2] K[0, :] *= dw / rw; K[1, :] *= dh / rh yy, xx = np.indices(depth.shape) xyz = np.stack([(xx-K[0, 2])*depth/K[0, 0], (yy-K[1, 2])*depth/K[1, 1], depth], -1) return xyz[frame["depth_valid"]] if __name__ == "__main__": import argparse p = argparse.ArgumentParser(); p.add_argument("root", type=Path) args = p.parse_args(); ds = ObservationDataset(args.root) for key, episode in ds.episodes.items(): frame = ds.frame(key, episode["frame_count"] // 2) if frame["depth_m"] is None: print(key, frame["rgb"].shape, "RGB-only; metric sensor channels unavailable") else: points = camera_points(frame) print(key, frame["rgb"].shape, frame["depth_m"].shape, len(points), "valid camera points")