File size: 4,598 Bytes
75ccd3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""Standalone reader for Diffraction human egocentric 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 aligned native RGB, metric depth, confidence, K and camera pose.



        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"]
        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)
        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}")
        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)."""
    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)
        points = camera_points(frame)
        print(key, frame["rgb"].shape, frame["depth_m"].shape, len(points), "valid camera points")