| """ |
| Visualize all camera parameter combinations with CoTracker. |
| |
| Tests all combinations of: |
| - param_type: refined, measured, vggt |
| - camera_view: exterior, wrist |
| |
| Generates videos showing tracked EEF for each combination. |
| """ |
|
|
| 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 tqdm import tqdm |
|
|
| 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 process_combo(episode, uuid, calib_loader, projector, cotracker, device, |
| extrinsics_type='refined', intrinsics_type='measured', |
| camera_view='exterior', max_frames=16): |
| """Process one combination and return video frames.""" |
|
|
| |
| try: |
| calib = calib_loader.load_calibration(uuid) |
| available_serials = [k for k in calib.keys() if k not in ['uuid', 'scene_path', 'optimization_summary']] |
|
|
| if camera_view == 'exterior': |
| camera_serial = available_serials[0] |
| else: |
| camera_serial = available_serials[1] if len(available_serials) > 1 else available_serials[0] |
|
|
| cam_data = calib[camera_serial] |
|
|
| |
| if f'{extrinsics_type}_extrinsics' not in cam_data: |
| return None |
| if f'{intrinsics_type}_intrinsics' not in cam_data: |
| return None |
|
|
| K = np.array(cam_data[f'{intrinsics_type}_intrinsics']) |
| E = np.array(cam_data[f'{extrinsics_type}_extrinsics']) |
|
|
| except Exception as e: |
| return None |
|
|
| |
| frames = [] |
| cart_positions = [] |
|
|
| for step_idx, step in enumerate(episode['steps']): |
| if step_idx >= max_frames: |
| break |
|
|
| cart_pos = step['observation']['cartesian_position'].numpy() |
| cart_positions.append(cart_pos) |
|
|
| if camera_view == 'exterior': |
| img = step['observation']['exterior_image_1_left'].numpy() |
| else: |
| img = step['observation']['wrist_image_left'].numpy() |
|
|
| if img is None or len(img.shape) != 3: |
| return None |
|
|
| frames.append(img) |
|
|
| if len(frames) < 10: |
| return None |
|
|
| img_h, img_w = frames[0].shape[:2] |
|
|
| |
| cart_pos_0 = cart_positions[0] |
| eef_pos_3d = cart_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 |
|
|
| print(f" E:{extrinsics_type:8s} I:{intrinsics_type:8s} | {camera_view:10s} | EEF 3D: {eef_pos_3d[0]} -> 2D: {eef_2d[0]}") |
|
|
| |
| 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] = 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() |
|
|
| |
| video_frames = [] |
| for frame_idx, frame in enumerate(frames): |
| viz = frame.copy() |
|
|
| |
| 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), 2) |
|
|
| |
| if visibility[frame_idx, 0]: |
| pt = tuple(tracks[frame_idx, 0].astype(int)) |
| cv2.circle(viz, pt, 5, (0, 255, 0), -1) |
| |
| init_pt = tuple(eef_2d[0].astype(int)) |
| cv2.circle(viz, init_pt, 3, (0, 0, 255), -1) |
|
|
| |
| title = f"E:{extrinsics_type} I:{intrinsics_type} | {camera_view} | {frame_idx}/{len(frames)}" |
| cv2.putText(viz, title, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) |
| cv2.putText(viz, f"2D: [{eef_2d[0,0]:.1f}, {eef_2d[0,1]:.1f}]", (10, 45), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 0), 1) |
|
|
| video_frames.append(viz) |
|
|
| return { |
| 'extrinsics_type': extrinsics_type, |
| 'intrinsics_type': intrinsics_type, |
| 'camera_view': camera_view, |
| 'frames': video_frames, |
| 'eef_3d': eef_pos_3d[0], |
| 'eef_2d': eef_2d[0], |
| 'img_shape': (img_h, img_w) |
| } |
|
|
|
|
| def main(): |
| output_dir = Path('/tmp/droid_all_camera_combos') |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| print("=" * 80) |
| print("Visualizing all camera parameter combinations") |
| 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] |
| print(f"Loaded {len(uuid_list)} camera calibrations") |
|
|
| |
| 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 |
|
|
| |
| print("\nChecking available parameter types...") |
| calib = calib_loader.load_calibration(uuid_found) |
| available_serials = [k for k in calib.keys() if k not in ['uuid', 'scene_path', 'optimization_summary']] |
|
|
| available_extrinsics = set() |
| available_intrinsics = set() |
| for serial in available_serials: |
| cam_data = calib[serial] |
| for param_type in ['refined', 'measured', 'vggt']: |
| if f'{param_type}_extrinsics' in cam_data: |
| available_extrinsics.add(param_type) |
| if f'{param_type}_intrinsics' in cam_data: |
| available_intrinsics.add(param_type) |
|
|
| print(f"Available extrinsics: {sorted(available_extrinsics)}") |
| print(f"Available intrinsics: {sorted(available_intrinsics)}") |
| print(f"Available camera serials: {available_serials}") |
|
|
| |
| print("\nProcessing all combinations...") |
| print("-" * 80) |
|
|
| results = [] |
| for extrinsics_type in ['refined', 'measured', 'vggt']: |
| if extrinsics_type not in available_extrinsics: |
| continue |
|
|
| for intrinsics_type in ['refined', 'measured', 'vggt']: |
| if intrinsics_type not in available_intrinsics: |
| continue |
|
|
| for camera_view in ['exterior', 'wrist']: |
| result = process_combo( |
| episode_found, uuid_found, calib_loader, projector, |
| cotracker, device, extrinsics_type, intrinsics_type, |
| camera_view, max_frames=16 |
| ) |
| if result: |
| results.append(result) |
| else: |
| print(f" Failed: E:{extrinsics_type} I:{intrinsics_type} | {camera_view}") |
|
|
| |
| print("\nSaving videos...") |
| for r in results: |
| video_name = f"E_{r['extrinsics_type']}_I_{r['intrinsics_type']}_{r['camera_view']}.mp4" |
| video_path = output_dir / video_name |
| media.write_video(str(video_path), r['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() |
|
|