""" DROID projection: per-camera ZED left intrinsics @ 1280x720 + h5 camera extrinsics. Data: ``trajectory.h5`` + ``recordings/MP4``. Intrinsics: cache / SN.conf / SVO / model default. """ from __future__ import annotations import numpy as np from scipy.spatial.transform import Rotation # DROID MP4 / SVO left view @ HD DROID_LEFT_K_1280x720 = np.array( [ [522.42260742, 0.0, 653.9631958], [0.0, 522.42260742, 358.79196167], [0.0, 0.0, 1.0], ], dtype=np.float64, ) DROID_NATIVE_HW = (720, 1280) # (H, W) # Polymetis / DROID raw h5 use extrinsic euler in this convention (see droid convert scripts). DROID_EULER_CONVENTION = "xyz" GRIPPER_OFFSETS = np.array( [ [0.0, 0.0, 0.0], [0.0, 0.045, 0.161], [0.0, -0.045, 0.161], [0.0, 0.045, 0.13], [0.0, -0.045, 0.13], [0.0, 0.0, 0.13], [0.0, 0.0, 0.065], ], dtype=np.float64, ) WRIST_GRIPPER_TEMPLATE_FRAC = np.array( [ [0.48, 0.75], # palm / wrist bridge [0.44, 0.62], # left finger base [0.82, 0.60], # right finger base [0.33, 0.84], # left finger outer [0.86, 0.83], # right finger outer [0.42, 0.93], # left fingertip <-- adjusted [0.81, 0.96], # right fingertip ], dtype=np.float64, ) def pose6_to_matrix(pose6: np.ndarray, *, euler: str = DROID_EULER_CONVENTION) -> np.ndarray: x = np.asarray(pose6, dtype=np.float64).reshape(-1) rot = Rotation.from_euler(euler, x[3:6]).as_matrix() T = np.eye(4, dtype=np.float64) T[:3, :3] = rot T[:3, 3] = x[:3] return T def world_to_cam_matrix(extrinsic_6d: np.ndarray) -> np.ndarray: """h5 ``camera_extrinsics`` stores cam-to-world; return world-to-cam 4x4.""" return np.linalg.inv(pose6_to_matrix(extrinsic_6d)) def scale_K_to_image_hw(K: np.ndarray, native_hw: tuple[int, int], image_hw: tuple[int, int]) -> np.ndarray: """Scale pinhole K from ``native_hw`` to ``image_hw`` (H, W).""" href, wref = native_hw hnew, wnew = image_hw K = np.asarray(K, dtype=np.float64).reshape(3, 3).copy() K[0, 0] *= wnew / float(wref) K[0, 2] *= wnew / float(wref) K[1, 1] *= hnew / float(href) K[1, 2] *= hnew / float(href) return K def droid_left_K_for_image_hw(image_hw: tuple[int, int], *, native_hw: tuple[int, int] = DROID_NATIVE_HW) -> np.ndarray: return scale_K_to_image_hw(DROID_LEFT_K_1280x720, native_hw, image_hw) def wrist_gripper_template_pixels(image_hw: tuple[int, int]) -> np.ndarray: """7-point U-shaped gripper seed layout in pixel coords (not a line).""" h, w = image_hw return (WRIST_GRIPPER_TEMPLATE_FRAC * np.array([float(w), float(h)], dtype=np.float64)).astype( np.float64 ) def gripper_queries_in_image( pixels: np.ndarray, vis: np.ndarray, image_hw: tuple[int, int], ) -> np.ndarray: """Boolean mask: visible, finite, and inside ``image_hw`` (H, W).""" h, w = image_hw pts = np.asarray(pixels, dtype=np.float64) mask = np.asarray(vis, dtype=bool).reshape(-1) mask &= np.isfinite(pts).all(axis=1) mask &= (pts[:, 0] >= 0.0) & (pts[:, 0] < float(w)) mask &= (pts[:, 1] >= 0.0) & (pts[:, 1] < float(h)) return mask def align_gripper_queries_to_template( queries: np.ndarray, valid: np.ndarray, image_hw: tuple[int, int], ) -> np.ndarray: """Keep valid projections; place invalid indices from a scaled gripper template.""" out = wrist_gripper_template_pixels(image_hw).astype(np.float32, copy=True) valid = np.asarray(valid, dtype=bool).reshape(-1) q = np.asarray(queries, dtype=np.float32) if valid.any(): vpts = q[valid] vmin, vmax = vpts.min(axis=0), vpts.max(axis=0) tmpl = out.copy() tmin, tmax = tmpl.min(axis=0), tmpl.max(axis=0) scale = (vmax - vmin) / np.maximum(tmax - tmin, 1e-3) out = (tmpl - tmin) * scale + vmin out[valid] = q[valid] return out # Wrist mesh indices that usually project onto visible finger geometry (not the EEF center line). WRIST_FINGER_MESH_INDICES = (1, 2, 3, 4) def _clamp_queries_to_image(queries: np.ndarray, image_hw: tuple[int, int]) -> np.ndarray: h, w = image_hw out = np.asarray(queries, dtype=np.float32).copy() out[..., 0] = np.clip(out[..., 0], 0.0, float(w - 1)) out[..., 1] = np.clip(out[..., 1], 0.0, float(h - 1)) return out def complete_wrist_mesh_queries( pix: np.ndarray, vis: np.ndarray, image_hw: tuple[int, int], ) -> np.ndarray: """ Build 7 CoTracker seeds from wrist projection. Center mesh points (0/5/6) often miss the image on wrist cam; finger points (1-4) are reliable. Interpolate missing indices in 2D from finger projections instead of warping a fixed template (which caused straight-line / off-gripper seeds). """ h, w = image_hw out = np.asarray(pix, dtype=np.float32).copy() valid = gripper_queries_in_image(out, vis, image_hw) finger_ok = [i for i in WRIST_FINGER_MESH_INDICES if valid[i]] if len(finger_ok) >= 2: if not valid[0]: out[0] = out[finger_ok].mean(axis=0) if not valid[2] and valid[1]: out[2] = 2.0 * out[0] - out[1] if not valid[1] and valid[2]: out[1] = 2.0 * out[0] - out[2] if not valid[4] and valid[3]: out[4] = 2.0 * out[0] - out[3] if not valid[3] and valid[4]: out[3] = 2.0 * out[0] - out[4] if not valid[5]: if valid[3] and valid[4]: mid = 0.5 * (out[3] + out[4]) elif valid[1] and valid[2]: mid = 0.5 * (out[1] + out[2]) else: mid = out[finger_ok].mean(axis=0) out[5] = 0.6 * out[0] + 0.4 * mid if not valid[6]: tip_dir = out[5] - out[0] if float(np.linalg.norm(tip_dir)) > 2.0: out[6] = out[5] + 0.5 * tip_dir else: out[6] = out[5] + np.array([0.0, 0.1 * h], dtype=np.float32) return _clamp_queries_to_image(out, image_hw) if int(valid.sum()) >= 3: return _clamp_queries_to_image(out, image_hw) return wrist_gripper_template_pixels(image_hw).astype(np.float32) def scale_pixels_between_hw( pixels: np.ndarray, src_hw: tuple[int, int], dst_hw: tuple[int, int], ) -> np.ndarray: """Affine scale pixel coords when resizing images src_hw -> dst_hw.""" href, wref = src_hw hnew, wnew = dst_hw out = np.asarray(pixels, dtype=np.float64).copy() sx = wnew / float(wref) sy = hnew / float(href) out[..., 0] *= sx out[..., 1] *= sy return out def project_gripper_mesh_wrist( cartesian6: np.ndarray, extrinsic_6d: np.ndarray, gripper_offset_6d: np.ndarray, *, K: np.ndarray, dist: np.ndarray | None = None, native_hw: tuple[int, int] = DROID_NATIVE_HW, gripper_open: float | None = None, ) -> tuple[np.ndarray, np.ndarray]: """ Wrist-view gripper mesh: same chain as :func:`project_gripper_mesh`. h5 ``{serial}_left_gripper_offset`` is the camera mount (``T_c2w ≈ T_eef @ T_offset``) and is already reflected in ``extrinsic_6d``; mesh points live in the EEF frame and must not be premultiplied by ``T_gripper_offset``. ``gripper_offset_6d`` is kept for API compatibility only. """ del gripper_offset_6d return project_gripper_mesh( cartesian6, extrinsic_6d, K=K, dist=dist, native_hw=native_hw, gripper_open=gripper_open, ) def project_gripper_mesh( cartesian6: np.ndarray, extrinsic_6d: np.ndarray, *, K: np.ndarray, dist: np.ndarray | None = None, native_hw: tuple[int, int] = DROID_NATIVE_HW, gripper_open: float | None = None, ) -> tuple[np.ndarray, np.ndarray]: """7 gripper points -> (7,2) pixels and visibility at ``native_hw`` resolution.""" c = np.asarray(cartesian6, dtype=np.float64).reshape(-1) R_wg = Rotation.from_euler(DROID_EULER_CONVENTION, c[3:6]).as_matrix() offsets = ( gripper_offsets_for_opening(gripper_open) if gripper_open is not None else GRIPPER_OFFSETS ) world = (R_wg @ offsets.T).T + c[:3].reshape(1, 3) K = np.asarray(K, dtype=np.float64).reshape(3, 3) w2c = world_to_cam_matrix(extrinsic_6d) R = w2c[:3, :3] t = w2c[:3, 3].reshape(3, 1) pixels = np.zeros((7, 2), dtype=np.float64) vis = np.zeros((7,), dtype=bool) dist_use = None if dist is not None: dist_use = np.asarray(dist, dtype=np.float64).reshape(-1) if dist_use.size >= 5 and np.allclose(dist_use[:5], 0.0): dist_use = None href, wref = native_hw cam_z = np.zeros((7,), dtype=np.float64) if dist_use is not None: import cv2 rvec, _ = cv2.Rodrigues(R) pts, _ = cv2.projectPoints( world.reshape(-1, 1, 3).astype(np.float64), rvec, t, K, dist_use[:5], ) pixels = pts.reshape(-1, 2) cam_z = (R @ world.T + t).T[:, 2] else: for i, p in enumerate(world): cam3d = (w2c @ np.concatenate([p, [1.0]]))[:3] cam_z[i] = cam3d[2] if cam_z[i] <= 1e-5: pixels[i] = np.nan vis[i] = False continue proj = K @ cam3d if abs(proj[2]) < 1e-8: pixels[i] = np.nan vis[i] = False else: pixels[i] = (proj / proj[2])[:2] for i in range(7): if cam_z[i] <= 0.02: vis[i] = False pixels[i] = np.nan continue if not ( np.isfinite(pixels[i, 0]) and np.isfinite(pixels[i, 1]) and 0.0 <= pixels[i, 0] < float(wref) and 0.0 <= pixels[i, 1] < float(href) ): vis[i] = False pixels[i] = np.nan else: vis[i] = True return pixels.astype(np.float64), vis.astype(np.float64) def gripper_offsets_for_opening(gripper_open: float) -> np.ndarray: """Scale finger keypoint offsets by gripper opening (0=closed, 1=open).""" g = float(np.clip(gripper_open, 0.0, 1.0)) offsets = GRIPPER_OFFSETS.copy() # Finger tips (indices 1-4): spread with opening; center / palm points stay fixed. for i in (1, 2, 3, 4): offsets[i, 1] *= 0.35 + 0.65 * g offsets[i, 2] *= 0.55 + 0.45 * g return offsets def _score_wrist_seed_queries(queries: np.ndarray, image_hw: tuple[int, int]) -> float: h, w = image_hw q = np.asarray(queries, dtype=np.float64).reshape(7, 2) cy = float(q[:, 1].mean() / max(h, 1)) cx_spread = float(q[:, 0].std()) y_spread = float(q[:, 1].std()) if cy < 0.28 or cy > 0.92: return -1.0 if cx_spread < 12.0 or y_spread < 8.0: return -1.0 finger = q[list(WRIST_FINGER_MESH_INDICES)] finger_spread = float(finger.std(axis=0).mean()) return finger_spread + cx_spread * 0.08 + (0.68 - abs(cy - 0.58)) * 3.0 def make_wrist_gripper_mesh_queries( cartesian: np.ndarray, wrist_extrinsics: np.ndarray, wrist_gripper_offset: np.ndarray, gripper_open: np.ndarray, *, K: np.ndarray, dist: np.ndarray | None, out_hw: tuple[int, int], K_candidates: list[tuple[np.ndarray, np.ndarray | None]] | None = None, ) -> np.ndarray: """ CoTracker seeds for 7 wrist gripper points. Uses the same chain as exterior: ``inv(cam2world) @ T_eef @ mesh`` (see :func:`project_gripper_mesh`). Tries KarlP vs ZED intrinsics and several timesteps. """ t_len = int(cartesian.shape[0]) if t_len < 1: return wrist_gripper_template_pixels(out_hw).astype(np.float32) seed_times = sorted({0, t_len // 4, t_len // 2, max(0, t_len - 1)}) k_list: list[tuple[np.ndarray, np.ndarray | None]] = ( list(K_candidates) if K_candidates else [(K, dist)] ) best_queries: np.ndarray | None = None best_score = -1.0 del wrist_gripper_offset # mount calib is in wrist_extrinsics, not applied to mesh for t_seed in seed_times: ext6 = wrist_extrinsics[t_seed] for K_use, dist_use in k_list: # Wrist seeds: nominal finger mesh only (gripper_open scaling pushes points OOB). pix, vis = project_gripper_mesh( cartesian[t_seed], ext6, K=K_use, dist=None, native_hw=DROID_NATIVE_HW, gripper_open=None, ) pix_out = scale_pixels_between_hw(pix, DROID_NATIVE_HW, out_hw) cand = complete_wrist_mesh_queries(pix_out, vis, out_hw) score = _score_wrist_seed_queries(cand, out_hw) if score > best_score: best_score = score best_queries = cand if best_score >= 25.0: return best_queries.astype(np.float32) if best_queries is not None and best_score >= 5.0: return best_queries.astype(np.float32) return wrist_gripper_template_pixels(out_hw).astype(np.float32) def make_image_grid(img_h: int, img_w: int, grid_size: int = 5) -> np.ndarray: xs = np.linspace(0.0, float(img_w - 1), grid_size, dtype=np.float64) ys = np.linspace(0.0, float(img_h - 1), grid_size, dtype=np.float64) return np.stack(np.meshgrid(xs, ys, indexing="xy"), axis=-1).reshape(-1, 2)