| """ |
| Visualize 7 gripper mesh points on both exterior and wrist views. |
| |
| The 7 points are offsets from action position (gripper base), transformed by gripper rotation: |
| 1. [0.0, 0.0, 0.0] - gripper base (action position) |
| 2. [0.0, 0.045, 0.161] - finger 1 tip |
| 3. [0.0, -0.045, 0.161] - finger 2 tip |
| 4. [0.0, 0.045, 0.13] - finger 1 end |
| 5. [0.0, -0.045, 0.13] - finger 2 end |
| 6. [0.0, 0.0, 0.13] - gripper center front |
| 7. [0.0, 0.0, 0.065] - gripper center middle |
| """ |
|
|
| import sys |
| from pathlib import Path |
| sys.path.append(str(Path(__file__).parent.parent)) |
|
|
| import os |
| import numpy as np |
| import torch |
| 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 scipy.spatial.transform import Rotation as R |
|
|
| from utils.load_camera_calibration import CameraCalibrationLoader |
| from utils.franka_mesh_projection import FrankaMeshProjector |
|
|
|
|
| |
| GRIPPER_OFFSETS = np.array([ |
| [0.0, 0.0, 0.0], |
| [0.0, 0.045, 0.161], |
| [0.0, -0.045, 0.161], |
| [0.0, 0.045, 0.13], |
| [0.0, -0.045, 0.13], |
| [0.0, 0.0, 0.13], |
| [0.0, 0.0, 0.065], |
| ]) |
|
|
| POINT_COLORS = [ |
| (255, 255, 0), |
| (0, 0, 255), |
| (0, 0, 255), |
| (0, 255, 255), |
| (0, 255, 255), |
| (0, 255, 0), |
| (255, 0, 255), |
| ] |
|
|
|
|
| def euler_xyz_to_rotation_matrix(euler_xyz): |
| """Convert Euler XYZ angles to rotation matrix.""" |
| return R.from_euler('xyz', euler_xyz).as_matrix() |
|
|
|
|
| def transform_gripper_offsets(action): |
| """ |
| Transform gripper offsets using action position and rotation. |
| |
| Args: |
| action: [x, y, z, rx, ry, rz, gripper] - Euler XYZ rotation |
| |
| Returns: |
| gripper_points_3d: [7, 3] array of 3D points in world frame |
| """ |
| pos = action[:3] |
| rot_euler = action[3:6] |
|
|
| |
| rot_matrix = euler_xyz_to_rotation_matrix(rot_euler) |
|
|
| |
| gripper_points_3d = (rot_matrix @ GRIPPER_OFFSETS.T).T + pos |
|
|
| return gripper_points_3d |
|
|
|
|
| def find_closest_calibration(episode, uuid_list): |
| """Find closest calibration by timestamp.""" |
| 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 process_dual_view_episode(episode, episode_idx, uuid, calib_loader, projector, max_frames=16): |
| """ |
| Process episode with both exterior and wrist views. |
| |
| Returns: |
| dict with frames and projections for both views, or None if failed |
| """ |
| |
| try: |
| dual_params = calib_loader.get_dual_view_params(uuid, param_type='refined', require_refined=False) |
| if dual_params is None: |
| return None |
| if not calib_loader.has_refined_extrinsics(uuid): |
| return None |
| except: |
| return None |
|
|
| K_ext, E_ext = dual_params['exterior_1'] |
| K_wrist, E_wrist = dual_params['wrist'] |
|
|
| |
| frames_ext = [] |
| frames_wrist = [] |
| actions = [] |
|
|
| for step_idx, step in enumerate(episode['steps']): |
| if step_idx >= max_frames: |
| break |
|
|
| img_ext = step['observation']['exterior_image_1_left'].numpy() |
| img_wrist = step['observation']['wrist_image_left'].numpy() |
|
|
| if img_ext is None or len(img_ext.shape) != 3: |
| continue |
| if img_wrist is None or len(img_wrist.shape) != 3: |
| continue |
|
|
| frames_ext.append(img_ext) |
| frames_wrist.append(img_wrist) |
| actions.append(step['action'].numpy()) |
|
|
| if len(frames_ext) < 10: |
| return None |
|
|
| img_h_ext, img_w_ext = frames_ext[0].shape[:2] |
| img_h_wrist, img_w_wrist = frames_wrist[0].shape[:2] |
|
|
| |
| all_gripper_3d = [] |
| all_gripper_2d_ext = [] |
| all_gripper_vis_ext = [] |
| all_gripper_2d_wrist = [] |
| all_gripper_vis_wrist = [] |
|
|
| for action in actions: |
| |
| gripper_3d = transform_gripper_offsets(action) |
|
|
| |
| gripper_2d_ext, gripper_vis_ext = projector._project_3d_to_2d( |
| gripper_3d, K_ext, E_ext, img_h=img_h_ext, img_w=img_w_ext |
| ) |
|
|
| |
| E_wrist_inv = np.linalg.inv(E_wrist) |
| gripper_2d_wrist, gripper_vis_wrist = projector._project_3d_to_2d( |
| gripper_3d, K_wrist, E_wrist_inv, img_h=img_h_wrist, img_w=img_w_wrist |
| ) |
|
|
| all_gripper_3d.append(gripper_3d) |
| all_gripper_2d_ext.append(gripper_2d_ext) |
| all_gripper_vis_ext.append(gripper_vis_ext) |
| all_gripper_2d_wrist.append(gripper_2d_wrist) |
| all_gripper_vis_wrist.append(gripper_vis_wrist) |
|
|
| all_gripper_3d = np.array(all_gripper_3d) |
| all_gripper_2d_ext = np.array(all_gripper_2d_ext) |
| all_gripper_vis_ext = np.array(all_gripper_vis_ext) |
| all_gripper_2d_wrist = np.array(all_gripper_2d_wrist) |
| all_gripper_vis_wrist = np.array(all_gripper_vis_wrist) |
|
|
| return { |
| 'frames_ext': frames_ext, |
| 'frames_wrist': frames_wrist, |
| 'gripper_3d': all_gripper_3d, |
| 'gripper_2d_ext': all_gripper_2d_ext, |
| 'gripper_vis_ext': all_gripper_vis_ext, |
| 'gripper_2d_wrist': all_gripper_2d_wrist, |
| 'gripper_vis_wrist': all_gripper_vis_wrist, |
| 'actions': np.array(actions), |
| } |
|
|
|
|
| def create_dual_view_video(result, output_path): |
| """Create side-by-side video with exterior (left) and wrist (right) views.""" |
|
|
| frames_ext = result['frames_ext'] |
| frames_wrist = result['frames_wrist'] |
| gripper_2d_ext = result['gripper_2d_ext'] |
| gripper_vis_ext = result['gripper_vis_ext'] |
| gripper_2d_wrist = result['gripper_2d_wrist'] |
| gripper_vis_wrist = result['gripper_vis_wrist'] |
|
|
| video_frames = [] |
|
|
| for frame_idx in range(len(frames_ext)): |
| |
| viz_ext = frames_ext[frame_idx].copy() |
|
|
| |
| for pt_idx in range(7): |
| if gripper_vis_ext[frame_idx, pt_idx]: |
| pt = tuple(gripper_2d_ext[frame_idx, pt_idx].astype(int)) |
| color = POINT_COLORS[pt_idx] |
| cv2.circle(viz_ext, pt, 4, color, -1) |
| cv2.putText(viz_ext, str(pt_idx), (pt[0]+6, pt[1]-6), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.4, color, 1) |
|
|
| |
| cv2.putText(viz_ext, "EXTERIOR VIEW", (10, 20), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) |
|
|
| |
| viz_wrist = frames_wrist[frame_idx].copy() |
|
|
| |
| for pt_idx in range(7): |
| if gripper_vis_wrist[frame_idx, pt_idx]: |
| pt = tuple(gripper_2d_wrist[frame_idx, pt_idx].astype(int)) |
| color = POINT_COLORS[pt_idx] |
| cv2.circle(viz_wrist, pt, 4, color, -1) |
| cv2.putText(viz_wrist, str(pt_idx), (pt[0]+6, pt[1]-6), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.4, color, 1) |
|
|
| |
| cv2.putText(viz_wrist, "WRIST VIEW", (10, 20), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) |
|
|
| |
| combined = np.concatenate([viz_ext, viz_wrist], axis=1) |
|
|
| |
| cv2.putText(combined, f"Frame {frame_idx}/{len(frames_ext)}", |
| (combined.shape[1]//2 - 50, 20), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 2) |
|
|
| legend_y = combined.shape[0] - 110 |
| cv2.putText(combined, "0:Base 1-2:FingerTips 3-4:FingerEnds 5:Front 6:Mid", |
| (10, legend_y), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1) |
|
|
| video_frames.append(combined) |
|
|
| |
| media.write_video(str(output_path), video_frames, fps=10) |
|
|
|
|
| def main(): |
| output_dir = Path('/tmp/droid_dual_view_gripper') |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| print("=" * 80) |
| print("Visualizing 7 Gripper Points on Dual Views (Exterior + Wrist)") |
| print("=" * 80) |
|
|
| |
| 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' |
| print("Loading DROID dataset...") |
| builder = tfds.builder_from_directory(droid_path) |
| dataset = builder.as_dataset(split='train') |
|
|
| |
| num_videos = 3 |
| created_count = 0 |
|
|
| for episode_idx, episode in enumerate(dataset): |
| if created_count >= num_videos: |
| break |
|
|
| uuid = find_closest_calibration(episode, uuid_list) |
| if uuid is None: |
| continue |
|
|
| if not calib_loader.has_refined_extrinsics(uuid): |
| continue |
|
|
| print(f"\nProcessing episode {episode_idx}...") |
|
|
| result = process_dual_view_episode( |
| episode, episode_idx, uuid, calib_loader, projector, max_frames=16 |
| ) |
|
|
| if result is None: |
| print(f" Skipped - processing failed") |
| continue |
|
|
| |
| output_path = output_dir / f"dual_view_episode_{episode_idx:04d}.mp4" |
| create_dual_view_video(result, output_path) |
|
|
| |
| vis_ext = result['gripper_vis_ext'][0] |
| vis_wrist = result['gripper_vis_wrist'][0] |
| print(f" Exterior view - visible points: {vis_ext.sum()}/7") |
| print(f" Wrist view - visible points: {vis_wrist.sum()}/7") |
| print(f" ✓ Saved: {output_path}") |
|
|
| created_count += 1 |
|
|
| print("\n" + "=" * 80) |
| print(f"Created {created_count} dual-view videos") |
| print(f"Output directory: {output_dir}") |
| print("=" * 80) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|