Skip to content

hylo.codeagents.replay_track

Package: hylo-code-agents · Core contracts

replay_track

Perception for replay-to-sim (RFC-0006 part 8): lift a recording to 3D, track objects, detect contact events, register the camera to the robot and retarget a human hand to a parallel gripper.

Frames. Tracking runs in a "frame" F with +z up and the table at z = table_z: the replay world itself when the recording knows its camera pose (our episodes), otherwise the gravity-levelled camera frame (GeoCalib roll / pitch, refined by the RANSAC table normal) shifted so the table is at z = 0. register then finds the similarity (scale, yaw about +z, translation) from F to the robot's world by aligning the carried object's track with the TCP path while the gripper holds it (the constant hand-object offset is absorbed by the translation).

Tracking (per object): a model point set from the first frame's mask; per frame the mask is propagated by projecting the model at the predicted pose (a box around it), keeping pixels that match the object's colour histogram (when it is discriminative), lie above the table and near the predicted surface, and are closer to this object than to any other; the pose is refined by trimmed ICP (translation + yaw by default, or full 6-DoF). A frame whose fit fails keeps the prediction and is marked lost.

Events: closed-gripper intervals from the opening signal (hysteresis relative to the open level); grasp (with the object that moves in the interval), lift (2 cm above its rest height), release, place (at rest after the release). The same detector runs on the simulation, so recorded and simulated events compare like for like.

UP module-attribute

UP = np.array([0.0, 0.0, 1.0])

LABEL_PROMPT module-attribute

LABEL_PROMPT = 'This is the first frame of a video in which {who} manipulates objects on a table.\n{task}List the distinct objects on the table that are handled in the video or are the place where something is put\n(at most {n}). Use short noun phrases with a colour or material when it helps an open-vocabulary segmenter tell them\napart (for example "red block", "white plate", "black bowl"). Do not list the robot, the gripper, the hand, the arm,\nthe table or the background. Reply with a JSON list of strings only.'

STOP_WORDS module-attribute

STOP_WORDS = {'the', 'a', 'an', 'it', 'on', 'in', 'into', 'inside', 'of', 'to', 'and', 'then', 'put', 'place', 'pick', 'up', 'move', 'take', 'from', 'top', 'left', 'right', 'front', 'back', 'next', 'both', 'its', 'onto'}

ALT_PROMPT module-attribute

ALT_PROMPT = 'An open-vocabulary segmenter found nothing for these labels in this image: {missing}.\nFor each, give up to three other short names a segmenter might know for the same object as it looks here (for\nexample "dish" or "pot" for a bowl seen from above). Reply with a JSON object mapping each label to a list.'

ColourModel

ColourModel(rgb: ndarray, mask: ndarray, background: ndarray, bins: int = 8)

Object-versus-background RGB histograms (8 bins per channel) from the first frame.

bins instance-attribute

bins = bins

p instance-attribute

p = h_obj / h_obj.sum() / (h_obj / h_obj.sum() + h_bg / h_bg.sum())

discriminative instance-attribute

discriminative = float(np.mean(self.p[q[mask]] > 0.5)) > 0.6 and float(np.mean(self.p[q[background]] > 0.5)) < 0.3

mean instance-attribute

mean = np.asarray(rgb[mask].mean(0), float) if mask.any() else np.full(3, 128.0)

prob

prob(rgb: ndarray) -> np.ndarray

Lift dataclass

Lift(depth: ndarray, K: ndarray, T_frame_cam: ndarray, table_z: float, table_extent: ndarray, frame: str, info: dict[str, Any] = dict())

Depth and camera in the tracking frame F (+z up). depth (T, H, W) camera metres; K (3, 3); T_frame_cam rigid; table_z, table_extent [[x0, x1], [y0, y1]] in F; frame "world" (F is the replay world) or "level".

depth instance-attribute

depth: ndarray

K instance-attribute

K: ndarray

T_frame_cam instance-attribute

T_frame_cam: ndarray

table_z instance-attribute

table_z: float

table_extent instance-attribute

table_extent: ndarray

frame instance-attribute

frame: str

info class-attribute instance-attribute

info: dict[str, Any] = field(default_factory=dict)

points

points(t: int, mask: ndarray | None = None) -> tuple[np.ndarray, np.ndarray]

Track dataclass

Track(name: str, label: str, model: ndarray, poses: ndarray, lost: ndarray, inliers: ndarray, npts: ndarray, colour: list[float], mask0: ndarray | None = None, extent: dict[str, Any] = dict())

name instance-attribute

name: str

label instance-attribute

label: str

model instance-attribute

model: ndarray

poses instance-attribute

poses: ndarray

lost instance-attribute

lost: ndarray

inliers instance-attribute

inliers: ndarray

npts instance-attribute

npts: ndarray

colour instance-attribute

colour: list[float]

mask0 class-attribute instance-attribute

mask0: ndarray | None = None

extent class-attribute instance-attribute

extent: dict[str, Any] = field(default_factory=dict)

positions

positions() -> np.ndarray

summary

summary() -> dict[str, Any]

pose

pose(R: ndarray | None = None, p: Any = None) -> np.ndarray

inv

inv(T: ndarray) -> np.ndarray

apply

apply(T: ndarray, pts: ndarray) -> np.ndarray

rotz

rotz(a: float) -> np.ndarray

rot_between

rot_between(a: ndarray, b: ndarray) -> np.ndarray

The smallest rotation taking unit vector a to unit vector b.

backproject

backproject(depth: ndarray, K: ndarray, mask: ndarray | None = None, max_depth: float = 6.0) -> tuple[np.ndarray, np.ndarray]

Camera-frame points of the valid depth pixels (inside mask) and their (row, col) indices.

project

project(pts_cam: ndarray, K: ndarray) -> tuple[np.ndarray, np.ndarray]

labels_from_text

labels_from_text(text: str, n: int = 4) -> list[str]

Deterministic fallback: noun phrases of the instruction, the words after 'the' up to a preposition.

propose_labels

propose_labels(model: Any, rgb: ndarray, instruction: str, who: str = 'a robot', n: int = 4) -> dict[str, Any]

Ask a vision chat model for segmenter labels; falls back to the instruction's noun phrases.

alternative_labels

alternative_labels(model: Any, rgb: ndarray, missing: Sequence[str]) -> dict[str, list[str]]

Other names for labels the segmenter missed: from the vision model, else the label's last word and generic container / object words.

normalise_depth_scale

normalise_depth_scale(depths: ndarray, static: ndarray) -> tuple[np.ndarray, np.ndarray]

Per-frame monocular depth rescaled to frame 0 on static pixels (median ratio, robust to moving parts).

fit_plane

fit_plane(pts: ndarray, rng: Generator, thresh: float, up_hint: ndarray | None = None, iters: int = 500) -> tuple[np.ndarray, np.ndarray, np.ndarray]

Dominant plane facing the camera (at the origin): unit normal towards the camera, a point on it and the inlier mask. Planes far from up_hint (> 40 degrees) count 0.6 of their inliers: gravity from one image is a hint (it can be far off for a camera looking straight down), the table is the big plane.

level_frame

level_frame(depth0: ndarray, K: ndarray, R_level_cam: ndarray | None, rng: Generator) -> tuple[np.ndarray, float, np.ndarray, dict[str, Any]]

T_frame_cam for a camera with unknown pose: the table plane's normal is +z (GeoCalib's gravity picks the plane and fixes the heading), the table at z = 0. Returns (T_frame_cam, table_z, extent, info).

table_in_world

table_in_world(depth0: ndarray, K: ndarray, T_world_cam: ndarray, rng: Generator, hint: float | None = None) -> tuple[float, np.ndarray]

object_points

object_points(lift: Lift, mask: ndarray, t: int = 0, min_height: float = 0.004) -> np.ndarray

Masked points of one object in F (mask eroded, table and outliers removed, largest 3D component).

box_extent

box_extent(points: ndarray, table_z: float) -> dict[str, Any]

Footprint (minimum-area rectangle of the xy hull) and height down to the table.

icp

icp(model: ndarray, observed: ndarray, init: ndarray, mode: str = 'yaw', iters: int = 25, max_dist: float = 0.03, trim: float = 85.0) -> tuple[np.ndarray, float, float]

Trimmed point-to-point ICP of model (object frame) onto observed, starting at init (object -> F). mode "xyz" (translation), "yaw" (translation + rotation about +z) or "full". Returns (T, rmse, inlier fraction within 1 cm).

init_tracks

init_tracks(lift: Lift, rgb0: ndarray, masks: Sequence[tuple[str, ndarray]], min_points: int = 25) -> list[Track]

track_objects

track_objects(lift: Lift, rgb: ndarray, tracks: list[Track], *, mode: str = 'yaw', prior: Callable[[str, int], ndarray | None] | None = None, gate: float = 0.04, max_speed: float = 1.0, fps: float = 10.0, log: Callable[[str], None] | None = None) -> list[Track]

Track every object through the video (see the module doc). prior(name, t) may give a predicted pose (e.g. attached to the gripper while it is closed).

smooth_poses

smooth_poses(poses: ndarray, lost: ndarray, window: int = 3) -> np.ndarray

Moving-average positions (rotations kept), lost frames interpolated between good ones.

closed_intervals

closed_intervals(gripper: ndarray, *, close_frac: float = 0.8, open_frac: float = 0.9, min_len: int = 2, merge_gap: int = 0) -> list[tuple[int, int]]

Frames [start, end) where the gripper is closed, with hysteresis relative to the open level (90th percentile of the signal); intervals separated by at most merge_gap open frames are merged (noisy signals such as a hand's aperture).

detect_events

detect_events(time: ndarray, gripper: ndarray | None, objects: dict[str, ndarray], *, table_z: float = 0.0, lift_h: float = 0.02, move_eps: float = 0.015, rest_speed: float = 0.03, intervals: list[tuple[int, int]] | None = None, closed_level: float = 0.04) -> list[dict[str, Any]]

Contact events from the gripper opening and object positions {name: (T, 3)}: grasp, lift, release, place (and missed_grasp when the gripper closes on nothing).

match_events

match_events(ref: list[dict[str, Any]], sim: list[dict[str, Any]], tol_s: float = 1.0) -> dict[str, Any]

Each reference grasp / lift / place matched to a simulated event of the same type and object within tol.

register_similarity

register_similarity(obj_pos: ndarray, tcp_pos: ndarray, *, scale: bool = True) -> dict[str, Any]

Least-squares s, yaw, t with tcp = s Rz(yaw) obj + t (both (N, 3), F and world).

similarity_matrix

similarity_matrix(reg: dict[str, Any]) -> np.ndarray

carried_pairs

carried_pairs(tracks: list[Track], tcp: ndarray, intervals: list[tuple[int, int]], move_eps: float = 0.02) -> tuple[np.ndarray, np.ndarray, list[str]]

(object positions in F, TCP positions) over the frames each closed interval carries an object.

anchor_grasps

anchor_grasps(tcp: ndarray, objects: dict[str, ndarray], events: list[dict[str, Any]], intervals: list[tuple[int, int]], ramp: int = 5) -> tuple[np.ndarray, list[dict[str, Any]]]

Grasp-anchored retargeting: a hand's thumb-index midpoint is not where a parallel gripper must close on the object (a wrap grasp holds the object beside the fingertips), so during each grasp the TCP path is shifted by the offset that puts it on the object's centre at the grasp moment, blended in and out over ramp frames. The hand's motion during the grasp is kept.

hand_scale

hand_scale(kp3d: ndarray, kp2d: ndarray, depth: ndarray, K: ndarray, valid: ndarray) -> dict[str, Any]

Scale that makes the monocular depth agree with the hand's metric size (the hand model's palm, about 9 cm wrist to middle knuckle): ratio of palm bone lengths, hand model over depth back-projection.

hand_keypoints_world

hand_keypoints_world(kp3d_cam: ndarray, kp2d: ndarray, valid: ndarray, depth: ndarray, K: ndarray, T_frame_cam: ndarray, smooth: int = 5) -> dict[str, np.ndarray]

The 21 hand keypoints per frame in F: each frame's metric hand (camera frame) shifted so its wrist and knuckles sit on the (scaled) depth map, as hand_to_gripper places it; missing frames interpolated, then a moving average over smooth frames. Returns {"kp": (T, 21, 3), "valid": (T,) frames with a detection}.

hand_to_gripper

hand_to_gripper(kp3d_cam: ndarray, kp2d: ndarray, valid: ndarray, depth: ndarray, K: ndarray, T_frame_cam: ndarray, max_opening: float = 0.12, smooth: int = 5) -> dict[str, np.ndarray]

Retarget one hand to a parallel-gripper TCP in F: origin between thumb and index tips, closing axis thumb to index, approach from the wrist towards the tips; opening = thumb-index aperture / max_opening. The hand is placed in depth by the (scaled) depth map at the wrist and knuckles; missing frames are interpolated.