Download droid/scripts/test_wrist_fixed_points.py from zhicao/openpi: direct link, hf CLI and curl.
- Browser
- Download file 6.94 kB
-
https://huggingface.co/datasets/zhicao/openpi/resolve/main/droid/scripts/test_wrist_fixed_points.py
- Command line
-
hf download hf://datasets/zhicao/openpi/droid/scripts/test_wrist_fixed_points.py
-
curl -L -o test_wrist_fixed_points.py https://huggingface.co/datasets/zhicao/openpi/resolve/main/droid/scripts/test_wrist_fixed_points.py
6.94 kB
| """ | |
| Test wrist camera projection with simple fixed points at known locations. | |
| This verifies the projection math is working, ignoring gripper semantics. | |
| """ | |
| import sys | |
| from pathlib import Path | |
| sys.path.append(str(Path(__file__).parent.parent)) | |
| import numpy as np | |
| import mediapy as media | |
| import tensorflow as tf | |
| tf.config.set_visible_devices([], 'GPU') | |
| import tensorflow_datasets as tfds | |
| import cv2 | |
| import datetime | |
| import re | |
| from utils.load_camera_calibration import CameraCalibrationLoader | |
| from utils.franka_mesh_projection import FrankaMeshProjector | |
| def find_closest_calibration(episode, uuid_list): | |
| try: | |
| recording_path = episode['episode_metadata']['recording_folderpath'].numpy().decode('utf-8') | |
| match = re.search(r'/([A-Z]+)/success/(\d{4}-\d{2}-\d{2})/\w+_\w+_+\d+_(\d{2}):(\d{2}):(\d{2})_\d{4}/', recording_path) | |
| if not match: | |
| return None | |
| lab, date, hour, minute, second = match.groups() | |
| episode_time = datetime.datetime.strptime(f"{date} {hour}:{minute}:{second}", "%Y-%m-%d %H:%M:%S") | |
| matching_calibs = [uuid for uuid in uuid_list if uuid.startswith(f"{lab}+") and f"+{date}-" in uuid] | |
| if len(matching_calibs) == 0: | |
| return None | |
| best_uuid = None | |
| min_time_diff = float('inf') | |
| for calib_uuid in matching_calibs: | |
| parts = calib_uuid.split('+') | |
| if len(parts) >= 3: | |
| time_str = parts[2].replace('_cameras', '') | |
| match_time = re.search(r'(\d{2})h-(\d{2})m-(\d{2})s', time_str) | |
| if match_time: | |
| calib_hour = int(match_time.group(1)) | |
| calib_min = int(match_time.group(2)) | |
| calib_sec = int(match_time.group(3)) | |
| calib_time = datetime.datetime.strptime( | |
| f"{date} {calib_hour}:{calib_min}:{calib_sec}", | |
| "%Y-%m-%d %H:%M:%S" | |
| ) | |
| time_diff = abs((episode_time - calib_time).total_seconds()) | |
| if time_diff < min_time_diff: | |
| min_time_diff = time_diff | |
| best_uuid = calib_uuid | |
| return best_uuid | |
| except: | |
| return None | |
| def main(): | |
| output_dir = Path('/tmp/droid_wrist_fixed_test') | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| print("=" * 80) | |
| print("Testing Wrist Projection with Fixed Points") | |
| print("=" * 80) | |
| print("\nStrategy: Project fixed points slightly in front of first frame action") | |
| print("This bypasses gripper rotation issues to test projection math.") | |
| calib_dir = '/root/workspace/code/wmrl/Dual-Dynamics-Models/DROID-main/vision/u/wenlongh/datasets/droid_v4/cameras' | |
| calib_loader = CameraCalibrationLoader(calib_dir) | |
| projector = FrankaMeshProjector(use_gui=False) | |
| calib_path = Path(calib_dir) | |
| uuid_list = [f.stem.replace('_cameras', '') for f in sorted(calib_path.glob("*_cameras.json"))] | |
| droid_path = '/mnt/kevin/data/droid/droid/1.0.0' | |
| builder = tfds.builder_from_directory(droid_path) | |
| dataset = builder.as_dataset(split='train') | |
| for episode_idx, episode in enumerate(dataset): | |
| if episode_idx > 3: # Just test first few | |
| break | |
| uuid = find_closest_calibration(episode, uuid_list) | |
| if uuid is None or not calib_loader.has_refined_extrinsics(uuid): | |
| continue | |
| print(f"\n{'='*80}") | |
| print(f"Episode {episode_idx}") | |
| print(f"{'='*80}") | |
| # Get first action position as reference | |
| step0 = next(iter(episode['steps'])) | |
| action0 = step0['action'].numpy() | |
| pos0 = action0[:3] | |
| print(f"First frame gripper position: {pos0}") | |
| # Create simple test points: grid in front of gripper | |
| test_points = [] | |
| for dx in [-0.05, 0, 0.05]: | |
| for dy in [-0.05, 0, 0.05]: | |
| test_points.append(pos0 + np.array([dx, dy, 0.1])) # 10cm in front | |
| test_points = np.array(test_points) | |
| print(f"Created {len(test_points)} test points in 3x3 grid") | |
| # Get wrist camera params | |
| dual_params = calib_loader.get_dual_view_params(uuid, param_type='refined', require_refined=True) | |
| K_wrist, E_wrist = dual_params['wrist'] | |
| # Get wrist frames | |
| frames_wrist = [] | |
| for step_idx, step in enumerate(episode['steps']): | |
| if step_idx >= 16: | |
| break | |
| img = step['observation']['wrist_image_left'].numpy() | |
| if img is not None: | |
| frames_wrist.append(img) | |
| if len(frames_wrist) < 10: | |
| continue | |
| img_h, img_w = frames_wrist[0].shape[:2] | |
| # Test both approaches | |
| E_wrist_inv = np.linalg.inv(E_wrist) | |
| # Project with both | |
| pts_2d_no_inv, vis_no_inv = projector._project_3d_to_2d( | |
| test_points, K_wrist, E_wrist, img_h=img_h, img_w=img_w | |
| ) | |
| pts_2d_inv, vis_inv = projector._project_3d_to_2d( | |
| test_points, K_wrist, E_wrist_inv, img_h=img_h, img_w=img_w | |
| ) | |
| print(f"\nProjection results on first frame:") | |
| print(f" No inversion: {vis_no_inv.sum()}/{len(test_points)} visible") | |
| print(f" With inversion: {vis_inv.sum()}/{len(test_points)} visible") | |
| # Create video | |
| video_frames = [] | |
| for frame in frames_wrist: | |
| viz_no_inv = frame.copy() | |
| viz_inv = frame.copy() | |
| # Draw points | |
| for i in range(len(test_points)): | |
| if vis_no_inv[i]: | |
| pt = tuple(pts_2d_no_inv[i].astype(int)) | |
| cv2.circle(viz_no_inv, pt, 3, (0, 255, 0), -1) | |
| cv2.putText(viz_no_inv, str(i), (pt[0]+5, pt[1]-5), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 255, 0), 1) | |
| if vis_inv[i]: | |
| pt = tuple(pts_2d_inv[i].astype(int)) | |
| cv2.circle(viz_inv, pt, 3, (0, 255, 0), -1) | |
| cv2.putText(viz_inv, str(i), (pt[0]+5, pt[1]-5), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 255, 0), 1) | |
| cv2.putText(viz_no_inv, "NO Inversion", (10, 20), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) | |
| cv2.putText(viz_inv, "WITH Inversion", (10, 20), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) | |
| combined = np.concatenate([viz_no_inv, viz_inv], axis=1) | |
| video_frames.append(combined) | |
| output_path = output_dir / f"fixed_points_episode_{episode_idx:04d}.mp4" | |
| media.write_video(str(output_path), video_frames, fps=10) | |
| print(f" ✓ Saved: {output_path}") | |
| print("\n" + "=" * 80) | |
| print("NOTE: Points should stay roughly fixed in wrist view since") | |
| print(" they're defined relative to first gripper position.") | |
| print("=" * 80) | |
| if __name__ == "__main__": | |
| main() | |