"""Sanity check: project the end-effector position from trajectory.h5 onto real 720p video frames using the improved calibrations. Usage: python project_check.py [frame_offset] """ import json import sys from pathlib import Path import cv2 import h5py import numpy as np from scipy.spatial.transform import Rotation as R ROOT = Path(__file__).resolve().parent.parent def pose6_to_mat(pose6): """[x,y,z,rx,ry,rz] (euler xyz) -> 4x4 homogeneous matrix.""" m = np.eye(4) m[:3, :3] = R.from_euler("xyz", pose6[3:6]).as_matrix() m[:3, 3] = pose6[0:3] return m def load_calib(uuid): sup = json.load(open(ROOT / "calib/cam2base_extrinsic_superset.json")) intr = json.load(open(ROOT / "calib/intrinsics.json")) ext = {k: v for k, v in sup[uuid].items() if k.isdigit()} K = {} for serial in ext: fx, cx, fy, cy = intr[uuid][serial]["cameraMatrix"] K[serial] = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) return ext, K def main(ep_dir, frame_offset=0): ep_dir = Path(ep_dir) meta = json.load(open(ep_dir / "metadata.json")) uuid = meta["uuid"] ext, K = load_calib(uuid) print("episode:", uuid, "| cameras with improved calib:", list(ext)) with h5py.File(ep_dir / "trajectory.h5", "r") as f: ee_pos = f["observation/robot_state/cartesian_position"][:, :3] out_dir = ROOT / "out" / uuid / "project_check" out_dir.mkdir(parents=True, exist_ok=True) n_steps = len(ee_pos) for serial, pose6 in ext.items(): T_base2cam = np.linalg.inv(pose6_to_mat(pose6)) cap = cv2.VideoCapture(str(ep_dir / f"recordings/MP4/{serial}.mp4")) n_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) for step in range(0, min(n_steps, n_frames), max(1, n_steps // 8)): cap.set(cv2.CAP_PROP_POS_FRAMES, step + frame_offset) ok, frame = cap.read() if not ok: continue p_cam = T_base2cam @ np.append(ee_pos[step], 1.0) uv = K[serial] @ p_cam[:3] u, v = uv[:2] / uv[2] cv2.drawMarker(frame, (int(round(u)), int(round(v))), (0, 0, 255), cv2.MARKER_CROSS, 40, 3) cv2.imwrite(str(out_dir / f"{serial}_step{step:04d}.jpg"), frame) cap.release() print(f"cam {serial}: wrote frames to {out_dir}") if __name__ == "__main__": main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 0)