| """ |
| Batch Process DROID Episodes with Mesh + CoTracker |
| |
| Processes multiple episodes and saves: |
| - NPZ files with tracks and metadata |
| - MP4 videos showing tracked trajectories (using mediapy) |
| """ |
|
|
| import os |
| import numpy as np |
| from pathlib import Path |
| import argparse |
| import cv2 |
| import sys |
|
|
| |
| import torch |
| import mediapy as media |
| from tqdm import tqdm |
| import datetime |
| import re |
|
|
| |
| import tensorflow as tf |
| |
| tf.config.set_visible_devices([], 'GPU') |
| import tensorflow_datasets as tfds |
|
|
| |
| sys.path.append(str(Path(__file__).parent.parent)) |
|
|
| 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, calib_loader): |
| """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 = match.group(1) |
| date = match.group(2) |
| hour = match.group(3) |
| minute = match.group(4) |
| second = match.group(5) |
|
|
| episode_time = datetime.datetime.strptime(f"{date} {hour}:{minute}:{second}", "%Y-%m-%d %H:%M:%S") |
|
|
| |
| matching_calibs = [] |
| for calib_uuid in uuid_list: |
| if calib_uuid.startswith(f"{lab}+") and f"+{date}-" in calib_uuid: |
| matching_calibs.append(calib_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_episode(episode, episode_idx, uuid_list, calib_loader, projector, cotracker, device, |
| camera_view='exterior', max_frames=16, num_sample_points=300, |
| num_chunks=3): |
| """ |
| Process single episode by chunking into multiple segments. |
| |
| Args: |
| num_sample_points: Total number of points to track (default 300) |
| num_chunks: Number of 16-frame chunks to process and concatenate (default 3) |
| Total frames = max_frames * num_chunks |
| |
| Returns: |
| dict with 'success', 'uuid', 'tracks', 'visibility', 'frames', 'num_points' |
| or None if failed |
| """ |
| |
| uuid = find_closest_calibration(episode, uuid_list, calib_loader) |
| if uuid is None: |
| return None |
|
|
| |
| 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 Exception as e: |
| return None |
|
|
| |
| total_frames_needed = max_frames * num_chunks |
| frames = [] |
| action_positions = [] |
|
|
| for step_idx, step in enumerate(episode['steps']): |
| if step_idx >= total_frames_needed: |
| break |
|
|
| action = step['action'].numpy() |
| action_positions.append(action) |
|
|
| 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 |
|
|
| |
| actual_chunks = min(num_chunks, len(frames) // max_frames) |
| if actual_chunks == 0: |
| actual_chunks = 1 |
|
|
| |
| img_h, img_w = frames[0].shape[:2] |
| print(f" Image resolution: {img_w}x{img_h}") |
|
|
| |
| if camera_view == 'exterior': |
| K, E = dual_params['exterior_1'] |
| else: |
| K, E = dual_params['wrist'] |
|
|
| |
| action_pos_0 = action_positions[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 |
| ) |
|
|
| |
| mesh_2d = eef_2d |
| mesh_vis = eef_vis |
|
|
| visible_mesh = np.sum(mesh_vis) |
| if visible_mesh < 1: |
| return None |
|
|
| |
| visible_mesh_2d = mesh_2d[mesh_vis] |
| num_mesh = len(visible_mesh_2d) |
|
|
| print(f" Action xyz 3D: {eef_pos_3d[0]}") |
| print(f" Action projected 2D: {visible_mesh_2d[0] if len(visible_mesh_2d) > 0 else 'NOT VISIBLE'}") |
|
|
| |
| query_points = visible_mesh_2d |
| num_points = len(query_points) |
|
|
| |
| num_random_actual = 0 |
| num_cluster = 0 |
|
|
| |
| points_per_mesh = 0 |
| mesh_radius = 0 |
| random_points = np.empty((0, 2)) |
|
|
| |
| all_tracks = [] |
| all_visibility = [] |
|
|
| print(f" Processing {actual_chunks} chunks of {max_frames} frames each...") |
|
|
| for chunk_idx in range(actual_chunks): |
| chunk_start = chunk_idx * max_frames |
| chunk_end = min(chunk_start + max_frames, len(frames)) |
| chunk_frames = frames[chunk_start:chunk_end] |
|
|
| if len(chunk_frames) < 4: |
| continue |
|
|
| |
| action_pos_chunk = action_positions[chunk_start] |
| eef_pos_3d_chunk = action_pos_chunk[:3].reshape(1, 3) |
|
|
| |
| eef_2d_chunk, eef_vis_chunk = projector._project_3d_to_2d( |
| eef_pos_3d_chunk, K, E, img_h=img_h, img_w=img_w |
| ) |
|
|
| if not eef_vis_chunk[0]: |
| print(f" Chunk {chunk_idx+1}: Action xyz not visible, skipping") |
| continue |
|
|
| print(f" Chunk {chunk_idx+1}: Action xyz 3D={eef_pos_3d_chunk[0]}, 2D={eef_2d_chunk[0]}") |
|
|
| |
| visible_mesh_2d_chunk = eef_2d_chunk[eef_vis_chunk] |
| query_points_chunk = visible_mesh_2d_chunk |
|
|
| |
| chunk_video_np = np.array(chunk_frames) |
| chunk_video_np = chunk_video_np.transpose(0, 3, 1, 2) |
| chunk_video_tensor = torch.from_numpy(chunk_video_np).float() / 255.0 |
| chunk_video_tensor = chunk_video_tensor.unsqueeze(0).to(device) |
|
|
| |
| queries = np.zeros((len(query_points_chunk), 3)) |
| queries[:, 0] = 0 |
| queries[:, 1] = query_points_chunk[:, 0] |
| queries[:, 2] = query_points_chunk[:, 1] |
| queries_tensor = torch.from_numpy(queries).float().unsqueeze(0).to(device) |
|
|
| |
| with torch.no_grad(): |
| pred_tracks, pred_visibility = cotracker( |
| chunk_video_tensor, |
| queries=queries_tensor, |
| backward_tracking=False |
| ) |
|
|
| chunk_tracks = pred_tracks[0].cpu().numpy() |
| chunk_visibility = pred_visibility[0].cpu().numpy() |
|
|
| all_tracks.append(chunk_tracks) |
| all_visibility.append(chunk_visibility) |
|
|
| print(f" Chunk {chunk_idx+1}/{actual_chunks}: {chunk_tracks.shape[0]} frames") |
|
|
| |
| tracks = np.concatenate(all_tracks, axis=0) |
| visibility = np.concatenate(all_visibility, axis=0) |
|
|
| |
| frames = frames[:tracks.shape[0]] |
|
|
| print(f" Total concatenated frames: {tracks.shape[0]}") |
|
|
| return { |
| 'success': True, |
| 'uuid': uuid, |
| 'tracks': tracks, |
| 'visibility': visibility, |
| 'frames': frames, |
| 'num_points': num_points, |
| 'visible_mesh': visible_mesh, |
| 'num_random': num_random_actual, |
| 'num_cluster': num_cluster, |
| 'num_mesh': num_mesh |
| } |
|
|
|
|
| def visualize_tracks_on_frame(frame, tracks, visibility, frame_idx, num_points, |
| num_random, num_cluster, num_mesh, title=""): |
| """ |
| Draw tracks on single frame. |
| |
| Point ordering: [random_points | cluster_points | mesh_vertices] |
| """ |
| viz = frame.copy() |
|
|
| |
| |
| |
| |
|
|
| for pt_idx in range(num_points): |
| |
| if pt_idx < num_random: |
| traj_color = (180, 180, 180) |
| point_color = (255, 100, 0) |
| point_size = 1 |
| is_mesh = False |
| elif pt_idx < num_random + num_cluster: |
| traj_color = (100, 200, 255) |
| point_color = (0, 200, 255) |
| point_size = 2 |
| is_mesh = False |
| else: |
| traj_color = (100, 255, 100) |
| point_color = (0, 255, 0) |
| point_size = 5 |
| is_mesh = True |
|
|
| |
| if frame_idx > 0: |
| for t in range(max(0, frame_idx-10), frame_idx): |
| if visibility[t, pt_idx] and visibility[t+1, pt_idx]: |
| pt1 = tuple(tracks[t, pt_idx].astype(int)) |
| pt2 = tuple(tracks[t+1, pt_idx].astype(int)) |
| cv2.line(viz, pt1, pt2, traj_color, 1) |
|
|
| |
| if visibility[frame_idx, pt_idx]: |
| pt = tuple(tracks[frame_idx, pt_idx].astype(int)) |
| cv2.circle(viz, pt, point_size, point_color, -1) |
|
|
| |
| if is_mesh: |
| mesh_idx = pt_idx - num_random - num_cluster |
| cv2.putText(viz, str(mesh_idx), (pt[0]+7, pt[1]-7), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.4, point_color, 1) |
|
|
| |
| if title: |
| cv2.putText(viz, title, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2) |
|
|
| visible_count = np.sum(visibility[frame_idx]) |
| cv2.putText(viz, f"Visible: {visible_count}/{num_points}", (10, 60), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 1) |
|
|
| return viz |
|
|
|
|
| def batch_process_episodes(droid_path: str, |
| calib_dir: str, |
| output_dir: str, |
| num_episodes: int = 10, |
| start_index: int = 0, |
| camera_view: str = 'exterior', |
| max_frames: int = 16, |
| num_sample_points: int = 300, |
| num_chunks: int = 3): |
| """Batch process multiple episodes.""" |
|
|
| print("=" * 80) |
| print("DROID Batch Processing: Mesh + CoTracker") |
| print("=" * 80) |
| print(f" Episodes: {num_episodes} (starting from {start_index})") |
| print(f" Camera: {camera_view}") |
| print(f" Frames per chunk: {max_frames}") |
| print(f" Number of chunks: {num_chunks}") |
| print(f" Total frames per episode: {max_frames * num_chunks}") |
| print(f" Output: {output_dir}") |
| print() |
|
|
| |
| output_path = Path(output_dir) |
| npz_path = output_path / "npz" |
| video_path = output_path / "videos" |
| npz_path.mkdir(parents=True, exist_ok=True) |
| video_path.mkdir(parents=True, exist_ok=True) |
|
|
| |
| 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") |
|
|
| |
| print("Loading DROID dataset...") |
| builder = tfds.builder_from_directory(droid_path) |
| dataset = builder.as_dataset(split='train') |
|
|
| |
| processed = 0 |
| skipped = 0 |
|
|
| pbar = tqdm(total=num_episodes, desc="Processing") |
|
|
| for episode_idx, episode in enumerate(dataset): |
| if episode_idx < start_index: |
| continue |
|
|
| if processed >= num_episodes: |
| break |
|
|
| try: |
| result = process_episode( |
| episode, episode_idx, uuid_list, calib_loader, projector, |
| cotracker, device, camera_view, max_frames, |
| num_sample_points=num_sample_points, num_chunks=num_chunks |
| ) |
|
|
| if result is None: |
| skipped += 1 |
| continue |
|
|
| |
| npz_file = npz_path / f"episode_{processed:04d}.npz" |
| np.savez_compressed( |
| npz_file, |
| tracks=result['tracks'], |
| visibility=result['visibility'], |
| uuid=result['uuid'], |
| num_points=result['num_points'], |
| visible_mesh=result['visible_mesh'], |
| episode_index=episode_idx |
| ) |
|
|
| |
| video_frames = [] |
| for frame_idx, frame in enumerate(result['frames']): |
| viz = visualize_tracks_on_frame( |
| frame, |
| result['tracks'], |
| result['visibility'], |
| frame_idx, |
| result['num_points'], |
| result['num_random'], |
| result['num_cluster'], |
| result['num_mesh'], |
| title=f"Episode {processed} | Frame {frame_idx}/{len(result['frames'])}" |
| ) |
| video_frames.append(viz) |
|
|
| video_file = video_path / f"episode_{processed:04d}.mp4" |
| media.write_video(str(video_file), video_frames, fps=10) |
|
|
| processed += 1 |
| pbar.update(1) |
|
|
| except Exception as e: |
| print(f"\nError processing episode {episode_idx}: {e}") |
| skipped += 1 |
| continue |
|
|
| pbar.close() |
|
|
| print("\n" + "=" * 80) |
| print("Batch Processing Complete") |
| print("=" * 80) |
| print(f" Processed: {processed} episodes") |
| print(f" Skipped: {skipped} episodes") |
| print(f" NPZ files: {npz_path}") |
| print(f" Videos: {video_path}") |
| print("=" * 80) |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Batch process DROID episodes with CoTracker") |
|
|
| parser.add_argument('--droid-path', type=str, |
| default='/mnt/kevin/data/droid/droid/1.0.0', |
| help='Path to DROID RLDS dataset') |
| parser.add_argument('--calib-dir', type=str, |
| default='/root/workspace/code/wmrl/Dual-Dynamics-Models/DROID-main/vision/u/wenlongh/datasets/droid_v4/cameras', |
| help='Path to camera calibration directory') |
| parser.add_argument('--output-dir', type=str, |
| default='/tmp/droid_batch_cotracker', |
| help='Output directory') |
| parser.add_argument('--num-episodes', type=int, default=10, |
| help='Number of episodes to process') |
| parser.add_argument('--start-index', type=int, default=0, |
| help='Starting episode index') |
| parser.add_argument('--camera', type=str, default='exterior', |
| choices=['exterior', 'wrist'], |
| help='Camera view') |
| parser.add_argument('--max-frames', type=int, default=16, |
| help='Frames per chunk (to avoid GPU OOM)') |
| parser.add_argument('--num-chunks', type=int, default=3, |
| help='Number of chunks to process and concatenate') |
| parser.add_argument('--num-points', type=int, default=300, |
| help='Total number of points to track') |
|
|
| args = parser.parse_args() |
|
|
| batch_process_episodes( |
| args.droid_path, |
| args.calib_dir, |
| args.output_dir, |
| args.num_episodes, |
| args.start_index, |
| args.camera, |
| args.max_frames, |
| args.num_points, |
| args.num_chunks |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|