| """ |
| Compare refined vs measured extrinsics with side-by-side videos. |
| |
| Shows projection and tracking quality differences between: |
| - Left: Refined extrinsics |
| - Right: Measured extrinsics |
| """ |
|
|
| 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 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: |
| return None |
|
|
|
|
| def process_with_extrinsics(episode, uuid, calib_loader, projector, cotracker, device, |
| extrinsics_type='refined', max_frames=16): |
| """Process episode with specified extrinsics type.""" |
|
|
| |
| calib = calib_loader.load_calibration(uuid) |
| serials = [k for k in calib.keys() if k not in ['uuid', 'scene_path', 'optimization_summary']] |
| cam_data = calib[serials[0]] |
|
|
| |
| if f'{extrinsics_type}_extrinsics' not in cam_data: |
| return None |
|
|
| K = np.array(cam_data['measured_intrinsics']) |
| E = np.array(cam_data[f'{extrinsics_type}_extrinsics']) |
|
|
| |
| frames = [] |
| actions = [] |
|
|
| for step_idx, step in enumerate(episode['steps']): |
| if step_idx >= max_frames: |
| break |
|
|
| img = step['observation']['exterior_image_1_left'].numpy() |
| if img is None or len(img.shape) != 3: |
| return None |
|
|
| frames.append(img) |
| actions.append(step['action'].numpy()) |
|
|
| if len(frames) < 10: |
| return None |
|
|
| img_h, img_w = frames[0].shape[:2] |
|
|
| |
| action_pos_0 = actions[0] |
| eef_pos_3d = action_pos_0[:3].reshape(1, 3) |
|
|
| eef_2d, eef_vis = projector._project_3d_to_2d( |
| eef_pos_3d, K, E, img_h=img_h, img_w=img_w |
| ) |
|
|
| if not eef_vis[0]: |
| return None |
|
|
| |
| 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.zeros((1, 3)) |
| queries[0, 0] = 0 |
| queries[0, 1] = eef_2d[0, 0] |
| queries[0, 2] = eef_2d[0, 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() |
|
|
| return { |
| 'frames': frames, |
| 'eef_2d_init': eef_2d[0], |
| 'tracks': tracks, |
| 'visibility': visibility, |
| 'extrinsics_type': extrinsics_type |
| } |
|
|
|
|
| def create_comparison_video(result_refined, result_measured, output_path): |
| """Create side-by-side comparison video.""" |
|
|
| frames_refined = result_refined['frames'] |
| frames_measured = result_measured['frames'] |
|
|
| tracks_refined = result_refined['tracks'] |
| visibility_refined = result_refined['visibility'] |
|
|
| tracks_measured = result_measured['tracks'] |
| visibility_measured = result_measured['visibility'] |
|
|
| eef_refined = result_refined['eef_2d_init'] |
| eef_measured = result_measured['eef_2d_init'] |
|
|
| video_frames = [] |
|
|
| for frame_idx in range(len(frames_refined)): |
| |
| viz_refined = frames_refined[frame_idx].copy() |
|
|
| |
| cv2.circle(viz_refined, tuple(eef_refined.astype(int)), 5, (0, 0, 255), 2) |
|
|
| |
| if visibility_refined[frame_idx, 0]: |
| pt = tuple(tracks_refined[frame_idx, 0].astype(int)) |
| cv2.circle(viz_refined, pt, 3, (0, 255, 0), -1) |
|
|
| |
| if frame_idx > 0: |
| for t in range(max(0, frame_idx-10), frame_idx): |
| if visibility_refined[t, 0] and visibility_refined[t+1, 0]: |
| pt1 = tuple(tracks_refined[t, 0].astype(int)) |
| pt2 = tuple(tracks_refined[t+1, 0].astype(int)) |
| cv2.line(viz_refined, pt1, pt2, (0, 255, 0), 1) |
|
|
| |
| cv2.putText(viz_refined, "REFINED Extrinsics", (10, 25), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) |
| cv2.putText(viz_refined, f"Init: [{eef_refined[0]:.1f}, {eef_refined[1]:.1f}]", |
| (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1) |
|
|
| |
| viz_measured = frames_measured[frame_idx].copy() |
|
|
| |
| cv2.circle(viz_measured, tuple(eef_measured.astype(int)), 5, (0, 0, 255), 2) |
|
|
| |
| if visibility_measured[frame_idx, 0]: |
| pt = tuple(tracks_measured[frame_idx, 0].astype(int)) |
| cv2.circle(viz_measured, pt, 3, (0, 255, 0), -1) |
|
|
| |
| if frame_idx > 0: |
| for t in range(max(0, frame_idx-10), frame_idx): |
| if visibility_measured[t, 0] and visibility_measured[t+1, 0]: |
| pt1 = tuple(tracks_measured[t, 0].astype(int)) |
| pt2 = tuple(tracks_measured[t+1, 0].astype(int)) |
| cv2.line(viz_measured, pt1, pt2, (0, 255, 0), 1) |
|
|
| |
| cv2.putText(viz_measured, "MEASURED Extrinsics", (10, 25), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) |
| cv2.putText(viz_measured, f"Init: [{eef_measured[0]:.1f}, {eef_measured[1]:.1f}]", |
| (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1) |
|
|
| |
| combined = np.concatenate([viz_refined, viz_measured], axis=1) |
|
|
| |
| cv2.putText(combined, f"Frame {frame_idx}/{len(frames_refined)}", |
| (combined.shape[1]//2 - 50, 25), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2) |
| cv2.putText(combined, "Red=Initial Projection, Green=CoTracker", |
| (10, combined.shape[0] - 10), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1) |
|
|
| video_frames.append(combined) |
|
|
| |
| media.write_video(str(output_path), video_frames, fps=10) |
|
|
|
|
| def main(): |
| output_dir = Path('/tmp/droid_extrinsics_comparison') |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| print("=" * 80) |
| print("Comparing Refined vs Measured Extrinsics") |
| 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' |
| 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 |
|
|
| |
| calib = calib_loader.load_calibration(uuid) |
| serials = [k for k in calib.keys() if k not in ['uuid', 'scene_path', 'optimization_summary']] |
| cam_data = calib[serials[0]] |
|
|
| if 'refined_extrinsics' not in cam_data or 'measured_extrinsics' not in cam_data: |
| continue |
|
|
| print(f"\nProcessing episode {episode_idx}...") |
|
|
| |
| result_refined = process_with_extrinsics( |
| episode, uuid, calib_loader, projector, cotracker, device, |
| extrinsics_type='refined', max_frames=16 |
| ) |
|
|
| result_measured = process_with_extrinsics( |
| episode, uuid, calib_loader, projector, cotracker, device, |
| extrinsics_type='measured', max_frames=16 |
| ) |
|
|
| if result_refined is None or result_measured is None: |
| print(f" Skipped - processing failed") |
| continue |
|
|
| |
| output_path = output_dir / f"comparison_episode_{episode_idx:04d}.mp4" |
| create_comparison_video(result_refined, result_measured, output_path) |
|
|
| print(f" Refined projection: {result_refined['eef_2d_init']}") |
| print(f" Measured projection: {result_measured['eef_2d_init']}") |
| print(f" Difference: {result_refined['eef_2d_init'] - result_measured['eef_2d_init']}") |
| print(f" ✓ Saved: {output_path}") |
|
|
| created_count += 1 |
|
|
| print("\n" + "=" * 80) |
| print(f"Created {created_count} comparison videos") |
| print(f"Output directory: {output_dir}") |
| print("=" * 80) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|