Download droid/scripts/validate_cartesian_projection.py from zhicao/openpi: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/datasets/zhicao/openpi/resolve/main/droid/scripts/validate_cartesian_projection.py
- Command line
-
hf download hf://datasets/zhicao/openpi/droid/scripts/validate_cartesian_projection.py
-
curl -L -o validate_cartesian_projection.py https://huggingface.co/datasets/zhicao/openpi/resolve/main/droid/scripts/validate_cartesian_projection.py
12.6 kB
| """ | |
| Validation Script for Cartesian-Based Mesh Projection | |
| Tests and compares: | |
| 1. FK-based projection (joint_position → PyBullet FK → mesh points) | |
| 2. Cartesian-based projection (cartesian_position → direct transform → mesh points) | |
| Outputs visualization showing both methods side-by-side. | |
| """ | |
| import numpy as np | |
| import tensorflow_datasets as tfds | |
| from pathlib import Path | |
| import argparse | |
| import cv2 | |
| import sys | |
| # Add parent directory to path | |
| sys.path.append(str(Path(__file__).parent.parent)) | |
| from utils.load_camera_calibration import CameraCalibrationLoader | |
| from utils.franka_mesh_projection import FrankaMeshProjector | |
| def visualize_comparison(img: np.ndarray, | |
| points_fk: np.ndarray, | |
| points_cart: np.ndarray, | |
| vis_fk: np.ndarray, | |
| vis_cart: np.ndarray, | |
| title: str = "") -> np.ndarray: | |
| """ | |
| Create side-by-side comparison of FK vs Cartesian projections. | |
| Args: | |
| img: Base image (H, W, 3) | |
| points_fk: Points from FK method (32, 2) | |
| points_cart: Points from Cartesian method (32, 2) | |
| vis_fk: Visibility mask from FK (32,) | |
| vis_cart: Visibility mask from Cartesian (32,) | |
| title: Title for visualization | |
| Returns: | |
| Combined visualization image | |
| """ | |
| # Create two copies of the image | |
| img_fk = img.copy() | |
| img_cart = img.copy() | |
| # Draw FK points (blue for grid, green for mesh) | |
| for i in range(32): | |
| if vis_fk[i]: | |
| pt = tuple(points_fk[i].astype(int)) | |
| color = (0, 0, 255) if i < 25 else (0, 255, 0) # Blue grid, green mesh | |
| cv2.circle(img_fk, pt, 3, color, -1) | |
| cv2.putText(img_fk, str(i), (pt[0]+5, pt[1]-5), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.3, color, 1) | |
| # Draw Cartesian points (blue for grid, red for mesh) | |
| for i in range(32): | |
| if vis_cart[i]: | |
| pt = tuple(points_cart[i].astype(int)) | |
| color = (0, 0, 255) if i < 25 else (255, 0, 0) # Blue grid, red mesh | |
| cv2.circle(img_cart, pt, 3, color, -1) | |
| cv2.putText(img_cart, str(i), (pt[0]+5, pt[1]-5), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.3, color, 1) | |
| # Add labels | |
| cv2.putText(img_fk, "FK (Joint → PyBullet)", (10, 30), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) | |
| cv2.putText(img_cart, "Cartesian (Direct Transform)", (10, 30), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) | |
| # Compute difference for mesh points (last 7) | |
| mesh_diff = np.linalg.norm(points_fk[25:] - points_cart[25:], axis=1) | |
| avg_diff = np.mean(mesh_diff) | |
| max_diff = np.max(mesh_diff) | |
| cv2.putText(img_cart, f"Avg diff: {avg_diff:.1f}px", (10, 60), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2) | |
| cv2.putText(img_cart, f"Max diff: {max_diff:.1f}px", (10, 90), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2) | |
| # Combine side-by-side | |
| combined = np.hstack([img_fk, img_cart]) | |
| # Add title | |
| if title: | |
| title_bar = np.zeros((50, combined.shape[1], 3), dtype=np.uint8) | |
| cv2.putText(title_bar, title, (10, 35), | |
| cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2) | |
| combined = np.vstack([title_bar, combined]) | |
| return combined | |
| def validate_episode(droid_path: str, | |
| calib_dir: str, | |
| episode_index: int = 0, | |
| num_frames: int = 5, | |
| output_dir: str = "/tmp/droid_validation"): | |
| """ | |
| Validate cartesian projection on a single DROID episode. | |
| Args: | |
| droid_path: Path to DROID RLDS dataset | |
| calib_dir: Path to camera calibration directory | |
| episode_index: Episode index to test | |
| num_frames: Number of frames to visualize | |
| output_dir: Directory for output images | |
| """ | |
| print(f"Loading DROID episode {episode_index}...") | |
| # Load RLDS dataset | |
| builder = tfds.builder_from_directory(droid_path) | |
| dataset = builder.as_dataset(split='train') | |
| # Initialize tools | |
| calib_loader = CameraCalibrationLoader(calib_dir) | |
| projector = FrankaMeshProjector(use_gui=False) | |
| # Find episode | |
| for idx, episode in enumerate(dataset): | |
| if idx != episode_index: | |
| continue | |
| # Extract metadata | |
| try: | |
| recording_path = episode['episode_metadata']['recording_folderpath'].numpy().decode('utf-8') | |
| print(f" Recording: {recording_path}") | |
| except: | |
| print(f" Warning: Could not extract recording path") | |
| # Get steps | |
| steps = list(episode['steps']) | |
| print(f" Total steps: {len(steps)}") | |
| # Try to extract UUID from episode metadata | |
| uuid = None | |
| try: | |
| # DROID stores UUID in different possible fields | |
| if 'uuid' in episode['episode_metadata']: | |
| uuid = episode['episode_metadata']['uuid'].numpy().decode('utf-8') | |
| print(f" UUID from metadata: {uuid}") | |
| else: | |
| # Try to find it from file_path or other fields | |
| print(f" Warning: UUID not found in episode_metadata") | |
| print(f" Available keys: {list(episode['episode_metadata'].keys())}") | |
| # List all camera calibration files to find potential matches | |
| from pathlib import Path | |
| calib_path = Path(calib_dir) | |
| calib_files = sorted(calib_path.glob("*_cameras.json")) | |
| print(f" Found {len(calib_files)} calibration files") | |
| if len(calib_files) > 0: | |
| # Try first calibration file as test | |
| uuid = calib_files[episode_index % len(calib_files)].stem.replace('_cameras', '') | |
| print(f" Using test UUID: {uuid}") | |
| else: | |
| print(f"✗ No calibration files found") | |
| return | |
| except Exception as e: | |
| print(f"✗ Error extracting UUID: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| return | |
| if uuid is None: | |
| print(f"✗ Could not determine UUID for episode") | |
| return | |
| try: | |
| # Check if refined extrinsics available | |
| has_refined = calib_loader.has_refined_extrinsics(uuid) | |
| print(f" Refined extrinsics: {has_refined}") | |
| # Load calibration (with fallback) | |
| dual_params = calib_loader.get_dual_view_params( | |
| uuid, | |
| param_type='refined', | |
| require_refined=False | |
| ) | |
| if dual_params is None: | |
| print(f"✗ No camera calibration available for UUID: {uuid}") | |
| return | |
| except Exception as e: | |
| print(f"✗ Error loading calibration for {uuid}: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| return | |
| # Create output directory | |
| output_path = Path(output_dir) | |
| output_path.mkdir(parents=True, exist_ok=True) | |
| # Sample frames uniformly | |
| sample_indices = np.linspace(0, len(steps)-1, num_frames, dtype=int) | |
| print(f"\nProcessing {num_frames} frames...") | |
| print("=" * 80) | |
| for i, step_idx in enumerate(sample_indices): | |
| step = steps[step_idx] | |
| # Get robot states | |
| joint_pos = step['observation']['joint_position'].numpy() | |
| cart_pos = step['observation']['cartesian_position'].numpy() | |
| print(f"\nFrame {step_idx} ({i+1}/{num_frames}):") | |
| print(f" Joint position: {joint_pos}") | |
| print(f" Cartesian position: {cart_pos}") | |
| # Process exterior camera | |
| img_ext_bytes = step['observation']['exterior_image_1_left'].numpy() | |
| img_ext = cv2.imdecode(np.frombuffer(img_ext_bytes, dtype=np.uint8), cv2.IMREAD_COLOR) | |
| if img_ext is None: | |
| print(f" ✗ Failed to decode exterior image") | |
| continue | |
| img_ext = cv2.resize(img_ext, (448, 448)) | |
| img_ext_rgb = cv2.cvtColor(img_ext, cv2.COLOR_BGR2RGB) | |
| K_ext, E_ext = dual_params['exterior_1'] | |
| # FK-based projection | |
| points_fk, vis_fk = projector.project_32_points( | |
| joint_pos, K_ext, E_ext, img_h=448, img_w=448 | |
| ) | |
| # Cartesian-based projection (Euler XYZ - confirmed by rotation format test) | |
| points_cart, vis_cart = projector.project_32_points_cartesian( | |
| cart_pos, K_ext, E_ext, img_h=448, img_w=448, rotation_format='euler_xyz' | |
| ) | |
| # Compute differences for mesh points (indices 25-31) | |
| mesh_diff = np.linalg.norm(points_fk[25:] - points_cart[25:], axis=1) | |
| print(f" Mesh point differences (FK vs Cartesian):") | |
| for j, diff in enumerate(mesh_diff): | |
| vis_str = "✓" if (vis_fk[25+j] and vis_cart[25+j]) else "✗" | |
| print(f" Point {25+j}: {diff:6.2f}px {vis_str}") | |
| print(f" Average: {np.mean(mesh_diff):.2f}px") | |
| print(f" Maximum: {np.max(mesh_diff):.2f}px") | |
| # Create visualization | |
| viz = visualize_comparison( | |
| img_ext_rgb, | |
| points_fk, | |
| points_cart, | |
| vis_fk, | |
| vis_cart, | |
| title=f"Episode {episode_index} | Frame {step_idx} | Exterior Camera" | |
| ) | |
| # Save | |
| output_file = output_path / f"frame_{step_idx:04d}_exterior.jpg" | |
| cv2.imwrite(str(output_file), cv2.cvtColor(viz, cv2.COLOR_RGB2BGR)) | |
| print(f" ✓ Saved: {output_file}") | |
| # Process wrist camera | |
| img_wrist_bytes = step['observation']['wrist_image_left'].numpy() | |
| img_wrist = cv2.imdecode(np.frombuffer(img_wrist_bytes, dtype=np.uint8), cv2.IMREAD_COLOR) | |
| if img_wrist is not None: | |
| img_wrist = cv2.resize(img_wrist, (448, 448)) | |
| img_wrist_rgb = cv2.cvtColor(img_wrist, cv2.COLOR_BGR2RGB) | |
| K_wrist, E_wrist = dual_params['wrist'] | |
| points_fk_w, vis_fk_w = projector.project_32_points( | |
| joint_pos, K_wrist, E_wrist, img_h=448, img_w=448 | |
| ) | |
| points_cart_w, vis_cart_w = projector.project_32_points_cartesian( | |
| cart_pos, K_wrist, E_wrist, img_h=448, img_w=448, rotation_format='auto' | |
| ) | |
| viz_wrist = visualize_comparison( | |
| img_wrist_rgb, | |
| points_fk_w, | |
| points_cart_w, | |
| vis_fk_w, | |
| vis_cart_w, | |
| title=f"Episode {episode_index} | Frame {step_idx} | Wrist Camera" | |
| ) | |
| output_file_wrist = output_path / f"frame_{step_idx:04d}_wrist.jpg" | |
| cv2.imwrite(str(output_file_wrist), cv2.cvtColor(viz_wrist, cv2.COLOR_RGB2BGR)) | |
| print(f" ✓ Saved: {output_file_wrist}") | |
| print(f"\n{'='*80}") | |
| print(f"✓ Validation complete. Output saved to: {output_path}") | |
| return | |
| print(f"✗ Episode {episode_index} not found") | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| description="Validate cartesian-based mesh projection on DROID data" | |
| ) | |
| parser.add_argument( | |
| '--droid-path', | |
| type=str, | |
| default='/mnt/kevin/data/droid/droid/1.0.0', | |
| help='Path to DROID RLDS dataset' | |
| ) | |
| parser.add_argument( | |
| '--calib-dir', | |
| type=str, | |
| default='/root/workspace/code/wmrl/Dual-Dynamics-Models/DROID-main/vision/u/wenlongh/datasets/droid_v4/cameras', | |
| help='Path to camera calibration directory' | |
| ) | |
| parser.add_argument( | |
| '--episode-index', | |
| type=int, | |
| default=0, | |
| help='Episode index to validate' | |
| ) | |
| parser.add_argument( | |
| '--num-frames', | |
| type=int, | |
| default=5, | |
| help='Number of frames to visualize' | |
| ) | |
| parser.add_argument( | |
| '--output-dir', | |
| type=str, | |
| default='/tmp/droid_validation', | |
| help='Output directory for visualizations' | |
| ) | |
| args = parser.parse_args() | |
| print("=" * 80) | |
| print("DROID Cartesian Projection Validation") | |
| print("=" * 80) | |
| print() | |
| validate_episode( | |
| args.droid_path, | |
| args.calib_dir, | |
| args.episode_index, | |
| args.num_frames, | |
| args.output_dir | |
| ) | |
| if __name__ == "__main__": | |
| main() | |