| """ |
| Debug what cartesian_position represents in DROID data. |
| |
| Compare: |
| 1. cartesian_position from observation |
| 2. FK from joint_position using different links (wrist, flange, gripper) |
| """ |
|
|
| 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 utils.load_camera_calibration import CameraCalibrationLoader |
| from utils.franka_mesh_projection import FrankaMeshProjector |
|
|
|
|
| def load_cotracker(): |
| """Load CoTracker v3 model.""" |
| 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): |
| """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 Exception as e: |
| return None |
|
|
|
|
| def get_link_position_from_fk(projector, joint_positions, link_idx): |
| """Get 3D position of a specific link using FK.""" |
| |
| for i in range(min(7, projector.num_joints)): |
| p.resetJointState(projector.robot_id, i, joint_positions[i]) |
|
|
| |
| link_state = p.getLinkState(projector.robot_id, link_idx) |
| link_pos = np.array(link_state[4]) |
| return link_pos |
|
|
|
|
| def main(): |
| output_dir = Path('/tmp/droid_debug_cartesian') |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| print("=" * 80) |
| print("Debugging cartesian_position vs FK") |
| 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) |
| calib_files = sorted(calib_path.glob("*_cameras.json")) |
| uuid_list = [f.stem.replace('_cameras', '') for f in calib_files] |
|
|
| |
| 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') |
|
|
| |
| episode_found = None |
| uuid_found = None |
|
|
| for episode_idx, episode in enumerate(dataset): |
| uuid = find_closest_calibration(episode, uuid_list) |
| if uuid is None: |
| continue |
| if not calib_loader.has_refined_extrinsics(uuid): |
| continue |
|
|
| episode_found = episode |
| uuid_found = uuid |
| print(f"\nUsing episode {episode_idx}, UUID: {uuid}") |
| break |
|
|
| if episode_found is None: |
| print("No valid episode found!") |
| return |
|
|
| |
| calib = calib_loader.load_calibration(uuid_found) |
| available_serials = [k for k in calib.keys() if k not in ['uuid', 'scene_path', 'optimization_summary']] |
| camera_serial = available_serials[0] |
| cam_data = calib[camera_serial] |
|
|
| K = np.array(cam_data['measured_intrinsics']) |
| E = np.array(cam_data['refined_extrinsics']) |
|
|
| |
| frames = [] |
| cart_positions = [] |
| joint_positions_list = [] |
| max_frames = 16 |
|
|
| for step_idx, step in enumerate(episode_found['steps']): |
| if step_idx >= max_frames: |
| break |
|
|
| cart_pos = step['observation']['cartesian_position'].numpy() |
| joint_pos = step['observation']['joint_position'].numpy() |
| img = step['observation']['exterior_image_1_left'].numpy() |
|
|
| cart_positions.append(cart_pos) |
| joint_positions_list.append(joint_pos) |
| frames.append(img) |
|
|
| img_h, img_w = frames[0].shape[:2] |
|
|
| |
| print("\n" + "=" * 80) |
| print("Comparing cartesian_position vs FK positions") |
| print("=" * 80) |
|
|
| cart_pos_0 = cart_positions[0] |
| joint_pos_0 = joint_positions_list[0] |
|
|
| print(f"\ncartesian_position: {cart_pos_0[:3]}") |
| print(f"joint_position: {joint_pos_0}") |
|
|
| |
| link_names = { |
| 5: "Link 5 (wrist)", |
| 7: "Link 7 (flange)", |
| 8: "Link 8 (panda_hand)", |
| 9: "Link 9 (panda_leftfinger)", |
| 10: "Link 10 (panda_rightfinger)", |
| } |
|
|
| fk_positions = {} |
| for link_idx, link_name in link_names.items(): |
| fk_pos = get_link_position_from_fk(projector, joint_pos_0, link_idx) |
| fk_positions[link_idx] = fk_pos |
| diff = np.linalg.norm(fk_pos - cart_pos_0[:3]) |
| print(f"\n{link_name:25s}: {fk_pos}") |
| print(f" Distance from cartesian_position: {diff:.4f}") |
|
|
| |
| closest_link = min(fk_positions.items(), key=lambda x: np.linalg.norm(x[1] - cart_pos_0[:3])) |
| print(f"\nClosest match: {link_names[closest_link[0]]}") |
|
|
| |
| print("\n" + "=" * 80) |
| print("Generating visualization videos") |
| print("=" * 80) |
|
|
| for link_idx, link_name in link_names.items(): |
| print(f"\nProcessing {link_name}...") |
|
|
| |
| all_projections = [] |
| for frame_idx, joint_pos in enumerate(joint_positions_list): |
| link_pos = get_link_position_from_fk(projector, joint_pos, link_idx) |
| link_pos_reshaped = link_pos.reshape(1, 3) |
| proj_2d, proj_vis = projector._project_3d_to_2d(link_pos_reshaped, K, E, img_h=img_h, img_w=img_w) |
| all_projections.append((proj_2d[0], proj_vis[0])) |
|
|
| |
| init_2d, init_vis = all_projections[0] |
| if not init_vis: |
| print(f" Skipping {link_name} - not visible") |
| continue |
|
|
| |
| video_np = np.array(frames) |
| video_np = video_np.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.zeros((1, 3)) |
| queries[0, 0] = 0 |
| queries[0, 1] = init_2d[0] |
| queries[0, 2] = init_2d[1] |
| queries_tensor = torch.from_numpy(queries).float().unsqueeze(0).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: |
| gt_pt = tuple(gt_2d.astype(int)) |
| cv2.circle(viz, gt_pt, 5, (255, 0, 0), 2) |
|
|
| |
| if visibility[frame_idx, 0]: |
| track_pt = tuple(tracks[frame_idx, 0].astype(int)) |
| cv2.circle(viz, track_pt, 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]: |
| pt1 = tuple(tracks[t, 0].astype(int)) |
| pt2 = tuple(tracks[t+1, 0].astype(int)) |
| cv2.line(viz, pt1, pt2, (0, 255, 0), 1) |
|
|
| |
| cv2.putText(viz, link_name, (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, f"Blue=GT, Green=Tracked", (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 0), 1) |
|
|
| video_frames.append(viz) |
|
|
| |
| video_name = f"{link_name.replace(' ', '_').replace('(', '').replace(')', '')}.mp4" |
| video_path = output_dir / video_name |
| media.write_video(str(video_path), video_frames, fps=10) |
| print(f" Saved: {video_path}") |
|
|
| print("\n" + "=" * 80) |
| print(f"Complete! Videos saved to: {output_dir}") |
| print("=" * 80) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|