[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6F38VKBQ9CW9KX14461W634":3,"skill-same:01M6F38VKBQ9CW9KX14461W634":75},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":26,"publishedAt":47,"linkOnly":48,"markdownContent":49,"markdownBody":50,"frontMatter":51,"refName":52,"commitSha":53,"skillDirectory":54,"forksCount":55,"repositoryHtmlUrl":56,"repositoryHomepageUrl":57,"ownerHtmlUrl":58,"ownerBlogUrl":6,"ownerDescription":59,"updatedAt":60,"install":61,"resources":74},"01M6F38VKBQ9CW9KX14461W634","robot-perception",null,"Comprehensive best practices for robot perception systems covering cameras, LiDARs, depth sensors, IMUs, and multi-sensor setups. Use this skill when working with RGB image processing, depth maps, point clouds, sensor calibration (intrinsic, extrinsic, hand-eye), object detection, semantic segmentation, 3D reconstruction, visual servoing, or perception pipeline optimization. Trigger whenever the user mentions OpenCV, Open3D, PCL, RealSense, ZED, OAK-D, camera calibration, AprilTags, ArUco markers, stereo vision, RGBD, point cloud filtering, ICP registration, coordinate transforms, camera intrinsics, distortion correction, image undistortion, sensor streaming, frame synchronization, or any computer vision task in a robotics context. Also covers multi-camera rigs, time synchronization across sensors, perception latency budgets, and production deployment of perception pipelines.","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Farpitg1304\u002Frobotics-agent-skills\u002Frobot-perception\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000016","图像与多媒体","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],"robot perception","perception","robot","time","zed","transforms","processing","markers","icp","across","image","coordinate","maps","robotics","image processing","synchronization","3D","segmentation","pipeline","streaming","2026-11-10 10:12:30",false,"---\nname: robot-perception\ndescription: >\n  Comprehensive best practices for robot perception systems covering cameras, LiDARs, depth sensors,\n  IMUs, and multi-sensor setups. Use this skill when working with RGB image processing, depth maps,\n  point clouds, sensor calibration (intrinsic, extrinsic, hand-eye), object detection, semantic\n  segmentation, 3D reconstruction, visual servoing, or perception pipeline optimization. Trigger\n  whenever the user mentions OpenCV, Open3D, PCL, RealSense, ZED, OAK-D, camera calibration,\n  AprilTags, ArUco markers, stereo vision, RGBD, point cloud filtering, ICP registration, coordinate\n  transforms, camera intrinsics, distortion correction, image undistortion, sensor streaming,\n  frame synchronization, or any computer vision task in a robotics context. Also covers multi-camera\n  rigs, time synchronization across sensors, perception latency budgets, and production deployment\n  of perception pipelines.\n---\n\n# Robot Perception Skill\n\n## When to Use This Skill\n- Setting up and configuring camera, LiDAR, or depth sensors\n- Building RGB, depth, or point cloud processing pipelines\n- Calibrating cameras (intrinsic, extrinsic, hand-eye)\n- Implementing object detection, segmentation, or tracking for robots\n- Fusing data from multiple sensor modalities\n- Streaming sensor data with proper threading and buffering\n- Synchronizing multi-sensor rigs\n- Deploying perception models on robot hardware (GPU, edge)\n- Debugging perception failures (latency, dropped frames, misalignment)\n\n## Sensor Landscape\n\n### Sensor Types and Characteristics\n\n```\nSensor Type        Output              Range       Rate     Best For\n─────────────────────────────────────────────────────────────────────────\nRGB Camera         (H,W,3) uint8       ∞           30-120Hz Object detection, tracking, visual servoing\nStereo Camera      (H,W,3)+(H,W,3)    0.3-20m     30-90Hz  Dense depth from passive stereo\nStructured Light   (H,W) float + RGB   0.2-10m     30Hz     Indoor manipulation, short range\nToF Depth          (H,W) float + RGB   0.1-10m     30Hz     Indoor, medium range\nLiDAR (spinning)   (N,3) or (N,4)     0.5-200m    10-20Hz  Outdoor navigation, mapping\nLiDAR (solid-st.)  (N,3)              0.5-200m    10-30Hz  Automotive, outdoor\nIMU                (6,) or (9,)        N\u002FA         200-1kHz Orientation, motion estimation\nForce\u002FTorque       (6,) float          N\u002FA         1kHz+    Contact detection, force control\nTactile            (H,W) or (N,3)      Contact     30-100Hz Grasp quality, texture\nEvent Camera       Events (x,y,t,p)    ∞           μs       High-speed tracking, HDR scenes\n```\n\n### Common Sensor Hardware\n\n```\nDevice             Type               SDK\u002FDriver           ROS2 Package\n──────────────────────────────────────────────────────────────────────────\nIntel RealSense    Structured Light   pyrealsense2         realsense2_camera\nStereolabs ZED     Stereo + IMU       pyzed                zed_wrapper\nLuxonis OAK-D      Stereo + Neural    depthai              depthai_ros\nFLIR\u002FBasler        Industrial RGB     PySpin\u002Fpypylon       spinnaker_camera_driver\nVelodyne           Spinning LiDAR     velodyne_driver      velodyne\nOuster             Spinning LiDAR     ouster-sdk           ros2_ouster\nLivox              Solid-state LiDAR  livox_sdk            livox_ros2_driver\nUSB Webcam         RGB                OpenCV VideoCapture  usb_cam \u002F v4l2_camera\n```\n\n## Camera Models and Calibration\n\n### Pinhole Camera Model\n\n```\n                    3D World Point (X, Y, Z)\n                           |\n                    [R | t] — Extrinsic (world → camera)\n                           |\n                    Camera Point (Xc, Yc, Zc)\n                           |\n                    K — Intrinsic (camera → pixel)\n                           |\n                    Pixel (u, v)\n\nK = [ fx   0   cx ]      fx, fy = focal lengths (pixels)\n    [  0  fy   cy ]      cx, cy = principal point\n    [  0   0    1 ]\n\nProjection:  [u, v, 1]^T = K @ [R | t] @ [X, Y, Z, 1]^T\n```\n\n### Intrinsic Calibration\n\n```python\nimport cv2\nimport numpy as np\nfrom pathlib import Path\n\nclass IntrinsicCalibrator:\n    \"\"\"Camera intrinsic calibration using checkerboard pattern\"\"\"\n\n    def __init__(self, board_size=(9, 6), square_size_m=0.025):\n        self.board_size = board_size\n        self.square_size = square_size_m\n\n        # Prepare object points (3D coordinates of checkerboard corners)\n        self.objp = np.zeros((board_size[0] * board_size[1], 3), np.float32)\n        self.objp[:, :2] = np.mgrid[\n            0:board_size[0], 0:board_size[1]\n        ].T.reshape(-1, 2) * square_size_m\n\n    def collect_calibration_images(self, camera, num_images=30,\n                                    min_coverage=0.6):\n        \"\"\"Collect calibration images with good spatial coverage.\n\n        IMPORTANT: Move the board to cover all regions of the image,\n        including corners and edges. Tilt the board at various angles.\n        Bad coverage = bad calibration, especially at image edges.\n        \"\"\"\n        obj_points = []\n        img_points = []\n        coverage_map = np.zeros((4, 4), dtype=int)  # Track board positions\n\n        while len(obj_points) \u003C num_images:\n            frame = camera.capture()\n            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n            found, corners = cv2.findChessboardCorners(\n                gray, self.board_size,\n                cv2.CALIB_CB_ADAPTIVE_THRESH |\n                cv2.CALIB_CB_NORMALIZE_IMAGE |\n                cv2.CALIB_CB_FAST_CHECK\n            )\n\n            if found:\n                # Sub-pixel refinement — critical for accuracy\n                criteria = (cv2.TERM_CRITERIA_EPS +\n                           cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\n                corners = cv2.cornerSubPix(\n                    gray, corners, (11, 11), (-1, -1), criteria)\n\n                # Track coverage\n                center = corners.mean(axis=0).flatten()\n                grid_x = int(center[0] \u002F gray.shape[1] * 4)\n                grid_y = int(center[1] \u002F gray.shape[0] * 4)\n                grid_x = min(grid_x, 3)\n                grid_y = min(grid_y, 3)\n                coverage_map[grid_y, grid_x] += 1\n\n                obj_points.append(self.objp)\n                img_points.append(corners)\n\n        coverage = (coverage_map > 0).sum() \u002F coverage_map.size\n        if coverage \u003C min_coverage:\n            print(f\"WARNING: Only {coverage:.0%} coverage. \"\n                  f\"Move board to uncovered regions.\")\n\n        return obj_points, img_points, gray.shape[::-1]\n\n    def calibrate(self, obj_points, img_points, image_size):\n        \"\"\"Run calibration and return camera matrix + distortion coeffs\"\"\"\n        ret, K, dist, rvecs, tvecs = cv2.calibrateCamera(\n            obj_points, img_points, image_size, None, None)\n\n        if ret > 1.0:\n            print(f\"WARNING: High reprojection error ({ret:.3f} px). \"\n                  f\"Check image quality and board detection.\")\n\n        # Compute per-image reprojection errors\n        errors = []\n        for i in range(len(obj_points)):\n            projected, _ = cv2.projectPoints(\n                obj_points[i], rvecs[i], tvecs[i], K, dist)\n            err = cv2.norm(img_points[i], projected, cv2.NORM_L2)\n            err \u002F= len(projected)\n            errors.append(err)\n\n        print(f\"Calibration complete:\")\n        print(f\"  RMS reprojection error: {ret:.4f} px\")\n        print(f\"  Per-image errors: mean={np.mean(errors):.4f}, \"\n              f\"max={np.max(errors):.4f}\")\n        print(f\"  Focal length: fx={K[0,0]:.1f}, fy={K[1,1]:.1f}\")\n        print(f\"  Principal point: cx={K[0,2]:.1f}, cy={K[1,2]:.1f}\")\n\n        return CalibrationResult(\n            camera_matrix=K, dist_coeffs=dist,\n            rms_error=ret, image_size=image_size)\n\n    def save(self, result, path):\n        \"\"\"Save calibration to YAML (OpenCV-compatible format)\"\"\"\n        fs = cv2.FileStorage(str(path), cv2.FILE_STORAGE_WRITE)\n        fs.write(\"camera_matrix\", result.camera_matrix)\n        fs.write(\"dist_coeffs\", result.dist_coeffs)\n        fs.write(\"image_width\", result.image_size[0])\n        fs.write(\"image_height\", result.image_size[1])\n        fs.write(\"rms_error\", result.rms_error)\n        fs.release()\n\n    @staticmethod\n    def load(path):\n        \"\"\"Load calibration from YAML\"\"\"\n        fs = cv2.FileStorage(str(path), cv2.FILE_STORAGE_READ)\n        K = fs.getNode(\"camera_matrix\").mat()\n        dist = fs.getNode(\"dist_coeffs\").mat()\n        w = int(fs.getNode(\"image_width\").real())\n        h = int(fs.getNode(\"image_height\").real())\n        fs.release()\n        return CalibrationResult(\n            camera_matrix=K, dist_coeffs=dist,\n            image_size=(w, h), rms_error=0.0)\n```\n\n### Extrinsic Calibration (Camera-to-Camera, Camera-to-LiDAR)\n\n```python\nclass ExtrinsicCalibrator:\n    \"\"\"Compute transform between two sensors using shared targets\"\"\"\n\n    def calibrate_stereo(self, calib_left, calib_right,\n                          obj_points, img_points_left, img_points_right,\n                          image_size):\n        \"\"\"Stereo calibration: find relative pose between two cameras\"\"\"\n        ret, K1, d1, K2, d2, R, T, E, F = cv2.stereoCalibrate(\n            obj_points, img_points_left, img_points_right,\n            calib_left.camera_matrix, calib_left.dist_coeffs,\n            calib_right.camera_matrix, calib_right.dist_coeffs,\n            image_size,\n            flags=cv2.CALIB_FIX_INTRINSIC  # Use pre-calibrated intrinsics\n        )\n\n        print(f\"Stereo calibration RMS: {ret:.4f} px\")\n        print(f\"Baseline: {np.linalg.norm(T):.4f} m\")\n\n        return StereoCalibration(R=R, T=T, E=E, F=F, rms_error=ret)\n\n    def calibrate_camera_to_lidar(self, camera_points_2d,\n                                    lidar_points_3d, K, dist):\n        \"\"\"Find camera-to-LiDAR transform using corresponding points.\n\n        Use a calibration target visible to both sensors (e.g.,\n        checkerboard with reflective tape corners).\n        \"\"\"\n        # PnP: find pose of 3D points relative to camera\n        success, rvec, tvec = cv2.solvePnP(\n            lidar_points_3d, camera_points_2d, K, dist,\n            flags=cv2.SOLVEPNP_ITERATIVE\n        )\n\n        if not success:\n            raise CalibrationError(\"PnP failed — check point correspondences\")\n\n        R, _ = cv2.Rodrigues(rvec)\n        T_camera_lidar = np.eye(4)\n        T_camera_lidar[:3, :3] = R\n        T_camera_lidar[:3, 3] = tvec.flatten()\n\n        # Verify by reprojecting\n        projected, _ = cv2.projectPoints(\n            lidar_points_3d, rvec, tvec, K, dist)\n        error = np.mean(np.linalg.norm(\n            camera_points_2d - projected.reshape(-1, 2), axis=1))\n        print(f\"Camera-LiDAR reprojection error: {error:.2f} px\")\n\n        return T_camera_lidar\n```\n\n### Hand-Eye Calibration (Camera-to-Robot)\n\n```python\nclass HandEyeCalibrator:\n    \"\"\"Solve AX = XB for camera mounted on robot end-effector (eye-in-hand)\n    or camera mounted on a fixed base (eye-to-hand).\n\n    Requires moving the robot to multiple poses while observing a\n    fixed calibration target.\n    \"\"\"\n\n    def __init__(self, K, dist, board_size=(9, 6), square_size=0.025):\n        self.K = K\n        self.dist = dist\n        self.board_size = board_size\n        self.square_size = square_size\n        self.objp = np.zeros((board_size[0] * board_size[1], 3), np.float32)\n        self.objp[:, :2] = np.mgrid[\n            0:board_size[0], 0:board_size[1]\n        ].T.reshape(-1, 2) * square_size\n\n    def collect_poses(self, camera, robot, num_poses=20):\n        \"\"\"Collect camera-target and robot poses at multiple configurations.\n\n        IMPORTANT: Move to diverse robot orientations. At least 3 different\n        rotation axes. Pure translations are NOT sufficient.\n        \"\"\"\n        R_gripper2base = []\n        t_gripper2base = []\n        R_target2cam = []\n        t_target2cam = []\n\n        for i in range(num_poses):\n            input(f\"Move robot to pose {i+1}\u002F{num_poses}, press Enter...\")\n\n            # Get robot end-effector pose\n            ee_pose = robot.get_ee_pose()  # 4x4 homogeneous matrix\n            R_gripper2base.append(ee_pose[:3, :3])\n            t_gripper2base.append(ee_pose[:3, 3])\n\n            # Detect calibration target in camera\n            frame = camera.capture()\n            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n            found, corners = cv2.findChessboardCorners(\n                gray, self.board_size, None)\n\n            if not found:\n                print(f\"  Board not detected at pose {i+1}, skip.\")\n                continue\n\n            corners = cv2.cornerSubPix(\n                gray, corners, (11, 11), (-1, -1),\n                (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001))\n\n            ret, rvec, tvec = cv2.solvePnP(\n                self.objp, corners, self.K, self.dist)\n            R, _ = cv2.Rodrigues(rvec)\n            R_target2cam.append(R)\n            t_target2cam.append(tvec.flatten())\n\n        return (R_gripper2base, t_gripper2base,\n                R_target2cam, t_target2cam)\n\n    def calibrate_eye_in_hand(self, R_g2b, t_g2b, R_t2c, t_t2c):\n        \"\"\"Eye-in-hand: camera mounted on end-effector.\n        Solves for T_camera_to_gripper.\"\"\"\n        R, t = cv2.calibrateHandEye(\n            R_g2b, t_g2b, R_t2c, t_t2c,\n            method=cv2.CALIB_HAND_EYE_TSAI  # Also: PARK, HORAUD, DANIILIDIS\n        )\n        T_cam2gripper = np.eye(4)\n        T_cam2gripper[:3, :3] = R\n        T_cam2gripper[:3, 3] = t.flatten()\n        return T_cam2gripper\n\n    def calibrate_eye_to_hand(self, R_g2b, t_g2b, R_t2c, t_t2c):\n        \"\"\"Eye-to-hand: camera fixed in workspace.\n        Solves for T_camera_to_base.\"\"\"\n        # Invert robot poses (base-to-gripper → gripper-to-base)\n        R_b2g = [R.T for R in R_g2b]\n        t_b2g = [-R.T @ t for R, t in zip(R_g2b, t_g2b)]\n\n        R, t = cv2.calibrateHandEye(\n            R_b2g, t_b2g, R_t2c, t_t2c,\n            method=cv2.CALIB_HAND_EYE_TSAI\n        )\n        T_cam2base = np.eye(4)\n        T_cam2base[:3, :3] = R\n        T_cam2base[:3, 3] = t.flatten()\n        return T_cam2base\n\n    def verify_calibration(self, T_cam2ee, robot, camera, target_points_3d):\n        \"\"\"Verify by projecting a known 3D point through the full chain.\n        Error should be \u003C 5mm for manipulation tasks.\"\"\"\n        ee_pose = robot.get_ee_pose()\n        T_cam2base = ee_pose @ T_cam2ee\n\n        # Project world point to camera\n        point_in_cam = np.linalg.inv(T_cam2base) @ np.append(\n            target_points_3d[0], 1.0)\n        projected, _ = cv2.projectPoints(\n            point_in_cam[:3].reshape(1, 3),\n            np.zeros(3), np.zeros(3), self.K, self.dist)\n\n        print(f\"Verification projection: {projected.flatten()}\")\n        return projected.flatten()\n```\n\n### Calibration Quality Checklist\n\n```\n✅ Intrinsic calibration:\n   - RMS reprojection error \u003C 0.5 px (good), \u003C 0.3 px (excellent)\n   - ≥ 20 images with board covering full image area (corners + edges)\n   - Board tilted at multiple angles (not just fronto-parallel)\n   - Fixed focus \u002F fixed zoom during calibration AND operation\n\n✅ Extrinsic calibration (stereo \u002F camera-LiDAR):\n   - RMS \u003C 1.0 px for stereo\n   - Reprojection error \u003C 3 px for camera-LiDAR\n   - Verified with independent measurement (ruler \u002F known distance)\n\n✅ Hand-eye calibration:\n   - ≥ 15 poses with diverse orientations (≥ 3 rotation axes)\n   - Verification error \u003C 5mm for manipulation, \u003C 10mm for navigation\n   - Robot repeatability accounted for (UR5 ≈ ±0.03mm, low-cost ≈ ±1mm)\n\n⚠️  Recalibrate when:\n   - Camera is physically bumped or remounted\n   - Lens focus or zoom is changed\n   - Temperature changes significantly (thermal expansion shifts intrinsics)\n   - Robot is re-homed or joints are recalibrated\n```\n\n## Sensor Streaming Best Practices\n\n### Camera Streaming Architecture\n\n```python\nimport threading\nimport time\nfrom collections import deque\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nimport numpy as np\n\n@dataclass\nclass StampedFrame:\n    \"\"\"Frame with capture timestamp for synchronization\"\"\"\n    data: np.ndarray\n    timestamp: float          # time.monotonic() at capture\n    sequence: int             # Frame counter\n    sensor_id: str\n\nclass CameraStream:\n    \"\"\"Thread-safe camera streaming with bounded buffer.\n\n    Design principles:\n    1. Capture runs in a dedicated thread at sensor rate\n    2. Processing never blocks capture\n    3. Always use the LATEST frame (drop old ones for real-time)\n    4. Timestamp at capture, not at processing time\n    \"\"\"\n\n    def __init__(self, camera, buffer_size=2, name=\"camera\"):\n        self.camera = camera\n        self.name = name\n        self._buffer = deque(maxlen=buffer_size)\n        self._lock = threading.Lock()\n        self._new_frame = threading.Event()\n        self._running = False\n        self._sequence = 0\n        self._thread = None\n\n        # Diagnostics\n        self._capture_times = deque(maxlen=100)\n        self._drop_count = 0\n\n    def start(self):\n        \"\"\"Start capture thread\"\"\"\n        self._running = True\n        self._thread = threading.Thread(\n            target=self._capture_loop, daemon=True, name=f\"{self.name}_capture\")\n        self._thread.start()\n\n    def stop(self):\n        \"\"\"Stop capture thread\"\"\"\n        self._running = False\n        if self._thread:\n            self._thread.join(timeout=2.0)\n\n    def _capture_loop(self):\n        while self._running:\n            t_start = time.monotonic()\n\n            try:\n                raw = self.camera.capture()\n                timestamp = time.monotonic()  # Timestamp AFTER capture\n\n                frame = StampedFrame(\n                    data=raw,\n                    timestamp=timestamp,\n                    sequence=self._sequence,\n                    sensor_id=self.name\n                )\n                self._sequence += 1\n\n                with self._lock:\n                    if len(self._buffer) == self._buffer.maxlen:\n                        self._drop_count += 1\n                    self._buffer.append(frame)\n\n                self._new_frame.set()\n                self._capture_times.append(time.monotonic() - t_start)\n\n            except Exception as e:\n                print(f\"[{self.name}] Capture error: {e}\")\n                time.sleep(0.01)  # Back off on error\n\n    def get_latest(self) -> Optional[StampedFrame]:\n        \"\"\"Get most recent frame (non-blocking). Returns None if empty.\"\"\"\n        with self._lock:\n            if self._buffer:\n                return self._buffer[-1]\n        return None\n\n    def wait_for_frame(self, timeout=1.0) -> Optional[StampedFrame]:\n        \"\"\"Block until a new frame arrives\"\"\"\n        self._new_frame.clear()\n        if self._new_frame.wait(timeout=timeout):\n            return self.get_latest()\n        return None\n\n    def get_diagnostics(self) -> dict:\n        \"\"\"Streaming health metrics\"\"\"\n        if self._capture_times:\n            times = list(self._capture_times)\n            fps = 1.0 \u002F np.mean(times) if np.mean(times) > 0 else 0\n        else:\n            fps = 0\n        return {\n            \"sensor\": self.name,\n            \"fps\": round(fps, 1),\n            \"frames_captured\": self._sequence,\n            \"frames_dropped\": self._drop_count,\n            \"buffer_size\": len(self._buffer),\n            \"avg_capture_ms\": round(np.mean(times) * 1000, 1) if self._capture_times else 0,\n        }\n```\n\n### Multi-Sensor Synchronization\n\n```python\nclass SyncedMultiSensor:\n    \"\"\"Synchronize frames from multiple sensors by timestamp.\n\n    Uses nearest-neighbor matching within a time tolerance.\n    For hardware-synced sensors, use hardware trigger instead.\n    \"\"\"\n\n    def __init__(self, sensors: dict, max_time_diff_ms=33):\n        \"\"\"\n        Args:\n            sensors: {\"rgb\": CameraStream, \"depth\": CameraStream, ...}\n            max_time_diff_ms: Maximum allowed time difference between\n                              synced frames. Default 33ms (1 frame at 30Hz).\n        \"\"\"\n        self.sensors = sensors\n        self.max_dt = max_time_diff_ms \u002F 1000.0\n        self._synced_callback = None\n\n    def start(self):\n        for s in self.sensors.values():\n            s.start()\n\n    def stop(self):\n        for s in self.sensors.values():\n            s.stop()\n\n    def get_synced(self) -> Optional[dict]:\n        \"\"\"Get time-synchronized frames from all sensors.\n        Returns None if any sensor is missing or too far out of sync.\"\"\"\n        frames = {}\n        for name, stream in self.sensors.items():\n            frame = stream.get_latest()\n            if frame is None:\n                return None\n            frames[name] = frame\n\n        # Check time alignment against the first sensor\n        ref_time = list(frames.values())[0].timestamp\n        for name, frame in frames.items():\n            dt = abs(frame.timestamp - ref_time)\n            if dt > self.max_dt:\n                return None  # Out of sync\n\n        return frames\n\n    def get_synced_interpolated(self) -> Optional[dict]:\n        \"\"\"For sensors at different rates, interpolate to common timestamp.\n        Useful for IMU + camera fusion.\"\"\"\n        # Get latest from each sensor\n        frames = {}\n        for name, stream in self.sensors.items():\n            frame = stream.get_latest()\n            if frame is None:\n                return None\n            frames[name] = frame\n\n        # Use the SLOWEST sensor's timestamp as reference\n        ref_time = min(f.timestamp for f in frames.values())\n\n        result = {}\n        for name, frame in frames.items():\n            dt = frame.timestamp - ref_time\n            if abs(dt) \u003C= self.max_dt:\n                result[name] = frame\n            # For high-rate sensors (IMU), could interpolate here\n\n        return result if len(result) == len(self.sensors) else None\n```\n\n### Hardware-Triggered Synchronization\n\n```python\nclass HardwareSyncConfig:\n    \"\"\"Configure hardware trigger for multi-camera synchronization.\n\n    ALWAYS prefer hardware sync over software sync for:\n    - Stereo depth computation\n    - Multi-camera 3D reconstruction\n    - Fast-moving scenes\n\n    Common trigger methods:\n    - GPIO pulse from microcontroller (Arduino, ESP32)\n    - Camera's own sync output → other cameras' trigger input\n    - PTP (Precision Time Protocol) for GigE cameras\n    \"\"\"\n\n    @staticmethod\n    def setup_realsense_sync(master_serial, slave_serials):\n        \"\"\"Configure RealSense hardware sync (Inter-Cam sync mode)\"\"\"\n        import pyrealsense2 as rs\n\n        # Master camera: generates sync signal\n        master = rs.pipeline()\n        master_cfg = rs.config()\n        master_cfg.enable_device(master_serial)\n        master_sensor = master.start(master_cfg)\n\n        # Set master to mode 1 (master)\n        depth_sensor = master_sensor.get_device().first_depth_sensor()\n        depth_sensor.set_option(rs.option.inter_cam_sync_mode, 1)\n\n        # Slave cameras: receive sync signal\n        slaves = []\n        for serial in slave_serials:\n            pipe = rs.pipeline()\n            cfg = rs.config()\n            cfg.enable_device(serial)\n            profile = pipe.start(cfg)\n            sensor = profile.get_device().first_depth_sensor()\n            sensor.set_option(rs.option.inter_cam_sync_mode, 2)  # Slave\n            slaves.append(pipe)\n\n        return master, slaves\n\n    @staticmethod\n    def setup_ptp_sync(camera_ips):\n        \"\"\"Enable PTP synchronization for GigE Vision cameras.\n\n        Requires PTP-capable network switch.\n        Achieves \u003C 1μs sync accuracy.\n        \"\"\"\n        # Example with Basler\u002Fpylon cameras\n        # import pypylon.pylon as py\n        #\n        # for ip in camera_ips:\n        #     cam = py.InstantCamera(py.TlFactory.GetInstance()\n        #         .CreateDevice(py.CDeviceInfo().SetIpAddress(ip)))\n        #     cam.Open()\n        #     cam.GevIEEE1588.Value = True  # Enable PTP\n        #     cam.Close()\n        pass\n```\n\n### Streaming Anti-Patterns\n\n```python\n# ❌ BAD: Capture and process in same thread — limits to slowest operation\ndef bad_pipeline():\n    while True:\n        frame = camera.capture()           # 5ms\n        detections = model.detect(frame)   # 100ms\n        # Effective rate: ~9 FPS regardless of camera's 30 FPS\n\n# ✅ GOOD: Decouple capture from processing\ndef good_pipeline():\n    stream = CameraStream(camera)\n    stream.start()\n    while True:\n        frame = stream.get_latest()        # Always latest, non-blocking\n        if frame:\n            detections = model.detect(frame.data)  # 100ms\n            # Camera still capturing at 30 FPS in background\n            # Processing at ~10 FPS but always on freshest frame\n\n\n# ❌ BAD: Unbounded buffer — memory grows until OOM\nbuffer = []  # Will grow forever if consumer is slower than producer!\n\n# ✅ GOOD: Bounded buffer with drop policy\nbuffer = deque(maxlen=2)  # Keep latest 2, drop old automatically\n\n\n# ❌ BAD: Sleeping for frame timing\ntime.sleep(1.0 \u002F 30)  # Drift accumulates, doesn't account for jitter\n\n# ✅ GOOD: Event-driven or spin with wall clock\nframe = stream.wait_for_frame(timeout=0.1)\n\n\n# ❌ BAD: Timestamp at processing time\ndef process_callback(raw_data):\n    timestamp = time.time()  # WRONG: includes queue delay + scheduling\n    frame = decode(raw_data)\n    publish(frame, timestamp)\n\n# ✅ GOOD: Timestamp at capture time\ndef capture_thread():\n    raw_data = sensor.read()\n    timestamp = time.monotonic()  # RIGHT: timestamp at source\n    queue.put((raw_data, timestamp))\n```\n\n## RGB Processing Pipelines\n\n### Image Undistortion\n\n```python\nclass ImageUndistorter:\n    \"\"\"Pre-compute undistortion maps for fast runtime correction.\n\n    ALWAYS undistort before any geometric computation\n    (pose estimation, 3D reconstruction, visual servoing).\n    \"\"\"\n\n    def __init__(self, K, dist, image_size, alpha=0.0):\n        \"\"\"\n        Args:\n            alpha: 0.0 = crop all black pixels (default, recommended)\n                   1.0 = keep all pixels (shows black borders)\n        \"\"\"\n        self.new_K, self.roi = cv2.getOptimalNewCameraMatrix(\n            K, dist, image_size, alpha, image_size)\n\n        # Pre-compute maps (do this ONCE, not per frame)\n        self.map1, self.map2 = cv2.initUndistortRectifyMap(\n            K, dist, None, self.new_K, image_size, cv2.CV_16SC2)\n\n    def undistort(self, image):\n        \"\"\"Apply undistortion using pre-computed maps (fast)\"\"\"\n        return cv2.remap(image, self.map1, self.map2,\n                         interpolation=cv2.INTER_LINEAR)\n\n    def undistort_points(self, points_2d):\n        \"\"\"Undistort 2D point coordinates\"\"\"\n        return cv2.undistortPoints(\n            points_2d.reshape(-1, 1, 2).astype(np.float64),\n            self.K, self.dist, P=self.new_K\n        ).reshape(-1, 2)\n```\n\n### Object Detection Integration\n\n```python\nclass RobotObjectDetector:\n    \"\"\"Object detection for robotic manipulation.\n\n    Wraps a detection model with robotics-specific post-processing:\n    - Workspace filtering (ignore detections outside robot reach)\n    - Stability tracking (reject flickering detections)\n    - 3D pose estimation from 2D detections + depth\n    \"\"\"\n\n    def __init__(self, model, K, workspace_bounds=None, min_confidence=0.5):\n        self.model = model\n        self.K = K\n        self.workspace_bounds = workspace_bounds\n        self.min_confidence = min_confidence\n        self.tracker = DetectionTracker(max_age=5, min_hits=3)\n\n    def detect(self, rgb, depth=None) -> list:\n        \"\"\"Run detection with robotics post-processing\"\"\"\n        # Raw detection\n        raw_dets = self.model(rgb)\n\n        # Filter by confidence\n        dets = [d for d in raw_dets if d.confidence >= self.min_confidence]\n\n        # Estimate 3D position if depth is available\n        if depth is not None:\n            for det in dets:\n                det.position_3d = self._backproject(det.center, depth)\n\n                # Filter by workspace\n                if self.workspace_bounds and det.position_3d is not None:\n                    if not self.workspace_bounds.contains(det.position_3d):\n                        det.in_workspace = False\n                        continue\n                    det.in_workspace = True\n\n        # Track across frames for stability\n        tracked = self.tracker.update(dets)\n\n        return tracked\n\n    def _backproject(self, pixel, depth_image):\n        \"\"\"Convert 2D pixel + depth to 3D point in camera frame.\n\n        This is the INVERSE of projection:\n        X = (u - cx) * Z \u002F fx\n        Y = (v - cy) * Z \u002F fy\n        Z = depth\n        \"\"\"\n        u, v = int(pixel[0]), int(pixel[1])\n\n        # Sample depth with a small window (more robust than single pixel)\n        h, w = depth_image.shape[:2]\n        u = np.clip(u, 2, w - 3)\n        v = np.clip(v, 2, h - 3)\n        patch = depth_image[v-2:v+3, u-2:u+3]\n\n        # Use median to reject outliers (holes, edges)\n        valid = patch[patch > 0]\n        if len(valid) == 0:\n            return None\n        Z = np.median(valid)\n\n        # Convert from depth sensor units (often mm) to meters\n        if Z > 100:  # Likely millimeters\n            Z = Z \u002F 1000.0\n\n        fx, fy = self.K[0, 0], self.K[1, 1]\n        cx, cy = self.K[0, 2], self.K[1, 2]\n\n        X = (u - cx) * Z \u002F fx\n        Y = (v - cy) * Z \u002F fy\n\n        return np.array([X, Y, Z])\n```\n\n### Fiducial Marker Detection (AprilTag \u002F ArUco)\n\n```python\nclass FiducialDetector:\n    \"\"\"Detect and estimate pose of fiducial markers.\n\n    Use cases:\n    - Robot localization (known marker positions)\n    - Object pose estimation (marker attached to object)\n    - Calibration targets\n    - Sim-to-real ground truth\n    \"\"\"\n\n    def __init__(self, K, dist, marker_size_m=0.05,\n                 dictionary=cv2.aruco.DICT_APRILTAG_36h11):\n        self.K = K\n        self.dist = dist\n        self.marker_size = marker_size_m\n        self.aruco_dict = cv2.aruco.getPredefinedDictionary(dictionary)\n        self.params = cv2.aruco.DetectorParameters()\n        self.detector = cv2.aruco.ArucoDetector(self.aruco_dict, self.params)\n\n    def detect(self, image) -> list:\n        \"\"\"Detect markers and estimate their 6DOF poses\"\"\"\n        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n        corners, ids, rejected = self.detector.detectMarkers(gray)\n\n        results = []\n        if ids is not None:\n            for i, marker_id in enumerate(ids.flatten()):\n                # Estimate pose (rotation + translation)\n                rvecs, tvecs, _ = cv2.aruco.estimatePoseSingleMarkers(\n                    corners[i:i+1], self.marker_size, self.K, self.dist)\n\n                R, _ = cv2.Rodrigues(rvecs[0])\n                T = np.eye(4)\n                T[:3, :3] = R\n                T[:3, 3] = tvecs[0].flatten()\n\n                results.append(MarkerDetection(\n                    marker_id=int(marker_id),\n                    corners=corners[i].reshape(4, 2),\n                    pose=T,\n                    distance=np.linalg.norm(tvecs[0]),\n                ))\n\n        return results\n\n    def draw(self, image, detections):\n        \"\"\"Visualize detected markers with axes\"\"\"\n        vis = image.copy()\n        for det in detections:\n            cv2.aruco.drawDetectedMarkers(\n                vis, [det.corners.reshape(1, 4, 2)],\n                np.array([[det.marker_id]]))\n            rvec, _ = cv2.Rodrigues(det.pose[:3, :3])\n            cv2.drawFrameAxes(\n                vis, self.K, self.dist, rvec,\n                det.pose[:3, 3], self.marker_size * 0.5)\n        return vis\n```\n\n### Semantic Segmentation for Manipulation\n\n```python\nclass WorkspaceSegmenter:\n    \"\"\"Segment a robot's workspace into actionable regions.\n\n    Common segmentation targets for manipulation:\n    - Graspable objects vs background\n    - Table \u002F support surface\n    - Robot body (for self-collision avoidance)\n    - Free space vs obstacles\n    \"\"\"\n\n    def __init__(self, model, class_map):\n        self.model = model\n        self.class_map = class_map  # {0: 'background', 1: 'table', 2: 'object', ...}\n\n    def segment(self, rgb) -> SegmentationResult:\n        \"\"\"Run segmentation and extract per-class masks\"\"\"\n        mask = self.model.predict(rgb)  # (H, W) with class IDs\n\n        return SegmentationResult(\n            full_mask=mask,\n            object_mask=(mask == self.class_map['object']),\n            table_mask=(mask == self.class_map['table']),\n            free_space_mask=(mask == self.class_map['free_space']),\n        )\n\n    def get_grasp_candidates(self, rgb, depth, K):\n        \"\"\"Combine segmentation with depth to find graspable regions\"\"\"\n        seg = self.segment(rgb)\n\n        # Find connected components in object mask\n        num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(\n            seg.object_mask.astype(np.uint8))\n\n        candidates = []\n        for i in range(1, num_labels):  # Skip background (0)\n            component_mask = (labels == i)\n            area = stats[i, cv2.CC_STAT_AREA]\n\n            if area \u003C 100:  # Too small, likely noise\n                continue\n\n            # Get median depth of this object\n            obj_depths = depth[component_mask]\n            valid_depths = obj_depths[obj_depths > 0]\n            if len(valid_depths) == 0:\n                continue\n\n            center_px = centroids[i]\n            median_depth = np.median(valid_depths)\n\n            # Backproject center to 3D\n            fx, fy = K[0, 0], K[1, 1]\n            cx, cy = K[0, 2], K[1, 2]\n            X = (center_px[0] - cx) * median_depth \u002F fx\n            Y = (center_px[1] - cy) * median_depth \u002F fy\n\n            candidates.append(GraspCandidate(\n                position_3d=np.array([X, Y, median_depth]),\n                pixel_center=center_px,\n                mask=component_mask,\n                area_pixels=area,\n            ))\n\n        return candidates\n```\n\n## Depth Processing\n\n### Depth Map Filtering and Cleanup\n\n```python\nclass DepthProcessor:\n    \"\"\"Clean up raw depth maps for downstream use.\n\n    Raw depth from sensors is noisy: holes, flying pixels at edges,\n    multi-path interference, and range noise. Always filter before use.\n    \"\"\"\n\n    def __init__(self, depth_scale=0.001, min_depth_m=0.1, max_depth_m=3.0):\n        self.depth_scale = depth_scale  # Raw units to meters\n        self.min_depth = min_depth_m\n        self.max_depth = max_depth_m\n\n    def process(self, raw_depth) -> np.ndarray:\n        \"\"\"Full depth cleanup pipeline\"\"\"\n        depth = raw_depth.astype(np.float32) * self.depth_scale\n\n        # 1. Range filtering\n        depth[(depth \u003C self.min_depth) | (depth > self.max_depth)] = 0\n\n        # 2. Edge filtering — remove flying pixels at depth discontinuities\n        depth = self._remove_flying_pixels(depth)\n\n        # 3. Hole filling — fill small holes via inpainting\n        depth = self._fill_holes(depth, max_hole_size=10)\n\n        # 4. Spatial smoothing — bilateral filter preserves edges\n        depth = self._bilateral_filter(depth)\n\n        return depth\n\n    def _remove_flying_pixels(self, depth, threshold=0.05):\n        \"\"\"Remove pixels at depth discontinuities (flying pixels).\n        These are artifacts where the sensor interpolates between\n        foreground and background.\"\"\"\n        dx = np.abs(np.diff(depth, axis=1, prepend=0))\n        dy = np.abs(np.diff(depth, axis=0, prepend=0))\n        gradient = np.sqrt(dx**2 + dy**2)\n        depth[gradient > threshold] = 0\n        return depth\n\n    def _fill_holes(self, depth, max_hole_size=10):\n        \"\"\"Fill small holes using inpainting. Large holes remain as 0.\"\"\"\n        mask = (depth == 0).astype(np.uint8)\n\n        # Only fill small holes\n        kernel = np.ones((max_hole_size, max_hole_size), np.uint8)\n        small_holes = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)\n        small_holes = small_holes & mask\n\n        if small_holes.any():\n            # Normalize depth to uint16 for inpainting\n            d_norm = (depth * 1000).astype(np.uint16)\n            filled = cv2.inpaint(\n                d_norm, small_holes, max_hole_size, cv2.INPAINT_NS)\n            depth = np.where(small_holes, filled.astype(np.float32) \u002F 1000, depth)\n\n        return depth\n\n    def _bilateral_filter(self, depth, d=5, sigma_color=0.02, sigma_space=5):\n        \"\"\"Bilateral filter: smooths noise while preserving depth edges\"\"\"\n        # Convert to uint16 for cv2 bilateral (doesn't support float)\n        d_uint16 = (depth * 10000).astype(np.uint16)\n        filtered = cv2.bilateralFilter(d_uint16, d,\n                                        sigma_color * 10000, sigma_space)\n        return filtered.astype(np.float32) \u002F 10000\n```\n\n### Depth-to-Point Cloud Conversion\n\n```python\nclass DepthToPointCloud:\n    \"\"\"Convert depth images to organized and unorganized point clouds.\"\"\"\n\n    def __init__(self, K, image_size):\n        self.K = K\n        # Pre-compute pixel coordinate grid (do once, reuse every frame)\n        h, w = image_size[1], image_size[0]\n        u_coords, v_coords = np.meshgrid(np.arange(w), np.arange(h))\n        self.u = u_coords.astype(np.float32)\n        self.v = v_coords.astype(np.float32)\n        self.fx, self.fy = K[0, 0], K[1, 1]\n        self.cx, self.cy = K[0, 2], K[1, 2]\n\n    def convert(self, depth, rgb=None) -> np.ndarray:\n        \"\"\"Convert depth image to point cloud.\n\n        Returns:\n            points: (N, 3) or (N, 6) if rgb provided [x, y, z, r, g, b]\n        \"\"\"\n        # Backproject all pixels in parallel (vectorized)\n        Z = depth.astype(np.float32)\n        X = (self.u - self.cx) * Z \u002F self.fx\n        Y = (self.v - self.cy) * Z \u002F self.fy\n\n        # Stack into (H, W, 3) organized point cloud\n        points = np.stack([X, Y, Z], axis=-1)\n\n        # Filter invalid points\n        valid_mask = Z > 0\n        points_valid = points[valid_mask]\n\n        if rgb is not None:\n            colors = rgb[valid_mask].astype(np.float32) \u002F 255.0\n            return np.hstack([points_valid, colors])\n\n        return points_valid\n\n    def convert_organized(self, depth, rgb=None):\n        \"\"\"Return organized point cloud (H, W, 3) — preserves pixel layout.\n        Invalid points are NaN.\"\"\"\n        Z = depth.astype(np.float32)\n        X = (self.u - self.cx) * Z \u002F self.fx\n        Y = (self.v - self.cy) * Z \u002F self.fy\n\n        organized = np.stack([X, Y, Z], axis=-1)\n        organized[depth == 0] = np.nan\n\n        return organized\n```\n\n### RGBD Alignment\n\n```python\nclass RGBDAligner:\n    \"\"\"Align RGB and depth images from different sensors.\n\n    Most RGBD sensors (RealSense, ZED) provide built-in alignment.\n    Use this when combining separate RGB + depth cameras.\n    \"\"\"\n\n    def __init__(self, K_rgb, K_depth, T_depth_to_rgb, rgb_size, depth_size):\n        self.K_rgb = K_rgb\n        self.K_depth = K_depth\n        self.T = T_depth_to_rgb  # 4x4 transform: depth frame → rgb frame\n        self.rgb_size = rgb_size\n        self.depth_size = depth_size\n\n    def align_depth_to_rgb(self, depth):\n        \"\"\"Reproject depth image into RGB camera's frame.\n\n        For each pixel in depth image:\n        1. Backproject to 3D using depth intrinsics\n        2. Transform to RGB camera frame\n        3. Project to RGB pixel using RGB intrinsics\n        \"\"\"\n        h_d, w_d = depth.shape\n        h_r, w_r = self.rgb_size[1], self.rgb_size[0]\n        aligned = np.zeros((h_r, w_r), dtype=np.float32)\n\n        # Backproject depth pixels to 3D\n        v_d, u_d = np.mgrid[0:h_d, 0:w_d].astype(np.float32)\n        Z = depth.astype(np.float32)\n        valid = Z > 0\n\n        X = (u_d[valid] - self.K_depth[0, 2]) * Z[valid] \u002F self.K_depth[0, 0]\n        Y = (v_d[valid] - self.K_depth[1, 2]) * Z[valid] \u002F self.K_depth[1, 1]\n        pts_3d = np.stack([X, Y, Z[valid], np.ones_like(X)], axis=0)\n\n        # Transform to RGB frame\n        pts_rgb = self.T @ pts_3d\n\n        # Project to RGB pixels\n        u_r = (self.K_rgb[0, 0] * pts_rgb[0] \u002F pts_rgb[2] +\n               self.K_rgb[0, 2]).astype(int)\n        v_r = (self.K_rgb[1, 1] * pts_rgb[1] \u002F pts_rgb[2] +\n               self.K_rgb[1, 2]).astype(int)\n\n        # Fill aligned depth (z-buffer for occlusion handling)\n        in_bounds = (u_r >= 0) & (u_r \u003C w_r) & (v_r >= 0) & (v_r \u003C h_r)\n        for u, v, z in zip(u_r[in_bounds], v_r[in_bounds],\n                           pts_rgb[2][in_bounds]):\n            if aligned[v, u] == 0 or z \u003C aligned[v, u]:\n                aligned[v, u] = z\n\n        return aligned\n```\n\n## Point Cloud Processing\n\n### Filtering and Downsampling\n\n```python\nimport open3d as o3d\n\nclass PointCloudProcessor:\n    \"\"\"Point cloud processing pipeline using Open3D.\n\n    Pipeline order matters:\n    1. Crop to region of interest (reduces data volume first)\n    2. Remove statistical outliers\n    3. Downsample (voxel grid)\n    4. Estimate normals\n    5. Application-specific processing\n    \"\"\"\n\n    def preprocess(self, points, colors=None,\n                   workspace_bounds=None, voxel_size=0.005):\n        \"\"\"Standard preprocessing pipeline\"\"\"\n        pcd = o3d.geometry.PointCloud()\n        pcd.points = o3d.utility.Vector3dVector(points[:, :3])\n        if colors is not None:\n            pcd.colors = o3d.utility.Vector3dVector(colors)\n\n        # 1. Crop to workspace\n        if workspace_bounds:\n            bbox = o3d.geometry.AxisAlignedBoundingBox(\n                min_bound=workspace_bounds['min'],\n                max_bound=workspace_bounds['max'])\n            pcd = pcd.crop(bbox)\n\n        # 2. Statistical outlier removal\n        pcd, inlier_idx = pcd.remove_statistical_outlier(\n            nb_neighbors=20, std_ratio=2.0)\n\n        # 3. Voxel downsampling\n        pcd = pcd.voxel_down_sample(voxel_size=voxel_size)\n\n        # 4. Normal estimation\n        pcd.estimate_normals(\n            search_param=o3d.geometry.KDTreeSearchParamHybrid(\n                radius=voxel_size * 4, max_nn=30))\n        # Orient normals toward camera\n        pcd.orient_normals_towards_camera_location(\n            camera_location=np.array([0, 0, 0]))\n\n        return pcd\n\n    def segment_plane(self, pcd, distance_threshold=0.005,\n                      ransac_n=3, num_iterations=1000):\n        \"\"\"Segment the dominant plane (table \u002F floor) using RANSAC.\n        Returns plane model and inlier\u002Foutlier point clouds.\"\"\"\n        plane_model, inliers = pcd.segment_plane(\n            distance_threshold=distance_threshold,\n            ransac_n=ransac_n,\n            num_iterations=num_iterations)\n\n        plane_cloud = pcd.select_by_index(inliers)\n        objects_cloud = pcd.select_by_index(inliers, invert=True)\n\n        a, b, c, d = plane_model\n        print(f\"Plane: {a:.3f}x + {b:.3f}y + {c:.3f}z + {d:.3f} = 0\")\n\n        return plane_model, plane_cloud, objects_cloud\n\n    def cluster_objects(self, pcd, eps=0.02, min_points=50):\n        \"\"\"Cluster point cloud into individual objects using DBSCAN\"\"\"\n        labels = np.array(pcd.cluster_dbscan(\n            eps=eps, min_points=min_points, print_progress=False))\n\n        clusters = []\n        for label_id in range(labels.max() + 1):\n            cluster_mask = labels == label_id\n            cluster_pcd = pcd.select_by_index(\n                np.where(cluster_mask)[0])\n\n            bbox = cluster_pcd.get_axis_aligned_bounding_box()\n            center = bbox.get_center()\n            extent = bbox.get_extent()\n\n            clusters.append(PointCloudCluster(\n                cloud=cluster_pcd,\n                centroid=center,\n                extent=extent,\n                num_points=cluster_mask.sum(),\n                bbox=bbox,\n            ))\n\n        # Sort by size (largest first)\n        clusters.sort(key=lambda c: c.num_points, reverse=True)\n        return clusters\n```\n\n### Point Cloud Registration (ICP)\n\n```python\nclass PointCloudRegistration:\n    \"\"\"Align two point clouds using ICP and its variants.\n\n    Use cases:\n    - Multi-view reconstruction (combine views from different poses)\n    - Object model matching (align scan to CAD model)\n    - LiDAR odometry (align consecutive scans)\n    - Bin picking (match object template to scene)\n    \"\"\"\n\n    def align_icp(self, source, target, initial_transform=np.eye(4),\n                  max_distance=0.05, method='point_to_plane'):\n        \"\"\"Iterative Closest Point alignment.\n\n        Args:\n            source: point cloud to align\n            target: reference point cloud\n            initial_transform: starting guess (CRITICAL for convergence)\n            max_distance: max correspondence distance\n            method: 'point_to_point' or 'point_to_plane'\n        \"\"\"\n        if method == 'point_to_plane':\n            # Point-to-plane converges faster but needs normals\n            if not target.has_normals():\n                target.estimate_normals(\n                    search_param=o3d.geometry.KDTreeSearchParamHybrid(\n                        radius=0.05, max_nn=30))\n            estimation = o3d.pipelines.registration.TransformationEstimationPointToPlane()\n        else:\n            estimation = o3d.pipelines.registration.TransformationEstimationPointToPoint()\n\n        result = o3d.pipelines.registration.registration_icp(\n            source, target, max_distance, initial_transform,\n            estimation,\n            o3d.pipelines.registration.ICPConvergenceCriteria(\n                max_iteration=100,\n                relative_fitness=1e-6,\n                relative_rmse=1e-6))\n\n        print(f\"ICP fitness: {result.fitness:.4f}, \"\n              f\"RMSE: {result.inlier_rmse:.6f}\")\n\n        if result.fitness \u003C 0.3:\n            print(\"WARNING: Low fitness — ICP likely failed. \"\n                  \"Check initial alignment or increase max_distance.\")\n\n        return result.transformation, result\n\n    def align_global(self, source, target, voxel_size=0.01):\n        \"\"\"Global registration (no initial guess needed).\n        Use FPFH features + RANSAC for coarse alignment,\n        then refine with ICP.\"\"\"\n\n        # Downsample for feature computation\n        source_down = source.voxel_down_sample(voxel_size)\n        target_down = target.voxel_down_sample(voxel_size)\n\n        # Compute normals\n        for pcd in [source_down, target_down]:\n            pcd.estimate_normals(\n                o3d.geometry.KDTreeSearchParamHybrid(\n                    radius=voxel_size * 2, max_nn=30))\n\n        # Compute FPFH features\n        source_fpfh = o3d.pipelines.registration.compute_fpfh_feature(\n            source_down,\n            o3d.geometry.KDTreeSearchParamHybrid(\n                radius=voxel_size * 5, max_nn=100))\n        target_fpfh = o3d.pipelines.registration.compute_fpfh_feature(\n            target_down,\n            o3d.geometry.KDTreeSearchParamHybrid(\n                radius=voxel_size * 5, max_nn=100))\n\n        # RANSAC-based global registration\n        coarse = o3d.pipelines.registration.registration_ransac_based_on_feature_matching(\n            source_down, target_down, source_fpfh, target_fpfh,\n            mutual_filter=True,\n            max_correspondence_distance=voxel_size * 2,\n            estimation_method=o3d.pipelines.registration.TransformationEstimationPointToPoint(),\n            ransac_n=3,\n            checkers=[\n                o3d.pipelines.registration.CorrespondenceCheckerBasedOnEdgeLength(0.9),\n                o3d.pipelines.registration.CorrespondenceCheckerBasedOnDistance(voxel_size * 2),\n            ],\n            criteria=o3d.pipelines.registration.RANSACConvergenceCriteria(100000, 0.999))\n\n        # Refine with ICP\n        refined, _ = self.align_icp(\n            source, target,\n            initial_transform=coarse.transformation,\n            max_distance=voxel_size * 1.5,\n            method='point_to_plane')\n\n        return refined\n```\n\n## Multi-Sensor Fusion\n\n### Perception Fusion Architecture\n\n```\n┌──────────────┐    ┌──────────────┐    ┌──────────────┐\n│  RGB Camera  │    │ Depth Sensor │    │    LiDAR     │\n│   30 Hz      │    │   30 Hz      │    │   10 Hz      │\n└──────┬───────┘    └──────┬───────┘    └──────┬───────┘\n       │                   │                   │\n       ▼                   ▼                   ▼\n┌──────────────┐    ┌──────────────┐    ┌──────────────┐\n│  Detection   │    │    Depth     │    │ Point Cloud  │\n│  + Segment   │    │  Filtering   │    │  Processing  │\n└──────┬───────┘    └──────┬───────┘    └──────┬───────┘\n       │                   │                   │\n       └───────────┬───────┘───────────────────┘\n                   ▼\n          ┌────────────────┐\n          │  Fusion Layer  │\n          │  (association  │\n          │   + tracking)  │\n          └────────┬───────┘\n                   ▼\n          ┌────────────────┐\n          │  World Model   │\n          │  (tracked      │\n          │   objects)     │\n          └────────────────┘\n```\n\n### Camera + LiDAR Fusion\n\n```python\nclass CameraLiDARFusion:\n    \"\"\"Project LiDAR points into camera image for cross-modal association.\n\n    Two fusion strategies:\n    1. Early fusion: Project LiDAR → camera, combine at data level\n    2. Late fusion: Detect in each modality, associate results\n\n    Early fusion is simpler and recommended when sensors are calibrated.\n    \"\"\"\n\n    def __init__(self, K, T_lidar_to_camera, image_size):\n        self.K = K\n        self.T = T_lidar_to_camera  # 4x4 transform\n        self.image_size = image_size  # (w, h)\n\n    def project_lidar_to_image(self, lidar_points):\n        \"\"\"Project 3D LiDAR points to 2D image pixels.\n\n        Returns:\n            pixels: (N, 2) pixel coordinates\n            depths: (N,) depth values\n            valid_mask: (N,) bool — True if point projects into image\n        \"\"\"\n        N = len(lidar_points)\n        # Homogeneous coordinates\n        pts_h = np.hstack([lidar_points[:, :3], np.ones((N, 1))])\n\n        # Transform to camera frame\n        pts_cam = (self.T @ pts_h.T).T\n\n        # Points behind camera\n        valid = pts_cam[:, 2] > 0\n        depths = pts_cam[:, 2]\n\n        # Project to pixels\n        pixels = np.zeros((N, 2))\n        pixels[:, 0] = self.K[0, 0] * pts_cam[:, 0] \u002F pts_cam[:, 2] + self.K[0, 2]\n        pixels[:, 1] = self.K[1, 1] * pts_cam[:, 1] \u002F pts_cam[:, 2] + self.K[1, 2]\n\n        # Check image bounds\n        w, h = self.image_size\n        valid &= (pixels[:, 0] >= 0) & (pixels[:, 0] \u003C w)\n        valid &= (pixels[:, 1] >= 0) & (pixels[:, 1] \u003C h)\n\n        return pixels, depths, valid\n\n    def colorize_pointcloud(self, lidar_points, rgb_image):\n        \"\"\"Paint LiDAR points with RGB colors from camera image\"\"\"\n        pixels, depths, valid = self.project_lidar_to_image(lidar_points)\n\n        colors = np.zeros((len(lidar_points), 3), dtype=np.float32)\n        valid_px = pixels[valid].astype(int)\n        colors[valid] = rgb_image[valid_px[:, 1], valid_px[:, 0]] \u002F 255.0\n\n        return colors, valid\n\n    def enrich_detections(self, detections_2d, lidar_points):\n        \"\"\"Add 3D information to 2D camera detections using LiDAR.\n\n        For each 2D bounding box, find LiDAR points that project\n        inside it, and compute the 3D centroid.\n        \"\"\"\n        pixels, depths, valid = self.project_lidar_to_image(lidar_points)\n\n        enriched = []\n        for det in detections_2d:\n            x1, y1, x2, y2 = det.bbox\n\n            # Find LiDAR points inside this bounding box\n            in_box = (valid &\n                      (pixels[:, 0] >= x1) & (pixels[:, 0] \u003C= x2) &\n                      (pixels[:, 1] >= y1) & (pixels[:, 1] \u003C= y2))\n\n            if in_box.sum() > 3:\n                # Use LiDAR points for 3D position (more accurate than depth camera)\n                box_points = lidar_points[in_box]\n\n                # Median is robust to outliers from other objects\n                position_3d = np.median(box_points[:, :3], axis=0)\n                det.position_3d = position_3d\n                det.num_lidar_points = in_box.sum()\n                det.has_3d = True\n            else:\n                det.has_3d = False\n\n            enriched.append(det)\n\n        return enriched\n```\n\n### Multi-Object Tracking\n\n```python\nclass PerceptionTracker:\n    \"\"\"Track detected objects across frames for temporal consistency.\n\n    Why tracking matters in robotics:\n    - Detections flicker (present one frame, absent the next)\n    - Robot needs consistent object IDs for manipulation\n    - Velocity estimation requires temporal association\n    - Occlusion handling prevents phantom disappearances\n    \"\"\"\n\n    def __init__(self, max_age=5, min_hits=3, iou_threshold=0.3):\n        self.max_age = max_age            # Frames before deleting lost track\n        self.min_hits = min_hits          # Frames before confirming track\n        self.iou_threshold = iou_threshold\n        self.tracks = {}\n        self.next_id = 0\n\n    def update(self, detections) -> list:\n        \"\"\"Associate detections with existing tracks.\n\n        Uses Hungarian algorithm for optimal assignment.\n        \"\"\"\n        if not self.tracks:\n            # First frame: create tracks for all detections\n            for det in detections:\n                self._create_track(det)\n            return list(self.tracks.values())\n\n        # Compute cost matrix (IoU for 2D, Euclidean for 3D)\n        track_list = list(self.tracks.values())\n        cost_matrix = self._compute_cost_matrix(track_list, detections)\n\n        # Hungarian assignment\n        from scipy.optimize import linear_sum_assignment\n        row_idx, col_idx = linear_sum_assignment(cost_matrix)\n\n        matched = set()\n        for r, c in zip(row_idx, col_idx):\n            if cost_matrix[r, c] \u003C self.iou_threshold:\n                track_list[r].update(detections[c])\n                matched.add(c)\n\n        # Create new tracks for unmatched detections\n        for i, det in enumerate(detections):\n            if i not in matched:\n                self._create_track(det)\n\n        # Age out old tracks\n        stale = [tid for tid, t in self.tracks.items()\n                 if t.age > self.max_age]\n        for tid in stale:\n            del self.tracks[tid]\n\n        # Return confirmed tracks only\n        return [t for t in self.tracks.values()\n                if t.hits >= self.min_hits]\n\n    def _create_track(self, detection):\n        track = Track(\n            track_id=self.next_id,\n            detection=detection,\n            hits=1, age=0)\n        self.tracks[self.next_id] = track\n        self.next_id += 1\n\n    def _compute_cost_matrix(self, tracks, detections):\n        n_tracks = len(tracks)\n        n_dets = len(detections)\n        cost = np.ones((n_tracks, n_dets))\n\n        for i, track in enumerate(tracks):\n            for j, det in enumerate(detections):\n                if hasattr(det, 'position_3d') and det.position_3d is not None:\n                    # 3D Euclidean distance (preferred)\n                    dist = np.linalg.norm(\n                        track.position_3d - det.position_3d)\n                    cost[i, j] = dist\n                else:\n                    # 2D IoU\n                    cost[i, j] = 1.0 - self._iou(track.bbox, det.bbox)\n\n        return cost\n\n    @staticmethod\n    def _iou(box1, box2):\n        x1 = max(box1[0], box2[0])\n        y1 = max(box1[1], box2[1])\n        x2 = min(box1[2], box2[2])\n        y2 = min(box1[3], box2[3])\n        inter = max(0, x2 - x1) * max(0, y2 - y1)\n        area1 = (box1[2] - box1[0]) * (box1[3] - box1[1])\n        area2 = (box2[2] - box2[0]) * (box2[3] - box2[1])\n        return inter \u002F (area1 + area2 - inter + 1e-6)\n```\n\n## Perception Latency Budget\n\n```\nComponent                   Typical Latency    Budget Target\n───────────────────────────────────────────────────────────────\nSensor capture              1-10 ms            —\nImage transfer (USB3)       2-5 ms             —\nUndistortion                1-2 ms             \u003C 3 ms\nDetection (GPU)             10-50 ms           \u003C 30 ms\nDetection (CPU)             50-500 ms          \u003C 100 ms\nDepth processing            2-5 ms             \u003C 5 ms\nPoint cloud generation      3-10 ms            \u003C 10 ms\nSegmentation (GPU)          15-40 ms           \u003C 30 ms\nTracking update             0.5-2 ms           \u003C 2 ms\n3D pose estimation          5-20 ms            \u003C 15 ms\n───────────────────────────────────────────────────────────────\nTOTAL PIPELINE              ~50-150 ms         \u003C 100 ms target\n\nFor 10 Hz perception: budget = 100 ms per frame\nFor 30 Hz perception: budget = 33 ms per frame\n\nRULE: Perception latency + planning latency \u003C control period\n      If control runs at 100 Hz (10 ms), perception must be\n      pipelined — process frame N while control uses frame N-1.\n```\n\n## Perception Anti-Patterns\n\n### 1. Processing Every Frame When You Don't Need To\n```python\n# ❌ BAD: Running heavy detection at sensor framerate\ndef callback(self, msg):\n    detections = self.heavy_model(msg)  # 100ms on every 30Hz frame\n\n# ✅ GOOD: Decimate or skip frames\ndef callback(self, msg):\n    self.frame_count += 1\n    if self.frame_count % 3 != 0:  # Process every 3rd frame\n        return\n    detections = self.heavy_model(msg)\n```\n\n### 2. Not Validating Depth Values\n```python\n# ❌ BAD: Using raw depth blindly\nz = depth_image[v, u]\npoint_3d = backproject(u, v, z)  # z might be 0 (hole) or 65535 (invalid)\n\n# ✅ GOOD: Always validate depth\nz = depth_image[v, u]\nif z \u003C= 0 or z > max_range:\n    return None\nz_meters = z * depth_scale\n```\n\n### 3. Assuming Cameras Are Calibrated\n```python\n# ❌ BAD: Using default\u002Fnominal intrinsics\nK = np.array([[600, 0, 320], [0, 600, 240], [0, 0, 1]])  # Guess\n\n# ✅ GOOD: Load actual calibration\nK = load_calibration(\"camera_serial_12345.yaml\").camera_matrix\n```\n\n### 4. Ignoring Sensor Warmup\n```python\n# ❌ BAD: Using first frames from sensor\ncamera.start()\nframe = camera.capture()  # Often overexposed, auto-exposure not settled\n\n# ✅ GOOD: Discard initial frames\ncamera.start()\nfor _ in range(30):  # Let auto-exposure settle (~1 second at 30Hz)\n    camera.capture()\nframe = camera.capture()  # Now usable\n```\n\n### 5. Single-Pixel Depth Sampling\n```python\n# ❌ BAD: Single pixel is noisy and may be a hole\nz = depth[int(center_y), int(center_x)]\n\n# ✅ GOOD: Sample a neighborhood, use median\npatch = depth[cy-3:cy+4, cx-3:cx+4]\nvalid = patch[patch > 0]\nz = np.median(valid) if len(valid) > 0 else None\n```\n\n### 6. Not Handling Coordinate Frame Transforms\n```python\n# ❌ BAD: Assuming everything is in the same frame\nobject_position = detection.position  # In camera frame? Robot frame? World frame?\nrobot.move_to(object_position)        # Which frame does move_to expect?\n\n# ✅ GOOD: Explicit frame tracking\nobject_in_camera = detection.position_3d       # Camera frame\nobject_in_base = T_base_camera @ np.append(object_in_camera, 1.0)  # Robot frame\nrobot.move_to(object_in_base[:3])\n```\n\n## Production Perception Checklist\n\n1. **Calibrate before deploying** — intrinsics, extrinsics, hand-eye\n2. **Validate calibration** with independent measurements\n3. **Set sensor exposure** appropriately — auto-exposure can cause detection flicker\n4. **Undistort** before any geometric computation\n5. **Filter depth** — remove flying pixels, fill small holes\n6. **Timestamp at capture** — not at processing time\n7. **Track objects** across frames — don't rely on single-frame detections\n8. **Handle sensor failures** — missing frames, degraded depth, overexposure\n9. **Log perception output** — bounding boxes, confidence scores, 3D positions\n10. **Benchmark latency** — measure each pipeline stage, find bottlenecks\n11. **Test with edge cases** — empty scenes, cluttered scenes, reflective surfaces, direct sunlight\n12. **Version your models** — pin detection\u002Fsegmentation model versions in deployment\n\n","# Robot Perception Skill\n\n## When to Use This Skill\n- Setting up and configuring camera, LiDAR, or depth sensors\n- Building RGB, depth, or point cloud processing pipelines\n- Calibrating cameras (intrinsic, extrinsic, hand-eye)\n- Implementing object detection, segmentation, or tracking for robots\n- Fusing data from multiple sensor modalities\n- Streaming sensor data with proper threading and buffering\n- Synchronizing multi-sensor rigs\n- Deploying perception models on robot hardware (GPU, edge)\n- Debugging perception failures (latency, dropped frames, misalignment)\n\n## Sensor Landscape\n\n### Sensor Types and Characteristics\n\n```\nSensor Type        Output              Range       Rate     Best For\n─────────────────────────────────────────────────────────────────────────\nRGB Camera         (H,W,3) uint8       ∞           30-120Hz Object detection, tracking, visual servoing\nStereo Camera      (H,W,3)+(H,W,3)    0.3-20m     30-90Hz  Dense depth from passive stereo\nStructured Light   (H,W) float + RGB   0.2-10m     30Hz     Indoor manipulation, short range\nToF Depth          (H,W) float + RGB   0.1-10m     30Hz     Indoor, medium range\nLiDAR (spinning)   (N,3) or (N,4)     0.5-200m    10-20Hz  Outdoor navigation, mapping\nLiDAR (solid-st.)  (N,3)              0.5-200m    10-30Hz  Automotive, outdoor\nIMU                (6,) or (9,)        N\u002FA         200-1kHz Orientation, motion estimation\nForce\u002FTorque       (6,) float          N\u002FA         1kHz+    Contact detection, force control\nTactile            (H,W) or (N,3)      Contact     30-100Hz Grasp quality, texture\nEvent Camera       Events (x,y,t,p)    ∞           μs       High-speed tracking, HDR scenes\n```\n\n### Common Sensor Hardware\n\n```\nDevice             Type               SDK\u002FDriver           ROS2 Package\n──────────────────────────────────────────────────────────────────────────\nIntel RealSense    Structured Light   pyrealsense2         realsense2_camera\nStereolabs ZED     Stereo + IMU       pyzed                zed_wrapper\nLuxonis OAK-D      Stereo + Neural    depthai              depthai_ros\nFLIR\u002FBasler        Industrial RGB     PySpin\u002Fpypylon       spinnaker_camera_driver\nVelodyne           Spinning LiDAR     velodyne_driver      velodyne\nOuster             Spinning LiDAR     ouster-sdk           ros2_ouster\nLivox              Solid-state LiDAR  livox_sdk            livox_ros2_driver\nUSB Webcam         RGB                OpenCV VideoCapture  usb_cam \u002F v4l2_camera\n```\n\n## Camera Models and Calibration\n\n### Pinhole Camera Model\n\n```\n                    3D World Point (X, Y, Z)\n                           |\n                    [R | t] — Extrinsic (world → camera)\n                           |\n                    Camera Point (Xc, Yc, Zc)\n                           |\n                    K — Intrinsic (camera → pixel)\n                           |\n                    Pixel (u, v)\n\nK = [ fx   0   cx ]      fx, fy = focal lengths (pixels)\n    [  0  fy   cy ]      cx, cy = principal point\n    [  0   0    1 ]\n\nProjection:  [u, v, 1]^T = K @ [R | t] @ [X, Y, Z, 1]^T\n```\n\n### Intrinsic Calibration\n\n```python\nimport cv2\nimport numpy as np\nfrom pathlib import Path\n\nclass IntrinsicCalibrator:\n    \"\"\"Camera intrinsic calibration using checkerboard pattern\"\"\"\n\n    def __init__(self, board_size=(9, 6), square_size_m=0.025):\n        self.board_size = board_size\n        self.square_size = square_size_m\n\n        # Prepare object points (3D coordinates of checkerboard corners)\n        self.objp = np.zeros((board_size[0] * board_size[1], 3), np.float32)\n        self.objp[:, :2] = np.mgrid[\n            0:board_size[0], 0:board_size[1]\n        ].T.reshape(-1, 2) * square_size_m\n\n    def collect_calibration_images(self, camera, num_images=30,\n                                    min_coverage=0.6):\n        \"\"\"Collect calibration images with good spatial coverage.\n\n        IMPORTANT: Move the board to cover all regions of the image,\n        including corners and edges. Tilt the board at various angles.\n        Bad coverage = bad calibration, especially at image edges.\n        \"\"\"\n        obj_points = []\n        img_points = []\n        coverage_map = np.zeros((4, 4), dtype=int)  # Track board positions\n\n        while len(obj_points) \u003C num_images:\n            frame = camera.capture()\n            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n            found, corners = cv2.findChessboardCorners(\n                gray, self.board_size,\n                cv2.CALIB_CB_ADAPTIVE_THRESH |\n                cv2.CALIB_CB_NORMALIZE_IMAGE |\n                cv2.CALIB_CB_FAST_CHECK\n            )\n\n            if found:\n                # Sub-pixel refinement — critical for accuracy\n                criteria = (cv2.TERM_CRITERIA_EPS +\n                           cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\n                corners = cv2.cornerSubPix(\n                    gray, corners, (11, 11), (-1, -1), criteria)\n\n                # Track coverage\n                center = corners.mean(axis=0).flatten()\n                grid_x = int(center[0] \u002F gray.shape[1] * 4)\n                grid_y = int(center[1] \u002F gray.shape[0] * 4)\n                grid_x = min(grid_x, 3)\n                grid_y = min(grid_y, 3)\n                coverage_map[grid_y, grid_x] += 1\n\n                obj_points.append(self.objp)\n                img_points.append(corners)\n\n        coverage = (coverage_map > 0).sum() \u002F coverage_map.size\n        if coverage \u003C min_coverage:\n            print(f\"WARNING: Only {coverage:.0%} coverage. \"\n                  f\"Move board to uncovered regions.\")\n\n        return obj_points, img_points, gray.shape[::-1]\n\n    def calibrate(self, obj_points, img_points, image_size):\n        \"\"\"Run calibration and return camera matrix + distortion coeffs\"\"\"\n        ret, K, dist, rvecs, tvecs = cv2.calibrateCamera(\n            obj_points, img_points, image_size, None, None)\n\n        if ret > 1.0:\n            print(f\"WARNING: High reprojection error ({ret:.3f} px). \"\n                  f\"Check image quality and board detection.\")\n\n        # Compute per-image reprojection errors\n        errors = []\n        for i in range(len(obj_points)):\n            projected, _ = cv2.projectPoints(\n                obj_points[i], rvecs[i], tvecs[i], K, dist)\n            err = cv2.norm(img_points[i], projected, cv2.NORM_L2)\n            err \u002F= len(projected)\n            errors.append(err)\n\n        print(f\"Calibration complete:\")\n        print(f\"  RMS reprojection error: {ret:.4f} px\")\n        print(f\"  Per-image errors: mean={np.mean(errors):.4f}, \"\n              f\"max={np.max(errors):.4f}\")\n        print(f\"  Focal length: fx={K[0,0]:.1f}, fy={K[1,1]:.1f}\")\n        print(f\"  Principal point: cx={K[0,2]:.1f}, cy={K[1,2]:.1f}\")\n\n        return CalibrationResult(\n            camera_matrix=K, dist_coeffs=dist,\n            rms_error=ret, image_size=image_size)\n\n    def save(self, result, path):\n        \"\"\"Save calibration to YAML (OpenCV-compatible format)\"\"\"\n        fs = cv2.FileStorage(str(path), cv2.FILE_STORAGE_WRITE)\n        fs.write(\"camera_matrix\", result.camera_matrix)\n        fs.write(\"dist_coeffs\", result.dist_coeffs)\n        fs.write(\"image_width\", result.image_size[0])\n        fs.write(\"image_height\", result.image_size[1])\n        fs.write(\"rms_error\", result.rms_error)\n        fs.release()\n\n    @staticmethod\n    def load(path):\n        \"\"\"Load calibration from YAML\"\"\"\n        fs = cv2.FileStorage(str(path), cv2.FILE_STORAGE_READ)\n        K = fs.getNode(\"camera_matrix\").mat()\n        dist = fs.getNode(\"dist_coeffs\").mat()\n        w = int(fs.getNode(\"image_width\").real())\n        h = int(fs.getNode(\"image_height\").real())\n        fs.release()\n        return CalibrationResult(\n            camera_matrix=K, dist_coeffs=dist,\n            image_size=(w, h), rms_error=0.0)\n```\n\n### Extrinsic Calibration (Camera-to-Camera, Camera-to-LiDAR)\n\n```python\nclass ExtrinsicCalibrator:\n    \"\"\"Compute transform between two sensors using shared targets\"\"\"\n\n    def calibrate_stereo(self, calib_left, calib_right,\n                          obj_points, img_points_left, img_points_right,\n                          image_size):\n        \"\"\"Stereo calibration: find relative pose between two cameras\"\"\"\n        ret, K1, d1, K2, d2, R, T, E, F = cv2.stereoCalibrate(\n            obj_points, img_points_left, img_points_right,\n            calib_left.camera_matrix, calib_left.dist_coeffs,\n            calib_right.camera_matrix, calib_right.dist_coeffs,\n            image_size,\n            flags=cv2.CALIB_FIX_INTRINSIC  # Use pre-calibrated intrinsics\n        )\n\n        print(f\"Stereo calibration RMS: {ret:.4f} px\")\n        print(f\"Baseline: {np.linalg.norm(T):.4f} m\")\n\n        return StereoCalibration(R=R, T=T, E=E, F=F, rms_error=ret)\n\n    def calibrate_camera_to_lidar(self, camera_points_2d,\n                                    lidar_points_3d, K, dist):\n        \"\"\"Find camera-to-LiDAR transform using corresponding points.\n\n        Use a calibration target visible to both sensors (e.g.,\n        checkerboard with reflective tape corners).\n        \"\"\"\n        # PnP: find pose of 3D points relative to camera\n        success, rvec, tvec = cv2.solvePnP(\n            lidar_points_3d, camera_points_2d, K, dist,\n            flags=cv2.SOLVEPNP_ITERATIVE\n        )\n\n        if not success:\n            raise CalibrationError(\"PnP failed — check point correspondences\")\n\n        R, _ = cv2.Rodrigues(rvec)\n        T_camera_lidar = np.eye(4)\n        T_camera_lidar[:3, :3] = R\n        T_camera_lidar[:3, 3] = tvec.flatten()\n\n        # Verify by reprojecting\n        projected, _ = cv2.projectPoints(\n            lidar_points_3d, rvec, tvec, K, dist)\n        error = np.mean(np.linalg.norm(\n            camera_points_2d - projected.reshape(-1, 2), axis=1))\n        print(f\"Camera-LiDAR reprojection error: {error:.2f} px\")\n\n        return T_camera_lidar\n```\n\n### Hand-Eye Calibration (Camera-to-Robot)\n\n```python\nclass HandEyeCalibrator:\n    \"\"\"Solve AX = XB for camera mounted on robot end-effector (eye-in-hand)\n    or camera mounted on a fixed base (eye-to-hand).\n\n    Requires moving the robot to multiple poses while observing a\n    fixed calibration target.\n    \"\"\"\n\n    def __init__(self, K, dist, board_size=(9, 6), square_size=0.025):\n        self.K = K\n        self.dist = dist\n        self.board_size = board_size\n        self.square_size = square_size\n        self.objp = np.zeros((board_size[0] * board_size[1], 3), np.float32)\n        self.objp[:, :2] = np.mgrid[\n            0:board_size[0], 0:board_size[1]\n        ].T.reshape(-1, 2) * square_size\n\n    def collect_poses(self, camera, robot, num_poses=20):\n        \"\"\"Collect camera-target and robot poses at multiple configurations.\n\n        IMPORTANT: Move to diverse robot orientations. At least 3 different\n        rotation axes. Pure translations are NOT sufficient.\n        \"\"\"\n        R_gripper2base = []\n        t_gripper2base = []\n        R_target2cam = []\n        t_target2cam = []\n\n        for i in range(num_poses):\n            input(f\"Move robot to pose {i+1}\u002F{num_poses}, press Enter...\")\n\n            # Get robot end-effector pose\n            ee_pose = robot.get_ee_pose()  # 4x4 homogeneous matrix\n            R_gripper2base.append(ee_pose[:3, :3])\n            t_gripper2base.append(ee_pose[:3, 3])\n\n            # Detect calibration target in camera\n            frame = camera.capture()\n            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n            found, corners = cv2.findChessboardCorners(\n                gray, self.board_size, None)\n\n            if not found:\n                print(f\"  Board not detected at pose {i+1}, skip.\")\n                continue\n\n            corners = cv2.cornerSubPix(\n                gray, corners, (11, 11), (-1, -1),\n                (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001))\n\n            ret, rvec, tvec = cv2.solvePnP(\n                self.objp, corners, self.K, self.dist)\n            R, _ = cv2.Rodrigues(rvec)\n            R_target2cam.append(R)\n            t_target2cam.append(tvec.flatten())\n\n        return (R_gripper2base, t_gripper2base,\n                R_target2cam, t_target2cam)\n\n    def calibrate_eye_in_hand(self, R_g2b, t_g2b, R_t2c, t_t2c):\n        \"\"\"Eye-in-hand: camera mounted on end-effector.\n        Solves for T_camera_to_gripper.\"\"\"\n        R, t = cv2.calibrateHandEye(\n            R_g2b, t_g2b, R_t2c, t_t2c,\n            method=cv2.CALIB_HAND_EYE_TSAI  # Also: PARK, HORAUD, DANIILIDIS\n        )\n        T_cam2gripper = np.eye(4)\n        T_cam2gripper[:3, :3] = R\n        T_cam2gripper[:3, 3] = t.flatten()\n        return T_cam2gripper\n\n    def calibrate_eye_to_hand(self, R_g2b, t_g2b, R_t2c, t_t2c):\n        \"\"\"Eye-to-hand: camera fixed in workspace.\n        Solves for T_camera_to_base.\"\"\"\n        # Invert robot poses (base-to-gripper → gripper-to-base)\n        R_b2g = [R.T for R in R_g2b]\n        t_b2g = [-R.T @ t for R, t in zip(R_g2b, t_g2b)]\n\n        R, t = cv2.calibrateHandEye(\n            R_b2g, t_b2g, R_t2c, t_t2c,\n            method=cv2.CALIB_HAND_EYE_TSAI\n        )\n        T_cam2base = np.eye(4)\n        T_cam2base[:3, :3] = R\n        T_cam2base[:3, 3] = t.flatten()\n        return T_cam2base\n\n    def verify_calibration(self, T_cam2ee, robot, camera, target_points_3d):\n        \"\"\"Verify by projecting a known 3D point through the full chain.\n        Error should be \u003C 5mm for manipulation tasks.\"\"\"\n        ee_pose = robot.get_ee_pose()\n        T_cam2base = ee_pose @ T_cam2ee\n\n        # Project world point to camera\n        point_in_cam = np.linalg.inv(T_cam2base) @ np.append(\n            target_points_3d[0], 1.0)\n        projected, _ = cv2.projectPoints(\n            point_in_cam[:3].reshape(1, 3),\n            np.zeros(3), np.zeros(3), self.K, self.dist)\n\n        print(f\"Verification projection: {projected.flatten()}\")\n        return projected.flatten()\n```\n\n### Calibration Quality Checklist\n\n```\n✅ Intrinsic calibration:\n   - RMS reprojection error \u003C 0.5 px (good), \u003C 0.3 px (excellent)\n   - ≥ 20 images with board covering full image area (corners + edges)\n   - Board tilted at multiple angles (not just fronto-parallel)\n   - Fixed focus \u002F fixed zoom during calibration AND operation\n\n✅ Extrinsic calibration (stereo \u002F camera-LiDAR):\n   - RMS \u003C 1.0 px for stereo\n   - Reprojection error \u003C 3 px for camera-LiDAR\n   - Verified with independent measurement (ruler \u002F known distance)\n\n✅ Hand-eye calibration:\n   - ≥ 15 poses with diverse orientations (≥ 3 rotation axes)\n   - Verification error \u003C 5mm for manipulation, \u003C 10mm for navigation\n   - Robot repeatability accounted for (UR5 ≈ ±0.03mm, low-cost ≈ ±1mm)\n\n⚠️  Recalibrate when:\n   - Camera is physically bumped or remounted\n   - Lens focus or zoom is changed\n   - Temperature changes significantly (thermal expansion shifts intrinsics)\n   - Robot is re-homed or joints are recalibrated\n```\n\n## Sensor Streaming Best Practices\n\n### Camera Streaming Architecture\n\n```python\nimport threading\nimport time\nfrom collections import deque\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nimport numpy as np\n\n@dataclass\nclass StampedFrame:\n    \"\"\"Frame with capture timestamp for synchronization\"\"\"\n    data: np.ndarray\n    timestamp: float          # time.monotonic() at capture\n    sequence: int             # Frame counter\n    sensor_id: str\n\nclass CameraStream:\n    \"\"\"Thread-safe camera streaming with bounded buffer.\n\n    Design principles:\n    1. Capture runs in a dedicated thread at sensor rate\n    2. Processing never blocks capture\n    3. Always use the LATEST frame (drop old ones for real-time)\n    4. Timestamp at capture, not at processing time\n    \"\"\"\n\n    def __init__(self, camera, buffer_size=2, name=\"camera\"):\n        self.camera = camera\n        self.name = name\n        self._buffer = deque(maxlen=buffer_size)\n        self._lock = threading.Lock()\n        self._new_frame = threading.Event()\n        self._running = False\n        self._sequence = 0\n        self._thread = None\n\n        # Diagnostics\n        self._capture_times = deque(maxlen=100)\n        self._drop_count = 0\n\n    def start(self):\n        \"\"\"Start capture thread\"\"\"\n        self._running = True\n        self._thread = threading.Thread(\n            target=self._capture_loop, daemon=True, name=f\"{self.name}_capture\")\n        self._thread.start()\n\n    def stop(self):\n        \"\"\"Stop capture thread\"\"\"\n        self._running = False\n        if self._thread:\n            self._thread.join(timeout=2.0)\n\n    def _capture_loop(self):\n        while self._running:\n            t_start = time.monotonic()\n\n            try:\n                raw = self.camera.capture()\n                timestamp = time.monotonic()  # Timestamp AFTER capture\n\n                frame = StampedFrame(\n                    data=raw,\n                    timestamp=timestamp,\n                    sequence=self._sequence,\n                    sensor_id=self.name\n                )\n                self._sequence += 1\n\n                with self._lock:\n                    if len(self._buffer) == self._buffer.maxlen:\n                        self._drop_count += 1\n                    self._buffer.append(frame)\n\n                self._new_frame.set()\n                self._capture_times.append(time.monotonic() - t_start)\n\n            except Exception as e:\n                print(f\"[{self.name}] Capture error: {e}\")\n                time.sleep(0.01)  # Back off on error\n\n    def get_latest(self) -> Optional[StampedFrame]:\n        \"\"\"Get most recent frame (non-blocking). Returns None if empty.\"\"\"\n        with self._lock:\n            if self._buffer:\n                return self._buffer[-1]\n        return None\n\n    def wait_for_frame(self, timeout=1.0) -> Optional[StampedFrame]:\n        \"\"\"Block until a new frame arrives\"\"\"\n        self._new_frame.clear()\n        if self._new_frame.wait(timeout=timeout):\n            return self.get_latest()\n        return None\n\n    def get_diagnostics(self) -> dict:\n        \"\"\"Streaming health metrics\"\"\"\n        if self._capture_times:\n            times = list(self._capture_times)\n            fps = 1.0 \u002F np.mean(times) if np.mean(times) > 0 else 0\n        else:\n            fps = 0\n        return {\n            \"sensor\": self.name,\n            \"fps\": round(fps, 1),\n            \"frames_captured\": self._sequence,\n            \"frames_dropped\": self._drop_count,\n            \"buffer_size\": len(self._buffer),\n            \"avg_capture_ms\": round(np.mean(times) * 1000, 1) if self._capture_times else 0,\n        }\n```\n\n### Multi-Sensor Synchronization\n\n```python\nclass SyncedMultiSensor:\n    \"\"\"Synchronize frames from multiple sensors by timestamp.\n\n    Uses nearest-neighbor matching within a time tolerance.\n    For hardware-synced sensors, use hardware trigger instead.\n    \"\"\"\n\n    def __init__(self, sensors: dict, max_time_diff_ms=33):\n        \"\"\"\n        Args:\n            sensors: {\"rgb\": CameraStream, \"depth\": CameraStream, ...}\n            max_time_diff_ms: Maximum allowed time difference between\n                              synced frames. Default 33ms (1 frame at 30Hz).\n        \"\"\"\n        self.sensors = sensors\n        self.max_dt = max_time_diff_ms \u002F 1000.0\n        self._synced_callback = None\n\n    def start(self):\n        for s in self.sensors.values():\n            s.start()\n\n    def stop(self):\n        for s in self.sensors.values():\n            s.stop()\n\n    def get_synced(self) -> Optional[dict]:\n        \"\"\"Get time-synchronized frames from all sensors.\n        Returns None if any sensor is missing or too far out of sync.\"\"\"\n        frames = {}\n        for name, stream in self.sensors.items():\n            frame = stream.get_latest()\n            if frame is None:\n                return None\n            frames[name] = frame\n\n        # Check time alignment against the first sensor\n        ref_time = list(frames.values())[0].timestamp\n        for name, frame in frames.items():\n            dt = abs(frame.timestamp - ref_time)\n            if dt > self.max_dt:\n                return None  # Out of sync\n\n        return frames\n\n    def get_synced_interpolated(self) -> Optional[dict]:\n        \"\"\"For sensors at different rates, interpolate to common timestamp.\n        Useful for IMU + camera fusion.\"\"\"\n        # Get latest from each sensor\n        frames = {}\n        for name, stream in self.sensors.items():\n            frame = stream.get_latest()\n            if frame is None:\n                return None\n            frames[name] = frame\n\n        # Use the SLOWEST sensor's timestamp as reference\n        ref_time = min(f.timestamp for f in frames.values())\n\n        result = {}\n        for name, frame in frames.items():\n            dt = frame.timestamp - ref_time\n            if abs(dt) \u003C= self.max_dt:\n                result[name] = frame\n            # For high-rate sensors (IMU), could interpolate here\n\n        return result if len(result) == len(self.sensors) else None\n```\n\n### Hardware-Triggered Synchronization\n\n```python\nclass HardwareSyncConfig:\n    \"\"\"Configure hardware trigger for multi-camera synchronization.\n\n    ALWAYS prefer hardware sync over software sync for:\n    - Stereo depth computation\n    - Multi-camera 3D reconstruction\n    - Fast-moving scenes\n\n    Common trigger methods:\n    - GPIO pulse from microcontroller (Arduino, ESP32)\n    - Camera's own sync output → other cameras' trigger input\n    - PTP (Precision Time Protocol) for GigE cameras\n    \"\"\"\n\n    @staticmethod\n    def setup_realsense_sync(master_serial, slave_serials):\n        \"\"\"Configure RealSense hardware sync (Inter-Cam sync mode)\"\"\"\n        import pyrealsense2 as rs\n\n        # Master camera: generates sync signal\n        master = rs.pipeline()\n        master_cfg = rs.config()\n        master_cfg.enable_device(master_serial)\n        master_sensor = master.start(master_cfg)\n\n        # Set master to mode 1 (master)\n        depth_sensor = master_sensor.get_device().first_depth_sensor()\n        depth_sensor.set_option(rs.option.inter_cam_sync_mode, 1)\n\n        # Slave cameras: receive sync signal\n        slaves = []\n        for serial in slave_serials:\n            pipe = rs.pipeline()\n            cfg = rs.config()\n            cfg.enable_device(serial)\n            profile = pipe.start(cfg)\n            sensor = profile.get_device().first_depth_sensor()\n            sensor.set_option(rs.option.inter_cam_sync_mode, 2)  # Slave\n            slaves.append(pipe)\n\n        return master, slaves\n\n    @staticmethod\n    def setup_ptp_sync(camera_ips):\n        \"\"\"Enable PTP synchronization for GigE Vision cameras.\n\n        Requires PTP-capable network switch.\n        Achieves \u003C 1μs sync accuracy.\n        \"\"\"\n        # Example with Basler\u002Fpylon cameras\n        # import pypylon.pylon as py\n        #\n        # for ip in camera_ips:\n        #     cam = py.InstantCamera(py.TlFactory.GetInstance()\n        #         .CreateDevice(py.CDeviceInfo().SetIpAddress(ip)))\n        #     cam.Open()\n        #     cam.GevIEEE1588.Value = True  # Enable PTP\n        #     cam.Close()\n        pass\n```\n\n### Streaming Anti-Patterns\n\n```python\n# ❌ BAD: Capture and process in same thread — limits to slowest operation\ndef bad_pipeline():\n    while True:\n        frame = camera.capture()           # 5ms\n        detections = model.detect(frame)   # 100ms\n        # Effective rate: ~9 FPS regardless of camera's 30 FPS\n\n# ✅ GOOD: Decouple capture from processing\ndef good_pipeline():\n    stream = CameraStream(camera)\n    stream.start()\n    while True:\n        frame = stream.get_latest()        # Always latest, non-blocking\n        if frame:\n            detections = model.detect(frame.data)  # 100ms\n            # Camera still capturing at 30 FPS in background\n            # Processing at ~10 FPS but always on freshest frame\n\n\n# ❌ BAD: Unbounded buffer — memory grows until OOM\nbuffer = []  # Will grow forever if consumer is slower than producer!\n\n# ✅ GOOD: Bounded buffer with drop policy\nbuffer = deque(maxlen=2)  # Keep latest 2, drop old automatically\n\n\n# ❌ BAD: Sleeping for frame timing\ntime.sleep(1.0 \u002F 30)  # Drift accumulates, doesn't account for jitter\n\n# ✅ GOOD: Event-driven or spin with wall clock\nframe = stream.wait_for_frame(timeout=0.1)\n\n\n# ❌ BAD: Timestamp at processing time\ndef process_callback(raw_data):\n    timestamp = time.time()  # WRONG: includes queue delay + scheduling\n    frame = decode(raw_data)\n    publish(frame, timestamp)\n\n# ✅ GOOD: Timestamp at capture time\ndef capture_thread():\n    raw_data = sensor.read()\n    timestamp = time.monotonic()  # RIGHT: timestamp at source\n    queue.put((raw_data, timestamp))\n```\n\n## RGB Processing Pipelines\n\n### Image Undistortion\n\n```python\nclass ImageUndistorter:\n    \"\"\"Pre-compute undistortion maps for fast runtime correction.\n\n    ALWAYS undistort before any geometric computation\n    (pose estimation, 3D reconstruction, visual servoing).\n    \"\"\"\n\n    def __init__(self, K, dist, image_size, alpha=0.0):\n        \"\"\"\n        Args:\n            alpha: 0.0 = crop all black pixels (default, recommended)\n                   1.0 = keep all pixels (shows black borders)\n        \"\"\"\n        self.new_K, self.roi = cv2.getOptimalNewCameraMatrix(\n            K, dist, image_size, alpha, image_size)\n\n        # Pre-compute maps (do this ONCE, not per frame)\n        self.map1, self.map2 = cv2.initUndistortRectifyMap(\n            K, dist, None, self.new_K, image_size, cv2.CV_16SC2)\n\n    def undistort(self, image):\n        \"\"\"Apply undistortion using pre-computed maps (fast)\"\"\"\n        return cv2.remap(image, self.map1, self.map2,\n                         interpolation=cv2.INTER_LINEAR)\n\n    def undistort_points(self, points_2d):\n        \"\"\"Undistort 2D point coordinates\"\"\"\n        return cv2.undistortPoints(\n            points_2d.reshape(-1, 1, 2).astype(np.float64),\n            self.K, self.dist, P=self.new_K\n        ).reshape(-1, 2)\n```\n\n### Object Detection Integration\n\n```python\nclass RobotObjectDetector:\n    \"\"\"Object detection for robotic manipulation.\n\n    Wraps a detection model with robotics-specific post-processing:\n    - Workspace filtering (ignore detections outside robot reach)\n    - Stability tracking (reject flickering detections)\n    - 3D pose estimation from 2D detections + depth\n    \"\"\"\n\n    def __init__(self, model, K, workspace_bounds=None, min_confidence=0.5):\n        self.model = model\n        self.K = K\n        self.workspace_bounds = workspace_bounds\n        self.min_confidence = min_confidence\n        self.tracker = DetectionTracker(max_age=5, min_hits=3)\n\n    def detect(self, rgb, depth=None) -> list:\n        \"\"\"Run detection with robotics post-processing\"\"\"\n        # Raw detection\n        raw_dets = self.model(rgb)\n\n        # Filter by confidence\n        dets = [d for d in raw_dets if d.confidence >= self.min_confidence]\n\n        # Estimate 3D position if depth is available\n        if depth is not None:\n            for det in dets:\n                det.position_3d = self._backproject(det.center, depth)\n\n                # Filter by workspace\n                if self.workspace_bounds and det.position_3d is not None:\n                    if not self.workspace_bounds.contains(det.position_3d):\n                        det.in_workspace = False\n                        continue\n                    det.in_workspace = True\n\n        # Track across frames for stability\n        tracked = self.tracker.update(dets)\n\n        return tracked\n\n    def _backproject(self, pixel, depth_image):\n        \"\"\"Convert 2D pixel + depth to 3D point in camera frame.\n\n        This is the INVERSE of projection:\n        X = (u - cx) * Z \u002F fx\n        Y = (v - cy) * Z \u002F fy\n        Z = depth\n        \"\"\"\n        u, v = int(pixel[0]), int(pixel[1])\n\n        # Sample depth with a small window (more robust than single pixel)\n        h, w = depth_image.shape[:2]\n        u = np.clip(u, 2, w - 3)\n        v = np.clip(v, 2, h - 3)\n        patch = depth_image[v-2:v+3, u-2:u+3]\n\n        # Use median to reject outliers (holes, edges)\n        valid = patch[patch > 0]\n        if len(valid) == 0:\n            return None\n        Z = np.median(valid)\n\n        # Convert from depth sensor units (often mm) to meters\n        if Z > 100:  # Likely millimeters\n            Z = Z \u002F 1000.0\n\n        fx, fy = self.K[0, 0], self.K[1, 1]\n        cx, cy = self.K[0, 2], self.K[1, 2]\n\n        X = (u - cx) * Z \u002F fx\n        Y = (v - cy) * Z \u002F fy\n\n        return np.array([X, Y, Z])\n```\n\n### Fiducial Marker Detection (AprilTag \u002F ArUco)\n\n```python\nclass FiducialDetector:\n    \"\"\"Detect and estimate pose of fiducial markers.\n\n    Use cases:\n    - Robot localization (known marker positions)\n    - Object pose estimation (marker attached to object)\n    - Calibration targets\n    - Sim-to-real ground truth\n    \"\"\"\n\n    def __init__(self, K, dist, marker_size_m=0.05,\n                 dictionary=cv2.aruco.DICT_APRILTAG_36h11):\n        self.K = K\n        self.dist = dist\n        self.marker_size = marker_size_m\n        self.aruco_dict = cv2.aruco.getPredefinedDictionary(dictionary)\n        self.params = cv2.aruco.DetectorParameters()\n        self.detector = cv2.aruco.ArucoDetector(self.aruco_dict, self.params)\n\n    def detect(self, image) -> list:\n        \"\"\"Detect markers and estimate their 6DOF poses\"\"\"\n        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n        corners, ids, rejected = self.detector.detectMarkers(gray)\n\n        results = []\n        if ids is not None:\n            for i, marker_id in enumerate(ids.flatten()):\n                # Estimate pose (rotation + translation)\n                rvecs, tvecs, _ = cv2.aruco.estimatePoseSingleMarkers(\n                    corners[i:i+1], self.marker_size, self.K, self.dist)\n\n                R, _ = cv2.Rodrigues(rvecs[0])\n                T = np.eye(4)\n                T[:3, :3] = R\n                T[:3, 3] = tvecs[0].flatten()\n\n                results.append(MarkerDetection(\n                    marker_id=int(marker_id),\n                    corners=corners[i].reshape(4, 2),\n                    pose=T,\n                    distance=np.linalg.norm(tvecs[0]),\n                ))\n\n        return results\n\n    def draw(self, image, detections):\n        \"\"\"Visualize detected markers with axes\"\"\"\n        vis = image.copy()\n        for det in detections:\n            cv2.aruco.drawDetectedMarkers(\n                vis, [det.corners.reshape(1, 4, 2)],\n                np.array([[det.marker_id]]))\n            rvec, _ = cv2.Rodrigues(det.pose[:3, :3])\n            cv2.drawFrameAxes(\n                vis, self.K, self.dist, rvec,\n                det.pose[:3, 3], self.marker_size * 0.5)\n        return vis\n```\n\n### Semantic Segmentation for Manipulation\n\n```python\nclass WorkspaceSegmenter:\n    \"\"\"Segment a robot's workspace into actionable regions.\n\n    Common segmentation targets for manipulation:\n    - Graspable objects vs background\n    - Table \u002F support surface\n    - Robot body (for self-collision avoidance)\n    - Free space vs obstacles\n    \"\"\"\n\n    def __init__(self, model, class_map):\n        self.model = model\n        self.class_map = class_map  # {0: 'background', 1: 'table', 2: 'object', ...}\n\n    def segment(self, rgb) -> SegmentationResult:\n        \"\"\"Run segmentation and extract per-class masks\"\"\"\n        mask = self.model.predict(rgb)  # (H, W) with class IDs\n\n        return SegmentationResult(\n            full_mask=mask,\n            object_mask=(mask == self.class_map['object']),\n            table_mask=(mask == self.class_map['table']),\n            free_space_mask=(mask == self.class_map['free_space']),\n        )\n\n    def get_grasp_candidates(self, rgb, depth, K):\n        \"\"\"Combine segmentation with depth to find graspable regions\"\"\"\n        seg = self.segment(rgb)\n\n        # Find connected components in object mask\n        num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(\n            seg.object_mask.astype(np.uint8))\n\n        candidates = []\n        for i in range(1, num_labels):  # Skip background (0)\n            component_mask = (labels == i)\n            area = stats[i, cv2.CC_STAT_AREA]\n\n            if area \u003C 100:  # Too small, likely noise\n                continue\n\n            # Get median depth of this object\n            obj_depths = depth[component_mask]\n            valid_depths = obj_depths[obj_depths > 0]\n            if len(valid_depths) == 0:\n                continue\n\n            center_px = centroids[i]\n            median_depth = np.median(valid_depths)\n\n            # Backproject center to 3D\n            fx, fy = K[0, 0], K[1, 1]\n            cx, cy = K[0, 2], K[1, 2]\n            X = (center_px[0] - cx) * median_depth \u002F fx\n            Y = (center_px[1] - cy) * median_depth \u002F fy\n\n            candidates.append(GraspCandidate(\n                position_3d=np.array([X, Y, median_depth]),\n                pixel_center=center_px,\n                mask=component_mask,\n                area_pixels=area,\n            ))\n\n        return candidates\n```\n\n## Depth Processing\n\n### Depth Map Filtering and Cleanup\n\n```python\nclass DepthProcessor:\n    \"\"\"Clean up raw depth maps for downstream use.\n\n    Raw depth from sensors is noisy: holes, flying pixels at edges,\n    multi-path interference, and range noise. Always filter before use.\n    \"\"\"\n\n    def __init__(self, depth_scale=0.001, min_depth_m=0.1, max_depth_m=3.0):\n        self.depth_scale = depth_scale  # Raw units to meters\n        self.min_depth = min_depth_m\n        self.max_depth = max_depth_m\n\n    def process(self, raw_depth) -> np.ndarray:\n        \"\"\"Full depth cleanup pipeline\"\"\"\n        depth = raw_depth.astype(np.float32) * self.depth_scale\n\n        # 1. Range filtering\n        depth[(depth \u003C self.min_depth) | (depth > self.max_depth)] = 0\n\n        # 2. Edge filtering — remove flying pixels at depth discontinuities\n        depth = self._remove_flying_pixels(depth)\n\n        # 3. Hole filling — fill small holes via inpainting\n        depth = self._fill_holes(depth, max_hole_size=10)\n\n        # 4. Spatial smoothing — bilateral filter preserves edges\n        depth = self._bilateral_filter(depth)\n\n        return depth\n\n    def _remove_flying_pixels(self, depth, threshold=0.05):\n        \"\"\"Remove pixels at depth discontinuities (flying pixels).\n        These are artifacts where the sensor interpolates between\n        foreground and background.\"\"\"\n        dx = np.abs(np.diff(depth, axis=1, prepend=0))\n        dy = np.abs(np.diff(depth, axis=0, prepend=0))\n        gradient = np.sqrt(dx**2 + dy**2)\n        depth[gradient > threshold] = 0\n        return depth\n\n    def _fill_holes(self, depth, max_hole_size=10):\n        \"\"\"Fill small holes using inpainting. Large holes remain as 0.\"\"\"\n        mask = (depth == 0).astype(np.uint8)\n\n        # Only fill small holes\n        kernel = np.ones((max_hole_size, max_hole_size), np.uint8)\n        small_holes = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)\n        small_holes = small_holes & mask\n\n        if small_holes.any():\n            # Normalize depth to uint16 for inpainting\n            d_norm = (depth * 1000).astype(np.uint16)\n            filled = cv2.inpaint(\n                d_norm, small_holes, max_hole_size, cv2.INPAINT_NS)\n            depth = np.where(small_holes, filled.astype(np.float32) \u002F 1000, depth)\n\n        return depth\n\n    def _bilateral_filter(self, depth, d=5, sigma_color=0.02, sigma_space=5):\n        \"\"\"Bilateral filter: smooths noise while preserving depth edges\"\"\"\n        # Convert to uint16 for cv2 bilateral (doesn't support float)\n        d_uint16 = (depth * 10000).astype(np.uint16)\n        filtered = cv2.bilateralFilter(d_uint16, d,\n                                        sigma_color * 10000, sigma_space)\n        return filtered.astype(np.float32) \u002F 10000\n```\n\n### Depth-to-Point Cloud Conversion\n\n```python\nclass DepthToPointCloud:\n    \"\"\"Convert depth images to organized and unorganized point clouds.\"\"\"\n\n    def __init__(self, K, image_size):\n        self.K = K\n        # Pre-compute pixel coordinate grid (do once, reuse every frame)\n        h, w = image_size[1], image_size[0]\n        u_coords, v_coords = np.meshgrid(np.arange(w), np.arange(h))\n        self.u = u_coords.astype(np.float32)\n        self.v = v_coords.astype(np.float32)\n        self.fx, self.fy = K[0, 0], K[1, 1]\n        self.cx, self.cy = K[0, 2], K[1, 2]\n\n    def convert(self, depth, rgb=None) -> np.ndarray:\n        \"\"\"Convert depth image to point cloud.\n\n        Returns:\n            points: (N, 3) or (N, 6) if rgb provided [x, y, z, r, g, b]\n        \"\"\"\n        # Backproject all pixels in parallel (vectorized)\n        Z = depth.astype(np.float32)\n        X = (self.u - self.cx) * Z \u002F self.fx\n        Y = (self.v - self.cy) * Z \u002F self.fy\n\n        # Stack into (H, W, 3) organized point cloud\n        points = np.stack([X, Y, Z], axis=-1)\n\n        # Filter invalid points\n        valid_mask = Z > 0\n        points_valid = points[valid_mask]\n\n        if rgb is not None:\n            colors = rgb[valid_mask].astype(np.float32) \u002F 255.0\n            return np.hstack([points_valid, colors])\n\n        return points_valid\n\n    def convert_organized(self, depth, rgb=None):\n        \"\"\"Return organized point cloud (H, W, 3) — preserves pixel layout.\n        Invalid points are NaN.\"\"\"\n        Z = depth.astype(np.float32)\n        X = (self.u - self.cx) * Z \u002F self.fx\n        Y = (self.v - self.cy) * Z \u002F self.fy\n\n        organized = np.stack([X, Y, Z], axis=-1)\n        organized[depth == 0] = np.nan\n\n        return organized\n```\n\n### RGBD Alignment\n\n```python\nclass RGBDAligner:\n    \"\"\"Align RGB and depth images from different sensors.\n\n    Most RGBD sensors (RealSense, ZED) provide built-in alignment.\n    Use this when combining separate RGB + depth cameras.\n    \"\"\"\n\n    def __init__(self, K_rgb, K_depth, T_depth_to_rgb, rgb_size, depth_size):\n        self.K_rgb = K_rgb\n        self.K_depth = K_depth\n        self.T = T_depth_to_rgb  # 4x4 transform: depth frame → rgb frame\n        self.rgb_size = rgb_size\n        self.depth_size = depth_size\n\n    def align_depth_to_rgb(self, depth):\n        \"\"\"Reproject depth image into RGB camera's frame.\n\n        For each pixel in depth image:\n        1. Backproject to 3D using depth intrinsics\n        2. Transform to RGB camera frame\n        3. Project to RGB pixel using RGB intrinsics\n        \"\"\"\n        h_d, w_d = depth.shape\n        h_r, w_r = self.rgb_size[1], self.rgb_size[0]\n        aligned = np.zeros((h_r, w_r), dtype=np.float32)\n\n        # Backproject depth pixels to 3D\n        v_d, u_d = np.mgrid[0:h_d, 0:w_d].astype(np.float32)\n        Z = depth.astype(np.float32)\n        valid = Z > 0\n\n        X = (u_d[valid] - self.K_depth[0, 2]) * Z[valid] \u002F self.K_depth[0, 0]\n        Y = (v_d[valid] - self.K_depth[1, 2]) * Z[valid] \u002F self.K_depth[1, 1]\n        pts_3d = np.stack([X, Y, Z[valid], np.ones_like(X)], axis=0)\n\n        # Transform to RGB frame\n        pts_rgb = self.T @ pts_3d\n\n        # Project to RGB pixels\n        u_r = (self.K_rgb[0, 0] * pts_rgb[0] \u002F pts_rgb[2] +\n               self.K_rgb[0, 2]).astype(int)\n        v_r = (self.K_rgb[1, 1] * pts_rgb[1] \u002F pts_rgb[2] +\n               self.K_rgb[1, 2]).astype(int)\n\n        # Fill aligned depth (z-buffer for occlusion handling)\n        in_bounds = (u_r >= 0) & (u_r \u003C w_r) & (v_r >= 0) & (v_r \u003C h_r)\n        for u, v, z in zip(u_r[in_bounds], v_r[in_bounds],\n                           pts_rgb[2][in_bounds]):\n            if aligned[v, u] == 0 or z \u003C aligned[v, u]:\n                aligned[v, u] = z\n\n        return aligned\n```\n\n## Point Cloud Processing\n\n### Filtering and Downsampling\n\n```python\nimport open3d as o3d\n\nclass PointCloudProcessor:\n    \"\"\"Point cloud processing pipeline using Open3D.\n\n    Pipeline order matters:\n    1. Crop to region of interest (reduces data volume first)\n    2. Remove statistical outliers\n    3. Downsample (voxel grid)\n    4. Estimate normals\n    5. Application-specific processing\n    \"\"\"\n\n    def preprocess(self, points, colors=None,\n                   workspace_bounds=None, voxel_size=0.005):\n        \"\"\"Standard preprocessing pipeline\"\"\"\n        pcd = o3d.geometry.PointCloud()\n        pcd.points = o3d.utility.Vector3dVector(points[:, :3])\n        if colors is not None:\n            pcd.colors = o3d.utility.Vector3dVector(colors)\n\n        # 1. Crop to workspace\n        if workspace_bounds:\n            bbox = o3d.geometry.AxisAlignedBoundingBox(\n                min_bound=workspace_bounds['min'],\n                max_bound=workspace_bounds['max'])\n            pcd = pcd.crop(bbox)\n\n        # 2. Statistical outlier removal\n        pcd, inlier_idx = pcd.remove_statistical_outlier(\n            nb_neighbors=20, std_ratio=2.0)\n\n        # 3. Voxel downsampling\n        pcd = pcd.voxel_down_sample(voxel_size=voxel_size)\n\n        # 4. Normal estimation\n        pcd.estimate_normals(\n            search_param=o3d.geometry.KDTreeSearchParamHybrid(\n                radius=voxel_size * 4, max_nn=30))\n        # Orient normals toward camera\n        pcd.orient_normals_towards_camera_location(\n            camera_location=np.array([0, 0, 0]))\n\n        return pcd\n\n    def segment_plane(self, pcd, distance_threshold=0.005,\n                      ransac_n=3, num_iterations=1000):\n        \"\"\"Segment the dominant plane (table \u002F floor) using RANSAC.\n        Returns plane model and inlier\u002Foutlier point clouds.\"\"\"\n        plane_model, inliers = pcd.segment_plane(\n            distance_threshold=distance_threshold,\n            ransac_n=ransac_n,\n            num_iterations=num_iterations)\n\n        plane_cloud = pcd.select_by_index(inliers)\n        objects_cloud = pcd.select_by_index(inliers, invert=True)\n\n        a, b, c, d = plane_model\n        print(f\"Plane: {a:.3f}x + {b:.3f}y + {c:.3f}z + {d:.3f} = 0\")\n\n        return plane_model, plane_cloud, objects_cloud\n\n    def cluster_objects(self, pcd, eps=0.02, min_points=50):\n        \"\"\"Cluster point cloud into individual objects using DBSCAN\"\"\"\n        labels = np.array(pcd.cluster_dbscan(\n            eps=eps, min_points=min_points, print_progress=False))\n\n        clusters = []\n        for label_id in range(labels.max() + 1):\n            cluster_mask = labels == label_id\n            cluster_pcd = pcd.select_by_index(\n                np.where(cluster_mask)[0])\n\n            bbox = cluster_pcd.get_axis_aligned_bounding_box()\n            center = bbox.get_center()\n            extent = bbox.get_extent()\n\n            clusters.append(PointCloudCluster(\n                cloud=cluster_pcd,\n                centroid=center,\n                extent=extent,\n                num_points=cluster_mask.sum(),\n                bbox=bbox,\n            ))\n\n        # Sort by size (largest first)\n        clusters.sort(key=lambda c: c.num_points, reverse=True)\n        return clusters\n```\n\n### Point Cloud Registration (ICP)\n\n```python\nclass PointCloudRegistration:\n    \"\"\"Align two point clouds using ICP and its variants.\n\n    Use cases:\n    - Multi-view reconstruction (combine views from different poses)\n    - Object model matching (align scan to CAD model)\n    - LiDAR odometry (align consecutive scans)\n    - Bin picking (match object template to scene)\n    \"\"\"\n\n    def align_icp(self, source, target, initial_transform=np.eye(4),\n                  max_distance=0.05, method='point_to_plane'):\n        \"\"\"Iterative Closest Point alignment.\n\n        Args:\n            source: point cloud to align\n            target: reference point cloud\n            initial_transform: starting guess (CRITICAL for convergence)\n            max_distance: max correspondence distance\n            method: 'point_to_point' or 'point_to_plane'\n        \"\"\"\n        if method == 'point_to_plane':\n            # Point-to-plane converges faster but needs normals\n            if not target.has_normals():\n                target.estimate_normals(\n                    search_param=o3d.geometry.KDTreeSearchParamHybrid(\n                        radius=0.05, max_nn=30))\n            estimation = o3d.pipelines.registration.TransformationEstimationPointToPlane()\n        else:\n            estimation = o3d.pipelines.registration.TransformationEstimationPointToPoint()\n\n        result = o3d.pipelines.registration.registration_icp(\n            source, target, max_distance, initial_transform,\n            estimation,\n            o3d.pipelines.registration.ICPConvergenceCriteria(\n                max_iteration=100,\n                relative_fitness=1e-6,\n                relative_rmse=1e-6))\n\n        print(f\"ICP fitness: {result.fitness:.4f}, \"\n              f\"RMSE: {result.inlier_rmse:.6f}\")\n\n        if result.fitness \u003C 0.3:\n            print(\"WARNING: Low fitness — ICP likely failed. \"\n                  \"Check initial alignment or increase max_distance.\")\n\n        return result.transformation, result\n\n    def align_global(self, source, target, voxel_size=0.01):\n        \"\"\"Global registration (no initial guess needed).\n        Use FPFH features + RANSAC for coarse alignment,\n        then refine with ICP.\"\"\"\n\n        # Downsample for feature computation\n        source_down = source.voxel_down_sample(voxel_size)\n        target_down = target.voxel_down_sample(voxel_size)\n\n        # Compute normals\n        for pcd in [source_down, target_down]:\n            pcd.estimate_normals(\n                o3d.geometry.KDTreeSearchParamHybrid(\n                    radius=voxel_size * 2, max_nn=30))\n\n        # Compute FPFH features\n        source_fpfh = o3d.pipelines.registration.compute_fpfh_feature(\n            source_down,\n            o3d.geometry.KDTreeSearchParamHybrid(\n                radius=voxel_size * 5, max_nn=100))\n        target_fpfh = o3d.pipelines.registration.compute_fpfh_feature(\n            target_down,\n            o3d.geometry.KDTreeSearchParamHybrid(\n                radius=voxel_size * 5, max_nn=100))\n\n        # RANSAC-based global registration\n        coarse = o3d.pipelines.registration.registration_ransac_based_on_feature_matching(\n            source_down, target_down, source_fpfh, target_fpfh,\n            mutual_filter=True,\n            max_correspondence_distance=voxel_size * 2,\n            estimation_method=o3d.pipelines.registration.TransformationEstimationPointToPoint(),\n            ransac_n=3,\n            checkers=[\n                o3d.pipelines.registration.CorrespondenceCheckerBasedOnEdgeLength(0.9),\n                o3d.pipelines.registration.CorrespondenceCheckerBasedOnDistance(voxel_size * 2),\n            ],\n            criteria=o3d.pipelines.registration.RANSACConvergenceCriteria(100000, 0.999))\n\n        # Refine with ICP\n        refined, _ = self.align_icp(\n            source, target,\n            initial_transform=coarse.transformation,\n            max_distance=voxel_size * 1.5,\n            method='point_to_plane')\n\n        return refined\n```\n\n## Multi-Sensor Fusion\n\n### Perception Fusion Architecture\n\n```\n┌──────────────┐    ┌──────────────┐    ┌──────────────┐\n│  RGB Camera  │    │ Depth Sensor │    │    LiDAR     │\n│   30 Hz      │    │   30 Hz      │    │   10 Hz      │\n└──────┬───────┘    └──────┬───────┘    └──────┬───────┘\n       │                   │                   │\n       ▼                   ▼                   ▼\n┌──────────────┐    ┌──────────────┐    ┌──────────────┐\n│  Detection   │    │    Depth     │    │ Point Cloud  │\n│  + Segment   │    │  Filtering   │    │  Processing  │\n└──────┬───────┘    └──────┬───────┘    └──────┬───────┘\n       │                   │                   │\n       └───────────┬───────┘───────────────────┘\n                   ▼\n          ┌────────────────┐\n          │  Fusion Layer  │\n          │  (association  │\n          │   + tracking)  │\n          └────────┬───────┘\n                   ▼\n          ┌────────────────┐\n          │  World Model   │\n          │  (tracked      │\n          │   objects)     │\n          └────────────────┘\n```\n\n### Camera + LiDAR Fusion\n\n```python\nclass CameraLiDARFusion:\n    \"\"\"Project LiDAR points into camera image for cross-modal association.\n\n    Two fusion strategies:\n    1. Early fusion: Project LiDAR → camera, combine at data level\n    2. Late fusion: Detect in each modality, associate results\n\n    Early fusion is simpler and recommended when sensors are calibrated.\n    \"\"\"\n\n    def __init__(self, K, T_lidar_to_camera, image_size):\n        self.K = K\n        self.T = T_lidar_to_camera  # 4x4 transform\n        self.image_size = image_size  # (w, h)\n\n    def project_lidar_to_image(self, lidar_points):\n        \"\"\"Project 3D LiDAR points to 2D image pixels.\n\n        Returns:\n            pixels: (N, 2) pixel coordinates\n            depths: (N,) depth values\n            valid_mask: (N,) bool — True if point projects into image\n        \"\"\"\n        N = len(lidar_points)\n        # Homogeneous coordinates\n        pts_h = np.hstack([lidar_points[:, :3], np.ones((N, 1))])\n\n        # Transform to camera frame\n        pts_cam = (self.T @ pts_h.T).T\n\n        # Points behind camera\n        valid = pts_cam[:, 2] > 0\n        depths = pts_cam[:, 2]\n\n        # Project to pixels\n        pixels = np.zeros((N, 2))\n        pixels[:, 0] = self.K[0, 0] * pts_cam[:, 0] \u002F pts_cam[:, 2] + self.K[0, 2]\n        pixels[:, 1] = self.K[1, 1] * pts_cam[:, 1] \u002F pts_cam[:, 2] + self.K[1, 2]\n\n        # Check image bounds\n        w, h = self.image_size\n        valid &= (pixels[:, 0] >= 0) & (pixels[:, 0] \u003C w)\n        valid &= (pixels[:, 1] >= 0) & (pixels[:, 1] \u003C h)\n\n        return pixels, depths, valid\n\n    def colorize_pointcloud(self, lidar_points, rgb_image):\n        \"\"\"Paint LiDAR points with RGB colors from camera image\"\"\"\n        pixels, depths, valid = self.project_lidar_to_image(lidar_points)\n\n        colors = np.zeros((len(lidar_points), 3), dtype=np.float32)\n        valid_px = pixels[valid].astype(int)\n        colors[valid] = rgb_image[valid_px[:, 1], valid_px[:, 0]] \u002F 255.0\n\n        return colors, valid\n\n    def enrich_detections(self, detections_2d, lidar_points):\n        \"\"\"Add 3D information to 2D camera detections using LiDAR.\n\n        For each 2D bounding box, find LiDAR points that project\n        inside it, and compute the 3D centroid.\n        \"\"\"\n        pixels, depths, valid = self.project_lidar_to_image(lidar_points)\n\n        enriched = []\n        for det in detections_2d:\n            x1, y1, x2, y2 = det.bbox\n\n            # Find LiDAR points inside this bounding box\n            in_box = (valid &\n                      (pixels[:, 0] >= x1) & (pixels[:, 0] \u003C= x2) &\n                      (pixels[:, 1] >= y1) & (pixels[:, 1] \u003C= y2))\n\n            if in_box.sum() > 3:\n                # Use LiDAR points for 3D position (more accurate than depth camera)\n                box_points = lidar_points[in_box]\n\n                # Median is robust to outliers from other objects\n                position_3d = np.median(box_points[:, :3], axis=0)\n                det.position_3d = position_3d\n                det.num_lidar_points = in_box.sum()\n                det.has_3d = True\n            else:\n                det.has_3d = False\n\n            enriched.append(det)\n\n        return enriched\n```\n\n### Multi-Object Tracking\n\n```python\nclass PerceptionTracker:\n    \"\"\"Track detected objects across frames for temporal consistency.\n\n    Why tracking matters in robotics:\n    - Detections flicker (present one frame, absent the next)\n    - Robot needs consistent object IDs for manipulation\n    - Velocity estimation requires temporal association\n    - Occlusion handling prevents phantom disappearances\n    \"\"\"\n\n    def __init__(self, max_age=5, min_hits=3, iou_threshold=0.3):\n        self.max_age = max_age            # Frames before deleting lost track\n        self.min_hits = min_hits          # Frames before confirming track\n        self.iou_threshold = iou_threshold\n        self.tracks = {}\n        self.next_id = 0\n\n    def update(self, detections) -> list:\n        \"\"\"Associate detections with existing tracks.\n\n        Uses Hungarian algorithm for optimal assignment.\n        \"\"\"\n        if not self.tracks:\n            # First frame: create tracks for all detections\n            for det in detections:\n                self._create_track(det)\n            return list(self.tracks.values())\n\n        # Compute cost matrix (IoU for 2D, Euclidean for 3D)\n        track_list = list(self.tracks.values())\n        cost_matrix = self._compute_cost_matrix(track_list, detections)\n\n        # Hungarian assignment\n        from scipy.optimize import linear_sum_assignment\n        row_idx, col_idx = linear_sum_assignment(cost_matrix)\n\n        matched = set()\n        for r, c in zip(row_idx, col_idx):\n            if cost_matrix[r, c] \u003C self.iou_threshold:\n                track_list[r].update(detections[c])\n                matched.add(c)\n\n        # Create new tracks for unmatched detections\n        for i, det in enumerate(detections):\n            if i not in matched:\n                self._create_track(det)\n\n        # Age out old tracks\n        stale = [tid for tid, t in self.tracks.items()\n                 if t.age > self.max_age]\n        for tid in stale:\n            del self.tracks[tid]\n\n        # Return confirmed tracks only\n        return [t for t in self.tracks.values()\n                if t.hits >= self.min_hits]\n\n    def _create_track(self, detection):\n        track = Track(\n            track_id=self.next_id,\n            detection=detection,\n            hits=1, age=0)\n        self.tracks[self.next_id] = track\n        self.next_id += 1\n\n    def _compute_cost_matrix(self, tracks, detections):\n        n_tracks = len(tracks)\n        n_dets = len(detections)\n        cost = np.ones((n_tracks, n_dets))\n\n        for i, track in enumerate(tracks):\n            for j, det in enumerate(detections):\n                if hasattr(det, 'position_3d') and det.position_3d is not None:\n                    # 3D Euclidean distance (preferred)\n                    dist = np.linalg.norm(\n                        track.position_3d - det.position_3d)\n                    cost[i, j] = dist\n                else:\n                    # 2D IoU\n                    cost[i, j] = 1.0 - self._iou(track.bbox, det.bbox)\n\n        return cost\n\n    @staticmethod\n    def _iou(box1, box2):\n        x1 = max(box1[0], box2[0])\n        y1 = max(box1[1], box2[1])\n        x2 = min(box1[2], box2[2])\n        y2 = min(box1[3], box2[3])\n        inter = max(0, x2 - x1) * max(0, y2 - y1)\n        area1 = (box1[2] - box1[0]) * (box1[3] - box1[1])\n        area2 = (box2[2] - box2[0]) * (box2[3] - box2[1])\n        return inter \u002F (area1 + area2 - inter + 1e-6)\n```\n\n## Perception Latency Budget\n\n```\nComponent                   Typical Latency    Budget Target\n───────────────────────────────────────────────────────────────\nSensor capture              1-10 ms            —\nImage transfer (USB3)       2-5 ms             —\nUndistortion                1-2 ms             \u003C 3 ms\nDetection (GPU)             10-50 ms           \u003C 30 ms\nDetection (CPU)             50-500 ms          \u003C 100 ms\nDepth processing            2-5 ms             \u003C 5 ms\nPoint cloud generation      3-10 ms            \u003C 10 ms\nSegmentation (GPU)          15-40 ms           \u003C 30 ms\nTracking update             0.5-2 ms           \u003C 2 ms\n3D pose estimation          5-20 ms            \u003C 15 ms\n───────────────────────────────────────────────────────────────\nTOTAL PIPELINE              ~50-150 ms         \u003C 100 ms target\n\nFor 10 Hz perception: budget = 100 ms per frame\nFor 30 Hz perception: budget = 33 ms per frame\n\nRULE: Perception latency + planning latency \u003C control period\n      If control runs at 100 Hz (10 ms), perception must be\n      pipelined — process frame N while control uses frame N-1.\n```\n\n## Perception Anti-Patterns\n\n### 1. Processing Every Frame When You Don't Need To\n```python\n# ❌ BAD: Running heavy detection at sensor framerate\ndef callback(self, msg):\n    detections = self.heavy_model(msg)  # 100ms on every 30Hz frame\n\n# ✅ GOOD: Decimate or skip frames\ndef callback(self, msg):\n    self.frame_count += 1\n    if self.frame_count % 3 != 0:  # Process every 3rd frame\n        return\n    detections = self.heavy_model(msg)\n```\n\n### 2. Not Validating Depth Values\n```python\n# ❌ BAD: Using raw depth blindly\nz = depth_image[v, u]\npoint_3d = backproject(u, v, z)  # z might be 0 (hole) or 65535 (invalid)\n\n# ✅ GOOD: Always validate depth\nz = depth_image[v, u]\nif z \u003C= 0 or z > max_range:\n    return None\nz_meters = z * depth_scale\n```\n\n### 3. Assuming Cameras Are Calibrated\n```python\n# ❌ BAD: Using default\u002Fnominal intrinsics\nK = np.array([[600, 0, 320], [0, 600, 240], [0, 0, 1]])  # Guess\n\n# ✅ GOOD: Load actual calibration\nK = load_calibration(\"camera_serial_12345.yaml\").camera_matrix\n```\n\n### 4. Ignoring Sensor Warmup\n```python\n# ❌ BAD: Using first frames from sensor\ncamera.start()\nframe = camera.capture()  # Often overexposed, auto-exposure not settled\n\n# ✅ GOOD: Discard initial frames\ncamera.start()\nfor _ in range(30):  # Let auto-exposure settle (~1 second at 30Hz)\n    camera.capture()\nframe = camera.capture()  # Now usable\n```\n\n### 5. Single-Pixel Depth Sampling\n```python\n# ❌ BAD: Single pixel is noisy and may be a hole\nz = depth[int(center_y), int(center_x)]\n\n# ✅ GOOD: Sample a neighborhood, use median\npatch = depth[cy-3:cy+4, cx-3:cx+4]\nvalid = patch[patch > 0]\nz = np.median(valid) if len(valid) > 0 else None\n```\n\n### 6. Not Handling Coordinate Frame Transforms\n```python\n# ❌ BAD: Assuming everything is in the same frame\nobject_position = detection.position  # In camera frame? Robot frame? World frame?\nrobot.move_to(object_position)        # Which frame does move_to expect?\n\n# ✅ GOOD: Explicit frame tracking\nobject_in_camera = detection.position_3d       # Camera frame\nobject_in_base = T_base_camera @ np.append(object_in_camera, 1.0)  # Robot frame\nrobot.move_to(object_in_base[:3])\n```\n\n## Production Perception Checklist\n\n1. **Calibrate before deploying** — intrinsics, extrinsics, hand-eye\n2. **Validate calibration** with independent measurements\n3. **Set sensor exposure** appropriately — auto-exposure can cause detection flicker\n4. **Undistort** before any geometric computation\n5. **Filter depth** — remove flying pixels, fill small holes\n6. **Timestamp at capture** — not at processing time\n7. **Track objects** across frames — don't rely on single-frame detections\n8. **Handle sensor failures** — missing frames, degraded depth, overexposure\n9. **Log perception output** — bounding boxes, confidence scores, 3D positions\n10. **Benchmark latency** — measure each pipeline stage, find bottlenecks\n11. **Test with edge cases** — empty scenes, cluttered scenes, reflective surfaces, direct sunlight\n12. **Version your models** — pin detection\u002Fsegmentation model versions in deployment\n\n",{"name":5,"description":7},"main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002Farpitg1304\u002Frobotics-agent-skills\u002Frobot-perception",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":62,"prompt":72,"zipAvailable":73},[63,66,69],{"tool":64,"command":65},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill robot-perception",{"tool":67,"command":68},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill robot-perception",{"tool":70,"command":71},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill robot-perception","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Farpitg1304\u002Frobotics-agent-skills\u002Frobot-perception\u002FSKILL.md",true,[],[76,86,96,105,111,118],{"skillNo":77,"name":78,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":82,"publishedAt":47},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[81],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[83,84,85],"model","model hierarchy","model hierarchy skill",{"skillNo":87,"name":88,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":92,"publishedAt":47},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[91],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[93,94,95],"MCP","zoom","zoom mcp",{"skillNo":97,"name":98,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":47},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[102,103,104,94],"sdk","zoom apps sdk","apps",{"skillNo":106,"name":107,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":47},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[107],{"skillNo":112,"name":113,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":117,"publishedAt":47},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[116],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[113],{"skillNo":119,"name":120,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":121,"categories":122,"keywords":123,"publishedAt":47},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[120]]