| """ |
| Test simple fixed offset to gripper tip. |
| |
| Based on earlier FK analysis, fingers are ~0.058m from flange. |
| Let's test if adding a fixed offset along the gripper z-axis works. |
| """ |
|
|
| 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 |
| import pybullet as p |
| from scipy.spatial.transform import Rotation as R |
|
|
| from utils.load_camera_calibration import CameraCalibrationLoader |
| from utils.franka_mesh_projection import FrankaMeshProjector |
|
|
|
|
| def load_cotracker(): |
| from cotracker.predictor import CoTrackerPredictor |
| device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
| model = CoTrackerPredictor(checkpoint='/mnt/kevin/vlm_models/cotracker/scaled_offline.pth') |
| model = model.to(device) |
| model.eval() |
| return model, device |
|
|
|
|
| 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_time = datetime.datetime.strptime( |
| f"{date} {match_time.group(1)}:{match_time.group(2)}:{match_time.group(3)}", |
| "%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 compute_gripper_tip(cartesian_position, joint_position, projector, offset_distance=0.058): |
| """ |
| Compute gripper tip by adding offset along gripper z-axis. |
| |
| Args: |
| cartesian_position: 6D [x, y, z, rx, ry, rz] flange pose |
| joint_position: 7D joint angles |
| projector: FrankaMeshProjector for FK |
| offset_distance: Distance from flange to gripper tip (default 5.8cm) |
| """ |
| |
| for i in range(min(7, projector.num_joints)): |
| p.resetJointState(projector.robot_id, i, joint_position[i]) |
|
|
| |
| flange_state = p.getLinkState(projector.robot_id, 7) |
| flange_orn = np.array(flange_state[5]) |
|
|
| |
| rot = R.from_quat(flange_orn) |
| rot_matrix = rot.as_matrix() |
|
|
| |
| local_offset = np.array([0.0, 0.0, offset_distance]) |
| world_offset = rot_matrix @ local_offset |
|
|
| gripper_tip = cartesian_position[:3] + world_offset |
| return gripper_tip |
|
|
|
|
| def main(): |
| output_dir = Path('/tmp/droid_test_gripper_tip') |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| print("Testing gripper tip with fixed 5.8cm offset") |
| 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) |
| cotracker, device = load_cotracker() |
|
|
| |
| 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): |
| uuid = find_closest_calibration(episode, uuid_list) |
| if uuid and calib_loader.has_refined_extrinsics(uuid): |
| break |
|
|
| print(f"Using episode {episode_idx}, UUID: {uuid}\n") |
|
|
| |
| calib = calib_loader.load_calibration(uuid) |
| serials = [k for k in calib.keys() if k not in ['uuid', 'scene_path', 'optimization_summary']] |
| K = np.array(calib[serials[0]]['measured_intrinsics']) |
| E = np.array(calib[serials[0]]['refined_extrinsics']) |
|
|
| |
| frames, cart_positions, joint_positions = [], [], [] |
| for step_idx, step in enumerate(episode['steps']): |
| if step_idx >= 16: |
| break |
| frames.append(step['observation']['exterior_image_1_left'].numpy()) |
| cart_positions.append(step['observation']['cartesian_position'].numpy()) |
| joint_positions.append(step['observation']['joint_position'].numpy()) |
|
|
| img_h, img_w = frames[0].shape[:2] |
|
|
| |
| all_projections = [] |
| for cart_pos, joint_pos in zip(cart_positions, joint_positions): |
| gripper_tip = compute_gripper_tip(cart_pos, joint_pos, projector, offset_distance=0.058) |
| proj_2d, proj_vis = projector._project_3d_to_2d( |
| gripper_tip.reshape(1, 3), K, E, img_h=img_h, img_w=img_w |
| ) |
| all_projections.append((proj_2d[0], proj_vis[0])) |
| if len(all_projections) == 1: |
| print(f"First frame:") |
| print(f" Flange position: {cart_pos[:3]}") |
| print(f" Gripper tip: {gripper_tip}") |
| print(f" Projected 2D: {proj_2d[0]}") |
|
|
| |
| init_2d, init_vis = all_projections[0] |
| if not init_vis: |
| print("Initial point not visible!") |
| return |
|
|
| video_np = np.array(frames).transpose(0, 3, 1, 2) |
| video_tensor = torch.from_numpy(video_np).float() / 255.0 |
| video_tensor = video_tensor.unsqueeze(0).to(device) |
|
|
| queries = np.array([[[0, init_2d[0], init_2d[1]]]], dtype=np.float32) |
| queries_tensor = torch.from_numpy(queries).to(device) |
|
|
| with torch.no_grad(): |
| pred_tracks, pred_visibility = cotracker(video_tensor, queries=queries_tensor, backward_tracking=False) |
|
|
| tracks = pred_tracks[0].cpu().numpy() |
| visibility = pred_visibility[0].cpu().numpy() |
|
|
| |
| video_frames = [] |
| for frame_idx, frame in enumerate(frames): |
| viz = frame.copy() |
|
|
| |
| gt_2d, gt_vis = all_projections[frame_idx] |
| if gt_vis: |
| cv2.circle(viz, tuple(gt_2d.astype(int)), 5, (255, 0, 0), 2) |
|
|
| |
| if visibility[frame_idx, 0]: |
| cv2.circle(viz, tuple(tracks[frame_idx, 0].astype(int)), 3, (0, 255, 0), -1) |
| if frame_idx > 0: |
| for t in range(max(0, frame_idx-10), frame_idx): |
| if visibility[t, 0] and visibility[t+1, 0]: |
| cv2.line(viz, tuple(tracks[t, 0].astype(int)), |
| tuple(tracks[t+1, 0].astype(int)), (0, 255, 0), 1) |
|
|
| cv2.putText(viz, "Gripper tip (5.8cm offset)", (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) |
| cv2.putText(viz, f"Frame {frame_idx}/{len(frames)}", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1) |
| cv2.putText(viz, "Blue=GT, Green=Tracked", (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 0), 1) |
| video_frames.append(viz) |
|
|
| video_path = output_dir / "gripper_tip_5_8cm.mp4" |
| media.write_video(str(video_path), video_frames, fps=10) |
| print(f"\nVideo saved: {video_path}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|