| """ |
| Test Mesh Projection |
| |
| Verifies that Franka mesh projection works correctly with camera calibration. |
| Optionally visualizes the projected points on images. |
| """ |
|
|
| import sys |
| import numpy as np |
| from pathlib import Path |
| import argparse |
|
|
| |
| sys.path.append(str(Path(__file__).parent.parent)) |
|
|
| from utils.load_camera_calibration import CameraCalibrationLoader |
| from utils.franka_mesh_projection import FrankaMeshProjector |
|
|
|
|
| def test_forward_kinematics(): |
| """Test forward kinematics computation.""" |
| print("=" * 60) |
| print("Test 1: Forward Kinematics") |
| print("=" * 60) |
|
|
| try: |
| projector = FrankaMeshProjector(use_gui=False) |
|
|
| |
| joint_configs = { |
| 'home': np.array([0.0, -0.785, 0.0, -2.356, 0.0, 1.571, 0.785]), |
| 'extended': np.array([0.0, 0.0, 0.0, -1.571, 0.0, 1.571, 0.785]), |
| 'folded': np.array([0.0, -1.571, 0.0, -2.356, 0.0, 0.785, 0.0]), |
| } |
|
|
| for name, joint_pos in joint_configs.items(): |
| pos, orn = projector.forward_kinematics(joint_pos) |
| print(f"\n {name} configuration:") |
| print(f" EE position: [{pos[0]:.3f}, {pos[1]:.3f}, {pos[2]:.3f}]") |
| print(f" EE orientation (quat): [{orn[0]:.3f}, {orn[1]:.3f}, {orn[2]:.3f}, {orn[3]:.3f}]") |
|
|
| print("\n✓ Forward kinematics working!") |
| return True |
|
|
| except Exception as e: |
| print(f"✗ Forward kinematics failed: {e}") |
| import traceback |
| traceback.print_exc() |
| return False |
|
|
|
|
| def test_mesh_extraction(): |
| """Test gripper mesh vertex extraction.""" |
| print("\n" + "=" * 60) |
| print("Test 2: Gripper Mesh Vertex Extraction") |
| print("=" * 60) |
|
|
| try: |
| projector = FrankaMeshProjector(use_gui=False) |
|
|
| joint_pos = np.array([0.0, -0.785, 0.0, -2.356, 0.0, 1.571, 0.785]) |
| mesh_vertices = projector.get_gripper_mesh_vertices(joint_pos) |
|
|
| print(f"✓ Extracted {len(mesh_vertices)} mesh vertices") |
| print(f" Vertex positions (first 7):") |
| for i, vertex in enumerate(mesh_vertices[:7]): |
| print(f" {i}: [{vertex[0]:.4f}, {vertex[1]:.4f}, {vertex[2]:.4f}]") |
|
|
| |
| assert len(mesh_vertices) == 7, f"Expected 7 vertices, got {len(mesh_vertices)}" |
|
|
| return True |
|
|
| except Exception as e: |
| print(f"✗ Mesh extraction failed: {e}") |
| import traceback |
| traceback.print_exc() |
| return False |
|
|
|
|
| def test_grid_generation(): |
| """Test 5x5 grid point generation.""" |
| print("\n" + "=" * 60) |
| print("Test 3: Grid Point Generation") |
| print("=" * 60) |
|
|
| try: |
| projector = FrankaMeshProjector(use_gui=False) |
|
|
| grid_points = projector.generate_grid_points(img_h=448, img_w=448, grid_size=5) |
|
|
| print(f"✓ Generated {len(grid_points)} grid points") |
| print(f" Grid points (corners):") |
| print(f" Top-left: [{grid_points[0, 0]:.1f}, {grid_points[0, 1]:.1f}]") |
| print(f" Top-right: [{grid_points[4, 0]:.1f}, {grid_points[4, 1]:.1f}]") |
| print(f" Bottom-left: [{grid_points[20, 0]:.1f}, {grid_points[20, 1]:.1f}]") |
| print(f" Bottom-right: [{grid_points[24, 0]:.1f}, {grid_points[24, 1]:.1f}]") |
| print(f" Center: [{grid_points[12, 0]:.1f}, {grid_points[12, 1]:.1f}]") |
|
|
| |
| assert len(grid_points) == 25, f"Expected 25 grid points, got {len(grid_points)}" |
|
|
| |
| assert np.all(grid_points >= 0) and np.all(grid_points <= 448), "Grid points outside image bounds" |
|
|
| return True |
|
|
| except Exception as e: |
| print(f"✗ Grid generation failed: {e}") |
| import traceback |
| traceback.print_exc() |
| return False |
|
|
|
|
| def test_32_point_projection(): |
| """Test full 32-point projection (25 grid + 7 mesh).""" |
| print("\n" + "=" * 60) |
| print("Test 4: 32-Point Projection") |
| print("=" * 60) |
|
|
| try: |
| |
| uuid = "AUTOLab+0d4edc83+2023-10-21-19h-02m-35s" |
| calib_loader = CameraCalibrationLoader() |
| dual_params = calib_loader.get_dual_view_params(uuid) |
|
|
| |
| projector = FrankaMeshProjector(use_gui=False) |
|
|
| |
| joint_pos = np.array([0.0, -0.785, 0.0, -2.356, 0.0, 1.571, 0.785]) |
|
|
| |
| for view_name, (K, E) in dual_params.items(): |
| points_32, visibility_32 = projector.project_32_points( |
| joint_pos, K, E, img_h=448, img_w=448 |
| ) |
|
|
| print(f"\n {view_name}:") |
| print(f" Total points: {len(points_32)}") |
| print(f" Grid points (25): {points_32[:25].shape}") |
| print(f" Mesh points (7): {points_32[25:].shape}") |
| print(f" Visible: {visibility_32.sum()}/{len(visibility_32)}") |
| print(f" Point range: X=[{points_32[:, 0].min():.1f}, {points_32[:, 0].max():.1f}], " |
| f"Y=[{points_32[:, 1].min():.1f}, {points_32[:, 1].max():.1f}]") |
|
|
| |
| assert points_32.shape == (32, 2), f"Expected (32, 2), got {points_32.shape}" |
| assert visibility_32.shape == (32,), f"Expected (32,), got {visibility_32.shape}" |
|
|
| |
| assert np.all(visibility_32[:25]), "Grid points should all be visible" |
|
|
| print("\n✓ 32-point projection working!") |
| return True |
|
|
| except Exception as e: |
| print(f"✗ 32-point projection failed: {e}") |
| import traceback |
| traceback.print_exc() |
| return False |
|
|
|
|
| def test_with_visualization(output_dir: str = "/tmp/droid_projection_test"): |
| """Test projection with visualization (requires matplotlib).""" |
| print("\n" + "=" * 60) |
| print("Test 5: Projection Visualization") |
| print("=" * 60) |
|
|
| try: |
| import matplotlib.pyplot as plt |
| import matplotlib.patches as patches |
|
|
| |
| uuid = "AUTOLab+0d4edc83+2023-10-21-19h-02m-35s" |
| calib_loader = CameraCalibrationLoader() |
| dual_params = calib_loader.get_dual_view_params(uuid) |
| projector = FrankaMeshProjector(use_gui=False) |
|
|
| |
| output_path = Path(output_dir) |
| output_path.mkdir(parents=True, exist_ok=True) |
|
|
| |
| joint_configs = { |
| 'home': np.array([0.0, -0.785, 0.0, -2.356, 0.0, 1.571, 0.785]), |
| 'extended': np.array([0.0, 0.0, 0.0, -1.571, 0.0, 1.571, 0.785]), |
| } |
|
|
| for config_name, joint_pos in joint_configs.items(): |
| fig, axes = plt.subplots(1, 2, figsize=(12, 6)) |
| fig.suptitle(f"32-Point Projection - {config_name} configuration", fontsize=14) |
|
|
| for ax_idx, (view_name, (K, E)) in enumerate(dual_params.items()): |
| |
| points_32, vis_32 = projector.project_32_points( |
| joint_pos, K, E, img_h=448, img_w=448 |
| ) |
|
|
| |
| ax = axes[ax_idx] |
| ax.set_xlim(0, 448) |
| ax.set_ylim(448, 0) |
| ax.set_aspect('equal') |
| ax.set_title(f"{view_name}") |
| ax.set_xlabel("X (pixels)") |
| ax.set_ylabel("Y (pixels)") |
|
|
| |
| grid_points = points_32[:25] |
| ax.scatter(grid_points[:, 0], grid_points[:, 1], |
| c='blue', s=50, alpha=0.6, label='Grid (25)') |
|
|
| |
| mesh_points = points_32[25:] |
| mesh_vis = vis_32[25:] |
| ax.scatter(mesh_points[mesh_vis, 0], mesh_points[mesh_vis, 1], |
| c='red', s=100, marker='x', linewidths=2, label='Mesh (7)') |
|
|
| |
| if not np.all(mesh_vis): |
| ax.scatter(mesh_points[~mesh_vis, 0], mesh_points[~mesh_vis, 1], |
| c='gray', s=50, marker='o', alpha=0.3, label='Invisible') |
|
|
| ax.legend() |
| ax.grid(True, alpha=0.3) |
|
|
| |
| output_file = output_path / f"projection_{config_name}.png" |
| plt.tight_layout() |
| plt.savefig(output_file, dpi=150) |
| plt.close() |
|
|
| print(f" ✓ Saved visualization: {output_file}") |
|
|
| print(f"\n✓ Visualizations saved to {output_path}") |
| return True |
|
|
| except ImportError: |
| print(" ⚠ Matplotlib not available, skipping visualization test") |
| return True |
| except Exception as e: |
| print(f"✗ Visualization failed: {e}") |
| import traceback |
| traceback.print_exc() |
| return False |
|
|
|
|
| def main(): |
| """Run all tests.""" |
| parser = argparse.ArgumentParser(description="Test Franka mesh projection") |
| parser.add_argument('--visualize', action='store_true', help='Generate visualization plots') |
| parser.add_argument('--output-dir', type=str, default='/tmp/droid_projection_test', |
| help='Output directory for visualizations') |
| args = parser.parse_args() |
|
|
| print("\n" + "=" * 60) |
| print("DROID Mesh Projection Test Suite") |
| print("=" * 60 + "\n") |
|
|
| tests = [ |
| test_forward_kinematics, |
| test_mesh_extraction, |
| test_grid_generation, |
| test_32_point_projection, |
| ] |
|
|
| if args.visualize: |
| tests.append(lambda: test_with_visualization(args.output_dir)) |
|
|
| results = [] |
| for test_func in tests: |
| try: |
| result = test_func() |
| results.append(result) |
| except Exception as e: |
| print(f"✗ Test crashed: {e}") |
| import traceback |
| traceback.print_exc() |
| results.append(False) |
|
|
| |
| print("\n" + "=" * 60) |
| print("Test Summary") |
| print("=" * 60) |
| passed = sum(results) |
| total = len(results) |
| print(f"Passed: {passed}/{total}") |
|
|
| if passed == total: |
| print("✓ All tests passed!") |
| return 0 |
| else: |
| print(f"✗ {total - passed} test(s) failed") |
| return 1 |
|
|
|
|
| if __name__ == "__main__": |
| sys.exit(main()) |
|
|