""" Final DROID Preprocessing Script Preprocesses DROID episodes for ControlNet+UNet training with: 1. 7 mesh vertices (computed per frame as ground truth) 2. CoTracker on 1000 points including the 7 mesh vertices (similar to LIBERO's 1098) 3. No manual chunking - uses CoTracker's automatic handling 4. Saves in This&That RLDS-compatible format with visibility masks For each episode: - Exterior view: 1000 tracked points (first 7 are mesh vertices, remaining 993 are arm-shaped) - Wrist view: 1000 tracked points (300 sparse + 700 dense bottom 60%-100%) - Ground truth mesh vertices saved separately for comparison - Original 180×320 resolution - Visibility masks saved for occlusion handling """ 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 json from tqdm import tqdm from scipy.spatial.transform import Rotation as R from utils.load_camera_calibration import CameraCalibrationLoader from utils.franka_mesh_projection import FrankaMeshProjector # 7 gripper offsets in gripper frame (before rotation) GRIPPER_OFFSETS = np.array([ [0.0, 0.0, 0.0], # 0: gripper base [0.0, 0.045, 0.161], # 1: finger 1 tip [0.0, -0.045, 0.161], # 2: finger 2 tip [0.0, 0.045, 0.13], # 3: finger 1 end [0.0, -0.045, 0.13], # 4: finger 2 end [0.0, 0.0, 0.13], # 5: gripper center front [0.0, 0.0, 0.065], # 6: gripper center middle ]) def euler_xyz_to_rotation_matrix(euler_xyz): """Convert Euler XYZ angles to rotation matrix.""" return R.from_euler('xyz', euler_xyz).as_matrix() def transform_gripper_offsets(action): """ Transform gripper offsets using action position and rotation. Args: action: [x, y, z, rx, ry, rz, gripper] - Euler XYZ rotation Returns: gripper_points_3d: [7, 3] array of 3D points in world frame """ pos = action[:3] rot_euler = action[3:6] rot_matrix = euler_xyz_to_rotation_matrix(rot_euler) gripper_points_3d = (rot_matrix @ GRIPPER_OFFSETS.T).T + pos return gripper_points_3d def sample_arm_shaped_points(mesh_2d_visible, img_h, img_w, num_points=993, seed=None): """ Sample points in arm shape around visible mesh vertices. Strategy: - Many points per visible mesh vertex (Gaussian, σ=15 pixels) - Points along lines connecting mesh vertices - Remaining points uniform random Args: mesh_2d_visible: [N_visible, 2] visible mesh vertex projections img_h, img_w: Image dimensions num_points: Total points to sample (default 993 for 1000 total with 7 mesh) seed: Random seed for reproducibility Returns: points: [num_points, 2] sampled points in pixel coordinates """ if seed is not None: np.random.seed(seed) points = [] num_visible = len(mesh_2d_visible) if num_visible == 0: # No mesh visible, return uniform random return np.random.rand(num_points, 2) * [img_w, img_h] # 1. Gaussian around each visible mesh vertex (15 per mesh) points_per_mesh = min(15, num_points // num_visible) gaussian_sigma = 15.0 # pixels for mesh_pt in mesh_2d_visible: gaussian_pts = np.random.randn(points_per_mesh, 2) * gaussian_sigma + mesh_pt # Clip to image bounds gaussian_pts[:, 0] = np.clip(gaussian_pts[:, 0], 0, img_w - 1) gaussian_pts[:, 1] = np.clip(gaussian_pts[:, 1], 0, img_h - 1) points.append(gaussian_pts) # 2. Lines between visible meshes (if multiple visible) if num_visible >= 2: # Sample along lines connecting consecutive visible points points_per_line = 6 for i in range(num_visible - 1): line_pts = np.linspace(mesh_2d_visible[i], mesh_2d_visible[i+1], points_per_line + 2) points.append(line_pts[1:-1]) # Exclude endpoints (already in Gaussian) # 3. Fill remaining with uniform random current_count = sum(len(p) for p in points) remaining = num_points - current_count if remaining > 0: uniform_pts = np.random.rand(remaining, 2) * [img_w, img_h] points.append(uniform_pts) # Concatenate and ensure exact count all_points = np.vstack(points) if points else np.empty((0, 2)) if len(all_points) < num_points: # Pad with uniform random extra = np.random.rand(num_points - len(all_points), 2) * [img_w, img_h] all_points = np.vstack([all_points, extra]) elif len(all_points) > num_points: # Truncate all_points = all_points[:num_points] return all_points def get_wrist_gripper_mesh_2d(gripper_state, img_h=180, img_w=320): """ Generate 7-point 2D gripper mesh for wrist camera (INITIAL TRACKING QUERIES). Similar to exterior camera's 3D projected mesh, these are the initial query points for CoTracker to track. The gripper is at ~70% from left (not centered). Args: gripper_state: float in [-1, 1] from action[6] -1 = fully closed, +1 = fully open img_h, img_w: Image dimensions (default DROID native 180x320) Returns: mesh_2d: [7, 2] array with (x, y) pixel coordinates for initial tracking 0: gripper base 1: right finger tip 2: left finger tip 3: right finger joint 4: left finger joint 5: center front 6: center back """ # Manually annotated keypoints (same as fixed mesh) # OPEN state (gripper_state = 0.0) mesh_open = np.array([ [141, 108], # 0: palm base [253, 106], # 1: RIGHT finger tip [129, 131], # 2: LEFT finger tip [290, 130], # 3: RIGHT finger joint [168, 156], # 4: LEFT finger joint [284, 156], # 5: right palm interior [95, 138], # 6: left palm interior ], dtype=np.float32) # CLOSED state (gripper_state = 1.0) mesh_closed = np.array([ [190, 102], # 0: palm base [198, 102], # 1: RIGHT finger tip [195, 120], # 2: LEFT finger tip [216, 119], # 3: RIGHT finger joint [200, 152], # 4: LEFT finger joint [245, 150], # 5: right palm interior [168, 126], # 6: left palm interior ], dtype=np.float32) # Interpolate between OPEN (gs=0) and CLOSED (gs=1) alpha = gripper_state # 0 = use mesh_open, 1 = use mesh_closed mesh_2d = (1 - alpha) * mesh_open + alpha * mesh_closed return mesh_2d def get_wrist_fixed_mesh_2d(gripper_state, img_h=180, img_w=320): """ Generate 7-point FIXED 2D mesh that moves with gripper state (NOT TRACKED). Uses manually annotated keypoints and interpolates between them based on gripper state. IMPORTANT: Gripper state convention is INVERTED in DROID dataset: gripper_state = 0.0 → OPEN (wide finger spacing) gripper_state = 1.0 → CLOSED (narrow finger spacing) Args: gripper_state: float in [0, 1] from action[6] 0.0 = fully OPEN, 1.0 = fully CLOSED img_h, img_w: Image dimensions (default DROID native 180x320) Returns: mesh_2d: [7, 2] array with (x, y) pixel coordinates 0: palm base 1: RIGHT finger tip 2: LEFT finger tip 3: RIGHT finger joint 4: LEFT finger joint 5: right palm interior 6: left palm interior """ # Manually annotated keypoints from web annotation tool # Convention: gripper_state 0.0=OPEN, 1.0=CLOSED # OPEN state (gripper_state = 0.0) - wide finger spacing mesh_open = np.array([ [141, 108], # 0: palm base [253, 106], # 1: RIGHT finger tip [129, 131], # 2: LEFT finger tip [290, 130], # 3: RIGHT finger joint [168, 156], # 4: LEFT finger joint [284, 156], # 5: right palm interior [95, 138], # 6: left palm interior ], dtype=np.float32) # CLOSED state (gripper_state = 1.0) - narrow finger spacing mesh_closed = np.array([ [190, 102], # 0: palm base [198, 102], # 1: RIGHT finger tip (only 8px from left!) [195, 120], # 2: LEFT finger tip [216, 119], # 3: RIGHT finger joint [200, 152], # 4: LEFT finger joint [245, 150], # 5: right palm interior [168, 126], # 6: left palm interior ], dtype=np.float32) # Interpolate between OPEN (gs=0) and CLOSED (gs=1) # gripper_state goes from 0 (open) to 1 (closed) alpha = gripper_state # 0 = use mesh_open, 1 = use mesh_closed mesh_2d = (1 - alpha) * mesh_open + alpha * mesh_closed return mesh_2d def sample_double_grid(n, img_h, img_w): """ Sample two offset grids for background coverage (matches LIBERO preprocessing). Creates 2×(n×n) grid points across the image for stable background tracking. Args: n: Grid size (e.g., n=7 gives 7×7×2=98 points) img_h, img_w: Image dimensions Returns: points: [2*n*n, 2] array of (x, y) coordinates """ # Grid 1: from 5% to 85% u1 = np.linspace(0.05 * img_w, 0.85 * img_w, n) v1 = np.linspace(0.05 * img_h, 0.85 * img_h, n) u1, v1 = np.meshgrid(u1, v1) grid1 = np.stack([u1.flatten(), v1.flatten()], axis=-1) # Grid 2: from 15% to 95% (offset from grid1) u2 = np.linspace(0.15 * img_w, 0.95 * img_w, n) v2 = np.linspace(0.15 * img_h, 0.95 * img_h, n) u2, v2 = np.meshgrid(u2, v2) grid2 = np.stack([u2.flatten(), v2.flatten()], axis=-1) # Combine both grids points = np.vstack([grid1, grid2]).astype(np.float32) return points def sample_uniform_grid( n, img_h, img_w, pad_ratio=0.05, crop_left=None, crop_right=None, crop_top=0.0, crop_bottom=None, out_w=None, out_h=None, ): """Sample an n×n grid; optionally uniform after crop+resize transform.""" if crop_left is None or crop_right is None: u = np.linspace(pad_ratio * img_w, (1.0 - pad_ratio) * img_w, n) v = np.linspace(pad_ratio * img_h, (1.0 - pad_ratio) * img_h, n) else: if crop_bottom is None: crop_bottom = float(img_h) crop_w = float(crop_right - crop_left) crop_h = float(crop_bottom - crop_top) if out_w is None: out_w = crop_w if out_h is None: out_h = crop_h u_out = np.linspace(pad_ratio * out_w, (1.0 - pad_ratio) * (out_w - 1.0), n) v_out = np.linspace(pad_ratio * out_h, (1.0 - pad_ratio) * (out_h - 1.0), n) u = u_out * (crop_w / float(out_w)) + float(crop_left) v = v_out * (crop_h / float(out_h)) + float(crop_top) uu, vv = np.meshgrid(u, v) return np.stack([uu.flatten(), vv.flatten()], axis=-1).astype(np.float32) def sample_wrist_points(img_h, img_w, num_sparse=300, num_dense=700, seed=None): """ Sample points for wrist view: sparse uniform + dense in bottom region. Bottom region: Y-coords from 60% to 100% of image height (bottom 40%) This is where the gripper typically appears in wrist camera view. Args: img_h, img_w: Image dimensions num_sparse: Number of sparse uniform points (default 300) num_dense: Number of dense points in bottom region (default 700) seed: Random seed Returns: points: [num_sparse + num_dense, 2] sampled points (1000 total by default) """ if seed is not None: np.random.seed(seed) # Sparse uniform across full image sparse = np.random.rand(num_sparse, 2) * [img_w, img_h] # Dense in bottom 60%-100% region # For 180 height: 60% = 108, 100% = 180 y_min = int(img_h * 0.60) y_max = img_h y_range = y_max - y_min dense_x = np.random.rand(num_dense) * img_w dense_y = np.random.rand(num_dense) * y_range + y_min dense = np.column_stack([dense_x, dense_y]) return np.vstack([sparse, dense]) def create_temporal_queries(points_2d, T, num_mesh=7): """ Create CoTracker queries with temporal sampling. Mesh vertices (first 7 points) always start at frame 0 (ground truth). Remaining points are sampled from random frames across the video. Args: points_2d: [N, 2] array of (x, y) spatial coordinates T: Number of frames in video num_mesh: Number of mesh points that start at t=0 (default 7) Returns: queries: [N, 3] array with (t, x, y) for CoTracker """ N = len(points_2d) queries = np.zeros((N, 3), dtype=np.float32) # Mesh vertices always start at frame 0 (ground truth from projection) queries[:num_mesh, 0] = 0 queries[:num_mesh, 1:] = points_2d[:num_mesh] # Remaining points: sample from random frames if T > 1: random_frames = np.random.randint(0, T, size=N - num_mesh) else: random_frames = np.zeros(N - num_mesh, dtype=np.int32) queries[num_mesh:, 0] = random_frames queries[num_mesh:, 1:] = points_2d[num_mesh:] return queries def track_with_variance_filter(cotracker, video_tensor, queries_tensor, device, var_threshold=10.0, preserve_indices=None): """ Track points with variance filtering and forward/backward tracking. Performs both forward and backward tracking passes, averages results, then filters out low-variance (static/noisy) points. Mesh points are always preserved. If too many points are filtered, resamples with jitter. Args: cotracker: CoTracker model video_tensor: [1, T, 3, H, W] video tensor queries_tensor: [1, N, 3] query tensor (t, x, y) device: torch device var_threshold: Minimum variance to keep point (default 10.0, matches LIBERO preprocessing) preserve_indices: List/array of point indices to always preserve (mesh + grid points) Returns: tracks: [T, N, 2] numpy array vis: [T, N] numpy array """ B, T, C, H, W = video_tensor.shape N = queries_tensor.shape[1] # Forward tracking with torch.no_grad(): tracks_fwd, vis_fwd = cotracker( video_tensor, queries=queries_tensor, backward_tracking=False ) # Backward tracking with torch.no_grad(): tracks_bwd, vis_bwd = cotracker( video_tensor, queries=queries_tensor, backward_tracking=True ) # Average forward and backward for robustness tracks = (tracks_fwd + tracks_bwd) / 2.0 vis = (vis_fwd + vis_bwd) / 2.0 # Compute variance per point (measure of motion/dynamics) # High variance = dynamic point, Low variance = static/noisy variance = torch.var(tracks[0], dim=0).sum(dim=-1) # [N] # Preserve specified indices (mesh + grid points, always keep them) if preserve_indices is not None: variance[preserve_indices] = float('inf') # Ensures they're never filtered # Filter: keep points with variance above threshold valid_idx = torch.where(variance > var_threshold)[0] # If we filtered too many points, resample from valid ones with jitter if len(valid_idx) < N: n_needed = N - len(valid_idx) # Resample from valid points resample_idx = valid_idx[torch.randint(len(valid_idx), (n_needed,), device=device)] new_queries = queries_tensor[:, resample_idx].clone() # Add spatial jitter to resampled queries (5% of image height) noise = torch.randn_like(new_queries[:, :, 1:]) * 0.05 * H new_queries[:, :, 1:] = torch.clamp(new_queries[:, :, 1:] + noise, 0, None) # Re-track resampled points (backward only for efficiency) with torch.no_grad(): new_tracks, new_vis = cotracker( video_tensor, queries=new_queries, backward_tracking=True ) # Concatenate valid + resampled tracks tracks = torch.cat([tracks[:, :, valid_idx], new_tracks], dim=2) vis = torch.cat([vis[:, :, valid_idx], new_vis], dim=2) else: # Keep only valid points tracks = tracks[:, :, valid_idx] vis = vis[:, :, valid_idx] return tracks[0].cpu().numpy(), vis[0].cpu().numpy() def track_with_variance_filter_batched(cotracker, video_tensor, queries_tensor, device, var_threshold=10.0, preserve_indices=None, batch_size=600): """ Batched version of track_with_variance_filter for OOM handling. Splits queries into batches to reduce memory usage. Uses same logic as track_with_variance_filter but processes points in smaller chunks. Args: cotracker: CoTracker model video_tensor: [1, T, 3, H, W] video tensor queries_tensor: [1, N, 3] query tensor (t, x, y) device: torch device var_threshold: Minimum variance to keep point (default 10.0) preserve_indices: List/array of point indices to always preserve batch_size: Number of points per batch (default 500) Returns: tracks: [T, N, 2] numpy array vis: [T, N] numpy array """ B, T, C, H, W = video_tensor.shape N = queries_tensor.shape[1] # Calculate number of batches num_batches = (N + batch_size - 1) // batch_size print(f" [BATCHED] Tracking {N} points in {num_batches} batches of {batch_size}") # Forward tracking in batches tracks_fwd_list = [] vis_fwd_list = [] for batch_idx in range(num_batches): start_idx = batch_idx * batch_size end_idx = min(start_idx + batch_size, N) batch_queries = queries_tensor[:, start_idx:end_idx, :] with torch.no_grad(): batch_tracks_fwd, batch_vis_fwd = cotracker( video_tensor, queries=batch_queries, backward_tracking=False ) tracks_fwd_list.append(batch_tracks_fwd) vis_fwd_list.append(batch_vis_fwd) # Free GPU memory after each batch torch.cuda.empty_cache() # Concatenate forward tracking results tracks_fwd = torch.cat(tracks_fwd_list, dim=2) # [1, T, N, 2] vis_fwd = torch.cat(vis_fwd_list, dim=2) # [1, T, N] # Backward tracking in batches tracks_bwd_list = [] vis_bwd_list = [] for batch_idx in range(num_batches): start_idx = batch_idx * batch_size end_idx = min(start_idx + batch_size, N) batch_queries = queries_tensor[:, start_idx:end_idx, :] with torch.no_grad(): batch_tracks_bwd, batch_vis_bwd = cotracker( video_tensor, queries=batch_queries, backward_tracking=True ) tracks_bwd_list.append(batch_tracks_bwd) vis_bwd_list.append(batch_vis_bwd) # Free GPU memory after each batch torch.cuda.empty_cache() # Concatenate backward tracking results tracks_bwd = torch.cat(tracks_bwd_list, dim=2) # [1, T, N, 2] vis_bwd = torch.cat(vis_bwd_list, dim=2) # [1, T, N] # Average forward and backward for robustness tracks = (tracks_fwd + tracks_bwd) / 2.0 vis = (vis_fwd + vis_bwd) / 2.0 # Compute variance per point (measure of motion/dynamics) variance = torch.var(tracks[0], dim=0).sum(dim=-1) # [N] # Preserve specified indices (mesh + grid points, always keep them) if preserve_indices is not None: variance[preserve_indices] = float('inf') # Filter: keep points with variance above threshold valid_idx = torch.where(variance > var_threshold)[0] # If we filtered too many points, resample from valid ones with jitter if len(valid_idx) < N: n_needed = N - len(valid_idx) # Resample from valid points resample_idx = valid_idx[torch.randint(len(valid_idx), (n_needed,), device=device)] new_queries = queries_tensor[:, resample_idx].clone() # Add spatial jitter to resampled queries (5% of image height) noise = torch.randn_like(new_queries[:, :, 1:]) * 0.05 * H new_queries[:, :, 1:] = torch.clamp(new_queries[:, :, 1:] + noise, 0, None) # Re-track resampled points (backward only for efficiency) # Also batch this if needed if n_needed > batch_size: new_tracks_list = [] new_vis_list = [] num_resample_batches = (n_needed + batch_size - 1) // batch_size for batch_idx in range(num_resample_batches): start_idx = batch_idx * batch_size end_idx = min(start_idx + batch_size, n_needed) batch_new_queries = new_queries[:, start_idx:end_idx, :] with torch.no_grad(): batch_new_tracks, batch_new_vis = cotracker( video_tensor, queries=batch_new_queries, backward_tracking=True ) new_tracks_list.append(batch_new_tracks) new_vis_list.append(batch_new_vis) torch.cuda.empty_cache() new_tracks = torch.cat(new_tracks_list, dim=2) new_vis = torch.cat(new_vis_list, dim=2) else: with torch.no_grad(): new_tracks, new_vis = cotracker( video_tensor, queries=new_queries, backward_tracking=True ) # Concatenate valid + resampled tracks tracks = torch.cat([tracks[:, :, valid_idx], new_tracks], dim=2) vis = torch.cat([vis[:, :, valid_idx], new_vis], dim=2) else: # Keep only valid points tracks = tracks[:, :, valid_idx] vis = vis[:, :, valid_idx] return tracks[0].cpu().numpy(), vis[0].cpu().numpy() def load_cotracker(device=None): """ Load CoTracker v3 offline model. Args: device: torch device to load model on. If None, uses cuda if available. Returns: model: CoTracker model device: Device model is loaded on """ from cotracker.predictor import CoTrackerPredictor if device is None: device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Try multiple checkpoint locations cotracker_paths = [ '/mnt/kevin/vlm_models/cotracker/scaled_offline.pth', '/mnt/kevin/vlm_models/hub/checkpoints/scaled_offline.pth', '/root/workspace/code/wmrl/Dual-Dynamics-Models/DROID-main/co-tracker/checkpoints/scaled_offline.pth', ] cotracker_checkpoint = None for path in cotracker_paths: if Path(path).exists(): cotracker_checkpoint = path print(f"Found CoTracker checkpoint: {cotracker_checkpoint}") break if cotracker_checkpoint is None: raise FileNotFoundError(f"CoTracker checkpoint not found. Tried:\n" + "\n".join(cotracker_paths)) model = CoTrackerPredictor(checkpoint=cotracker_checkpoint) model = model.to(device) model.eval() return model, device def find_closest_calibration(episode, uuid_list): """Find closest calibration by timestamp (FIXED UUID MATCHING).""" try: # Extract timestamp from file_path file_path = episode['episode_metadata']['file_path'].numpy().decode('utf-8') # Path format: .../YYYY-MM-DD/Day_Month_DD_HH:MM:SS_YYYY/... date_match = re.search(r'/(\d{4})-(\d{2})-(\d{2})/[^/]+_(\d{1,2}):(\d{2}):(\d{2})_\d{4}/', file_path) if not date_match: return None year, month, day, hour, minute, second = date_match.groups() episode_ts = datetime.datetime(int(year), int(month), int(day), int(hour), int(minute), int(second)) # Find closest UUID by timestamp closest_uuid = None min_diff = None for uuid in uuid_list: try: # UUID format: TRI+52ca9b6a+2023-11-06-11h-33m-00s ts_part = uuid.split('+')[-1] uuid_ts = datetime.datetime.strptime(ts_part, '%Y-%m-%d-%Hh-%Mm-%Ss') time_diff = abs((episode_ts - uuid_ts).total_seconds()) if min_diff is None or time_diff < min_diff: min_diff = time_diff closest_uuid = uuid except: continue return closest_uuid except: return None def process_episode(episode, episode_idx, uuid, calib_loader, projector, cotracker, device, max_frames=400, save_video=False, output_dir=None, use_batching=False, batch_size=300): """ Process single DROID episode. Args: use_batching: If True, use batched tracking to reduce memory usage batch_size: Number of points per batch when use_batching=True (default 500) Returns: dict with processed data, or None if failed """ # Get calibration (refined extrinsics + measured intrinsics) try: dual_params = calib_loader.get_dual_view_params(uuid, param_type='refined', require_refined=True) if dual_params is None: return None except: return None K_ext, E_ext = dual_params['exterior_1'] K_wrist, E_wrist = dual_params['wrist'] # First pass: count valid frames to check if episode is too long valid_frame_count = 0 for step in episode['steps']: img_ext = step['observation']['exterior_image_1_left'].numpy() img_wrist = step['observation']['wrist_image_left'].numpy() if img_ext is not None and img_wrist is not None: if len(img_ext.shape) == 3 and len(img_wrist.shape) == 3: valid_frame_count += 1 if valid_frame_count > max_frames: # Episode is too long, skip it return None # Check minimum length if valid_frame_count < 10: return None # Collect frames and observations frames_ext = [] frames_wrist = [] actions = [] for step_idx, step in enumerate(episode['steps']): img_ext = step['observation']['exterior_image_1_left'].numpy() img_wrist = step['observation']['wrist_image_left'].numpy() if img_ext is None or img_wrist is None: continue if len(img_ext.shape) != 3 or len(img_wrist.shape) != 3: continue frames_ext.append(img_ext) frames_wrist.append(img_wrist) actions.append(step['action'].numpy()) T = len(frames_ext) img_h, img_w = frames_ext[0].shape[:2] # Step 1: Compute mesh vertices for ALL frames (ground truth, not tracked) all_mesh_3d = [] all_mesh_2d_ext = [] all_mesh_vis_ext = [] for action in actions: # Transform gripper offsets gripper_3d = transform_gripper_offsets(action) # Project to exterior camera mesh_2d, mesh_vis = projector._project_3d_to_2d( gripper_3d, K_ext, E_ext, img_h=img_h, img_w=img_w ) all_mesh_3d.append(gripper_3d) all_mesh_2d_ext.append(mesh_2d) all_mesh_vis_ext.append(mesh_vis) all_mesh_2d_ext = np.array(all_mesh_2d_ext) # [T, 7, 2] all_mesh_vis_ext = np.array(all_mesh_vis_ext) # [T, 7] # Check if at least some mesh points visible in first frame if np.sum(all_mesh_vis_ext[0]) < 2: return None # Compute FIXED mesh for wrist camera (moves with gripper state, NOT tracked) all_mesh_2d_wrist_fixed = [] for action in actions: gripper_state = action[6] mesh_wrist_fixed = get_wrist_fixed_mesh_2d(gripper_state, img_h, img_w) all_mesh_2d_wrist_fixed.append(mesh_wrist_fixed) all_mesh_2d_wrist_fixed = np.array(all_mesh_2d_wrist_fixed) # [T, 7, 2] # Wrist mesh is always visible (hardcoded 2D, always in frame) all_mesh_vis_wrist_fixed = np.ones((T, 7), dtype=bool) # Step 2: Sample CoTracker query points at frame 0 # LIBERO approach: 7 mesh + 98 grid + 1000 variance-sampled random = 1105 total mesh_2d_0 = all_mesh_2d_ext[0] # [7, 2] - all mesh points from frame 0 # Sample grid points for background coverage (uniform grid, always kept) grid_points_ext = sample_double_grid(n=7, img_h=img_h, img_w=img_w) # [98, 2] # Sample random points across entire image (filtered by variance > 10.0) if episode_idx is not None: np.random.seed(episode_idx) random_points_ext = np.random.rand(1000, 2) * [img_w, img_h] random_points_ext = random_points_ext.astype(np.float32) # Combine: first 7 = mesh, next 98 = grid, last 1000 = random (variance filtered) query_points_ext = np.vstack([mesh_2d_0, grid_points_ext, random_points_ext]) # [1105, 2] num_mesh_ext = 7 num_grid_ext = 98 # Wrist: 7 tracked mesh + 98 grid + 1000 random = 1105 total tracked points # Fixed mesh is saved separately (not part of tracked points) # Get gripper mesh for first frame (initial tracking queries) gripper_state_0 = actions[0][6] # action[6] is gripper state mesh_2d_wrist_tracked = get_wrist_gripper_mesh_2d(gripper_state_0, img_h, img_w) # [7, 2] # Fixed 5x5 wrist query grid (closest to crop edges with light padding). fixed_grid_wrist = sample_uniform_grid( n=5, img_h=img_h, img_w=img_w, pad_ratio=0.10, crop_left=92.0, crop_right=272.0, crop_top=0.0, crop_bottom=180.0, out_w=224.0, out_h=224.0, ) # [25, 2], uniform in resized-crop coordinates # Keep 5 rows but compress vertical span so the bottom row sits higher (above gripper). fixed_grid_wrist_xy = fixed_grid_wrist.reshape(5, 5, 2) y_top = fixed_grid_wrist_xy[0, 0, 1] y_bottom = fixed_grid_wrist_xy[3, 0, 1] fixed_grid_wrist_xy[:, :, 1] = np.linspace(y_top, y_bottom, 5, dtype=np.float32)[:, None] fixed_grid_wrist = fixed_grid_wrist_xy.reshape(-1, 2) # Keep total wrist grid count at 98 for compatibility with existing downstream assumptions. support_grid_wrist = sample_double_grid(n=7, img_h=img_h, img_w=img_w)[:73] # [73, 2] grid_points_wrist = np.vstack([fixed_grid_wrist, support_grid_wrist]).astype(np.float32) # [98, 2] fixed_grid_wrist_indices = np.arange(7, 7 + len(fixed_grid_wrist), dtype=np.int32) # [25] # Sample random points across entire image (filtered by variance > 10.0) if episode_idx is not None: np.random.seed(episode_idx + 1000) # Different seed for wrist random_points_wrist = np.random.rand(1000, 2) * [img_w, img_h] random_points_wrist = random_points_wrist.astype(np.float32) # Combine: first 7 = tracked mesh, next 98 = grid, last 1000 = random (variance filtered) query_points_wrist = np.vstack([mesh_2d_wrist_tracked, grid_points_wrist, random_points_wrist]) # [1105, 2] num_mesh_wrist = 7 num_grid_wrist = 98 # Step 3: Run CoTracker with enhanced tracking (temporal sampling + variance filtering) # Exterior view video_ext_np = np.array(frames_ext).transpose(0, 3, 1, 2) # [T, 3, H, W] video_ext_tensor = torch.from_numpy(video_ext_np).float() / 255.0 video_ext_tensor = video_ext_tensor.unsqueeze(0).to(device) # [1, T, 3, H, W] # Create temporal queries (mesh from t=0, others from random frames) queries_ext = create_temporal_queries(query_points_ext, T, num_mesh=7) queries_ext_tensor = torch.from_numpy(queries_ext).float().unsqueeze(0).to(device) # Track with variance filtering + forward/backward tracking # Threshold 10.0 matches LIBERO preprocessing # Preserve mesh (0-6) + grid (7-104) points, filter scattered (105-999) preserve_indices_ext = list(range(num_mesh_ext + num_grid_ext)) # 0-104 # Choose tracking function based on batching flag track_fn = track_with_variance_filter_batched if use_batching else track_with_variance_filter if use_batching: tracks_ext, vis_ext = track_fn( cotracker, video_ext_tensor, queries_ext_tensor, device, var_threshold=10.0, preserve_indices=preserve_indices_ext, batch_size=batch_size ) else: tracks_ext, vis_ext = track_fn( cotracker, video_ext_tensor, queries_ext_tensor, device, var_threshold=10.0, preserve_indices=preserve_indices_ext ) # tracks_ext: [T, 1000, 2], vis_ext: [T, 1000] # Wrist view video_wrist_np = np.array(frames_wrist).transpose(0, 3, 1, 2) video_wrist_tensor = torch.from_numpy(video_wrist_np).float() / 255.0 video_wrist_tensor = video_wrist_tensor.unsqueeze(0).to(device) # Create temporal queries (mesh + fixed wrist grid from t=0, others from random frames) queries_wrist = create_temporal_queries(query_points_wrist, T, num_mesh=7) queries_wrist[7:7 + len(fixed_grid_wrist), 0] = 0 queries_wrist_tensor = torch.from_numpy(queries_wrist).float().unsqueeze(0).to(device) # Track with variance filtering + forward/backward tracking (1105 points) # Threshold 10.0 matches LIBERO preprocessing # Preserve mesh (0-6) + grid (7-104) points, filter random (105-1104) preserve_indices_wrist = list(range(num_mesh_wrist + num_grid_wrist)) # 0-104 if use_batching: tracks_wrist, vis_wrist = track_fn( cotracker, video_wrist_tensor, queries_wrist_tensor, device, var_threshold=10.0, preserve_indices=preserve_indices_wrist, batch_size=batch_size ) else: tracks_wrist, vis_wrist = track_fn( cotracker, video_wrist_tensor, queries_wrist_tensor, device, var_threshold=10.0, preserve_indices=preserve_indices_wrist ) # tracks_wrist: [T, 1105, 2], vis_wrist: [T, 1105] # First 7 = tracked mesh, next 98 = grid, rest = variance-filtered random # Fixed mesh is saved separately in all_mesh_2d_wrist_fixed # Step 4: Save preview video if requested if save_video and output_dir: video_frames = [] for t in range(T): # Exterior view viz_ext = frames_ext[t].copy() # Draw ground truth mesh vertices (blue circles) for i in range(7): if all_mesh_vis_ext[t, i]: pt = tuple(all_mesh_2d_ext[t, i].astype(int)) cv2.circle(viz_ext, pt, 5, (255, 0, 0), 2) # Blue hollow cv2.putText(viz_ext, str(i), (pt[0]+6, pt[1]-6), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (255, 0, 0), 1) # Draw tracked mesh vertices (red filled) - first 7 of CoTracker for i in range(7): if vis_ext[t, i]: pt = tuple(tracks_ext[t, i].astype(int)) cv2.circle(viz_ext, pt, 3, (0, 0, 255), -1) # Red filled # Draw other CoTracker points (green, smaller) for i in range(7, len(tracks_ext[t])): if vis_ext[t, i]: pt = tuple(tracks_ext[t, i].astype(int)) cv2.circle(viz_ext, pt, 1, (0, 255, 0), -1) cv2.putText(viz_ext, f"Ext: GT mesh (blue) | Tracked mesh (red) | Others (green)", (5, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 255, 255), 1) # Wrist view viz_wrist = frames_wrist[t].copy() # Draw TRACKED mesh vertices (first 7 points) - magenta filled circles for i in range(7): if vis_wrist[t, i]: pt = tuple(tracks_wrist[t, i].astype(int)) cv2.circle(viz_wrist, pt, 3, (255, 0, 255), -1) # Magenta filled # Draw FIXED mesh vertices (from separate array) - cyan hollow circles for i in range(7): if all_mesh_vis_wrist_fixed[t, i]: pt = tuple(all_mesh_2d_wrist_fixed[t, i].astype(int)) cv2.circle(viz_wrist, pt, 4, (255, 255, 0), 2) # Cyan hollow # Label finger tips and joints if i in [1, 2, 3, 4]: # Tips and joints cv2.putText(viz_wrist, str(i), (pt[0]+5, pt[1]-5), cv2.FONT_HERSHEY_SIMPLEX, 0.25, (255, 255, 0), 1) # Draw other CoTracker points (grid + random, green, smaller) for i in range(7, len(tracks_wrist[t])): if vis_wrist[t, i]: pt = tuple(tracks_wrist[t, i].astype(int)) cv2.circle(viz_wrist, pt, 1, (0, 255, 0), -1) # Green cv2.putText(viz_wrist, f"Wrist: Tracked mesh (magenta) | Fixed mesh (cyan) | Others (green)", (5, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (255, 255, 255), 1) # Concatenate side by side combined = np.concatenate([viz_ext, viz_wrist], axis=1) cv2.putText(combined, f"Episode {episode_idx} | Frame {t}/{T}", (combined.shape[1]//2 - 60, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) video_frames.append(combined) video_path = output_dir / f"preview_episode_{episode_idx:06d}.mp4" media.write_video(str(video_path), video_frames, fps=10) # Return processed data return { 'episode_idx': episode_idx, 'uuid': uuid, 'frames_exterior': np.array(frames_ext), # [T, H, W, 3] 'frames_wrist': np.array(frames_wrist), 'actions': np.array(actions), # [T, 7] 'mesh_vertices_2d_exterior': all_mesh_2d_ext, # [T, 7, 2] - ground truth (3D projection) 'mesh_vertices_vis_exterior': all_mesh_vis_ext, # [T, 7] 'mesh_vertices_2d_wrist_fixed': all_mesh_2d_wrist_fixed, # [T, 7, 2] - fixed mesh (2D, hardcoded from annotations) 'mesh_vertices_vis_wrist_fixed': all_mesh_vis_wrist_fixed, # [T, 7] 'tracks_exterior': tracks_ext, # [T, 1105, 2] - 7 mesh + 98 grid + ~1000 variance-filtered random 'tracks_vis_exterior': vis_ext, # [T, 1105] 'tracks_wrist': tracks_wrist, # [T, 1105, 2] - 7 tracked mesh + 98 grid + ~1000 variance-filtered random 'tracks_vis_wrist': vis_wrist, # [T, 1105] - Fixed mesh saved separately above 'wrist_fixed_grid_points': fixed_grid_wrist, # [25, 2] in original 180x320 frame space 'wrist_fixed_grid_indices': fixed_grid_wrist_indices, # [25] indices into tracks_wrist axis=1 } def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('--num-episodes', type=int, default=None, help='Number of episodes to process (deprecated, use --end-episode)') parser.add_argument('--start-episode', type=int, default=0, help='Start episode index') parser.add_argument('--end-episode', type=int, default=None, help='End episode index (exclusive)') parser.add_argument('--episode-ids-file', type=str, default=None, help='JSON file with specific episode IDs to process') parser.add_argument('--output-dir', type=str, default='/tmp/droid_rlds_final', help='Output directory') parser.add_argument('--max-frames', type=int, default=400, help='Max frames per episode') parser.add_argument('--save-previews', type=int, default=3, help='Number of preview videos to save') parser.add_argument('--gpu-id', type=int, default=None, help='GPU ID for logging') args = parser.parse_args() # Handle backward compatibility if args.end_episode is None and args.num_episodes is not None: args.end_episode = args.start_episode + args.num_episodes # Load episode IDs from file if provided episode_ids_list = None if args.episode_ids_file: import json with open(args.episode_ids_file, 'r') as f: episode_ids_list = json.load(f) print(f"Loaded {len(episode_ids_list)} episode IDs from {args.episode_ids_file}") output_dir = Path(args.output_dir) output_dir.mkdir(parents=True, exist_ok=True) preview_dir = output_dir / 'preview_videos' preview_dir.mkdir(exist_ok=True) data_dir = output_dir / 'data' data_dir.mkdir(exist_ok=True) gpu_label = f"GPU {args.gpu_id}" if args.gpu_id is not None else "Processing" print("=" * 80) print(f"DROID Preprocessing: {gpu_label}") print("=" * 80) if episode_ids_list: print(f" Mode: Direct episode access (from file)") print(f" Episodes to process: {len(episode_ids_list)}") else: print(f" Mode: Range iteration") print(f" Episode range: {args.start_episode} to {args.end_episode if args.end_episode else 'end'}") print(f" Max frames: {args.max_frames}") print(f" Output: {output_dir}") print(f" Preview videos: {args.save_previews}") print("=" * 80) # Initialize # CUDA_VISIBLE_DEVICES handles GPU selection, so always use cuda:0 # (gpu_id is only for logging purposes) device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') 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(device=device) calib_path = Path(calib_dir) uuid_list = [f.stem.replace('_cameras', '') for f in sorted(calib_path.glob("*_cameras.json"))] print(f"Loaded {len(uuid_list)} camera calibrations") # Load dataset 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') # Process episodes processed_count = 0 skipped_count = 0 # DIRECT EPISODE ACCESS MODE (from file) if episode_ids_list: print(f"\n{gpu_label}: Processing {len(episode_ids_list)} specific episodes...") pbar = tqdm(total=len(episode_ids_list), desc=gpu_label) for episode_idx in episode_ids_list: pbar.update(1) # Skip if already processed npz_path = data_dir / f"episode_{episode_idx:06d}.npz" if npz_path.exists(): continue # Skip directly to this episode episode = dataset.skip(episode_idx).take(1) episode = next(iter(episode)) # Find calibration uuid = find_closest_calibration(episode, uuid_list) if uuid is None or not calib_loader.has_refined_extrinsics(uuid): skipped_count += 1 continue # Process episode (no need to check length - already filtered!) save_video = processed_count < args.save_previews try: # OOM retry logic: try unbatched first, retry with batching on OOM try: result = process_episode( episode, episode_idx, uuid, calib_loader, projector, cotracker, device, max_frames=args.max_frames, save_video=save_video, output_dir=preview_dir, use_batching=False ) except torch.cuda.OutOfMemoryError: print(f"\n OOM on episode {episode_idx}, retrying with batching (batch_size=600)...") torch.cuda.empty_cache() result = process_episode( episode, episode_idx, uuid, calib_loader, projector, cotracker, device, max_frames=args.max_frames, save_video=save_video, output_dir=preview_dir, use_batching=True, batch_size=150 ) if result is None: skipped_count += 1 continue # Save as NPZ npz_path = data_dir / f"episode_{episode_idx:06d}.npz" np.savez_compressed( npz_path, episode_idx=result['episode_idx'], uuid=result['uuid'], images_exterior=result['frames_exterior'], images_wrist=result['frames_wrist'], actions=result['actions'], mesh_vertices_2d_exterior=result['mesh_vertices_2d_exterior'], mesh_vertices_vis_exterior=result['mesh_vertices_vis_exterior'], mesh_vertices_2d_wrist_fixed=result['mesh_vertices_2d_wrist_fixed'], mesh_vertices_vis_wrist_fixed=result['mesh_vertices_vis_wrist_fixed'], tracks_exterior=result['tracks_exterior'], tracks_vis_exterior=result['tracks_vis_exterior'], tracks_wrist=result['tracks_wrist'], tracks_vis_wrist=result['tracks_vis_wrist'], wrist_fixed_grid_points=result['wrist_fixed_grid_points'], wrist_fixed_grid_indices=result['wrist_fixed_grid_indices'], mesh_indices=np.array([0, 1, 2, 3, 4, 5, 6], dtype=np.int32), ) processed_count += 1 except Exception as e: print(f"\nError processing episode {episode_idx}: {e}") skipped_count += 1 continue pbar.close() # RANGE ITERATION MODE (backward compatibility) else: # EFFICIENT SKIPPING: Use dataset.skip() instead of manual iteration if args.start_episode > 0: print(f"{gpu_label} Skipping to episode {args.start_episode}...") dataset = dataset.skip(args.start_episode) if args.end_episode is not None: num_episodes = args.end_episode - args.start_episode print(f"{gpu_label} Taking {num_episodes} episodes...") dataset = dataset.take(num_episodes) total_to_process = (args.end_episode - args.start_episode) if args.end_episode else None pbar = tqdm(total=total_to_process, desc=gpu_label) for local_idx, episode in enumerate(dataset): # Calculate actual episode index in full dataset episode_idx = args.start_episode + local_idx # Skip if already processed npz_path = data_dir / f"episode_{episode_idx:06d}.npz" if npz_path.exists(): pbar.update(1) continue # Find calibration uuid = find_closest_calibration(episode, uuid_list) if uuid is None or not calib_loader.has_refined_extrinsics(uuid): skipped_count += 1 pbar.update(1) continue # Check episode length episode_length = sum(1 for _ in episode['steps']) if episode_length > args.max_frames or episode_length < 10: skipped_count += 1 pbar.update(1) continue # Process episode save_video = processed_count < args.save_previews try: # OOM retry logic: try unbatched first, retry with batching on OOM try: result = process_episode( episode, episode_idx, uuid, calib_loader, projector, cotracker, device, max_frames=args.max_frames, save_video=save_video, output_dir=preview_dir, use_batching=False ) except torch.cuda.OutOfMemoryError: print(f"\n OOM on episode {episode_idx}, retrying with batching (batch_size=150)...") torch.cuda.empty_cache() result = process_episode( episode, episode_idx, uuid, calib_loader, projector, cotracker, device, max_frames=args.max_frames, save_video=save_video, output_dir=preview_dir, use_batching=True, batch_size=150 ) if result is None: skipped_count += 1 pbar.update(1) continue # Save as NPZ npz_path = data_dir / f"episode_{episode_idx:06d}.npz" np.savez_compressed( npz_path, episode_idx=result['episode_idx'], uuid=result['uuid'], images_exterior=result['frames_exterior'], images_wrist=result['frames_wrist'], actions=result['actions'], mesh_vertices_2d_exterior=result['mesh_vertices_2d_exterior'], mesh_vertices_vis_exterior=result['mesh_vertices_vis_exterior'], mesh_vertices_2d_wrist_fixed=result['mesh_vertices_2d_wrist_fixed'], mesh_vertices_vis_wrist_fixed=result['mesh_vertices_vis_wrist_fixed'], tracks_exterior=result['tracks_exterior'], tracks_vis_exterior=result['tracks_vis_exterior'], tracks_wrist=result['tracks_wrist'], tracks_vis_wrist=result['tracks_vis_wrist'], wrist_fixed_grid_points=result['wrist_fixed_grid_points'], wrist_fixed_grid_indices=result['wrist_fixed_grid_indices'], mesh_indices=np.array([0, 1, 2, 3, 4, 5, 6], dtype=np.int32), ) processed_count += 1 pbar.update(1) except Exception as e: print(f"\nError processing episode {episode_idx}: {e}") skipped_count += 1 pbar.update(1) continue pbar.close() # Save metadata metadata = { 'num_episodes': processed_count, 'split': 'train', 'camera_params': { 'exterior': { 'extrinsics': 'refined', 'intrinsics': 'measured', 'inversion': False }, 'wrist': { 'sampling': 'random', 'dense_region': 'bottom_60_100_pct' } }, 'point_distribution': { 'exterior': { 'total_tracked_points': 1000, 'mesh_vertices_tracked': 7, # First 7 indices 'additional_points': 993, # Indices 7-999 'arm_shaped_strategy': 'gaussian_15px_per_mesh + lines_between', 'note': 'Mesh vertices tracked by CoTracker AND saved as ground truth separately' }, 'wrist': { 'total_tracked_points': 1000, 'sparse_uniform': 300, # First 300 indices 'dense_bottom': 700 # Last 700 indices in bottom 60%-100% } }, 'image_resolution': [180, 320], 'max_frames_per_episode': args.max_frames, 'cotracker_model': 'scaled_offline.pth', 'cotracker_chunking': 'automatic_internal_only' } with open(output_dir / 'metadata.json', 'w') as f: json.dump(metadata, f, indent=2) print("\n" + "=" * 80) print("Preprocessing Complete") print("=" * 80) print(f" Processed: {processed_count} episodes") print(f" Skipped: {skipped_count} episodes") print(f" Preview videos: {preview_dir}") print(f" NPZ data: {data_dir}") print(f" Metadata: {output_dir / 'metadata.json'}") print("=" * 80) if __name__ == "__main__": main()