| """ |
| 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 |
|
|
|
|
| |
| GRIPPER_OFFSETS = np.array([ |
| [0.0, 0.0, 0.0], |
| [0.0, 0.045, 0.161], |
| [0.0, -0.045, 0.161], |
| [0.0, 0.045, 0.13], |
| [0.0, -0.045, 0.13], |
| [0.0, 0.0, 0.13], |
| [0.0, 0.0, 0.065], |
| ]) |
|
|
|
|
| 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: |
| |
| return np.random.rand(num_points, 2) * [img_w, img_h] |
|
|
| |
| points_per_mesh = min(15, num_points // num_visible) |
| gaussian_sigma = 15.0 |
|
|
| for mesh_pt in mesh_2d_visible: |
| gaussian_pts = np.random.randn(points_per_mesh, 2) * gaussian_sigma + mesh_pt |
| |
| 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) |
|
|
| |
| if num_visible >= 2: |
| |
| 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]) |
|
|
| |
| 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) |
|
|
| |
| all_points = np.vstack(points) if points else np.empty((0, 2)) |
|
|
| if len(all_points) < num_points: |
| |
| 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: |
| |
| 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 |
| """ |
| |
| |
| mesh_open = np.array([ |
| [141, 108], |
| [253, 106], |
| [129, 131], |
| [290, 130], |
| [168, 156], |
| [284, 156], |
| [95, 138], |
| ], dtype=np.float32) |
|
|
| |
| mesh_closed = np.array([ |
| [190, 102], |
| [198, 102], |
| [195, 120], |
| [216, 119], |
| [200, 152], |
| [245, 150], |
| [168, 126], |
| ], dtype=np.float32) |
|
|
| |
| alpha = gripper_state |
| 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 |
| """ |
| |
| |
|
|
| |
| mesh_open = np.array([ |
| [141, 108], |
| [253, 106], |
| [129, 131], |
| [290, 130], |
| [168, 156], |
| [284, 156], |
| [95, 138], |
| ], dtype=np.float32) |
|
|
| |
| mesh_closed = np.array([ |
| [190, 102], |
| [198, 102], |
| [195, 120], |
| [216, 119], |
| [200, 152], |
| [245, 150], |
| [168, 126], |
| ], dtype=np.float32) |
|
|
| |
| |
| alpha = gripper_state |
| 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 |
| """ |
| |
| 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) |
|
|
| |
| 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) |
|
|
| |
| 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 = np.random.rand(num_sparse, 2) * [img_w, img_h] |
|
|
| |
| |
| 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) |
|
|
| |
| queries[:num_mesh, 0] = 0 |
| queries[:num_mesh, 1:] = points_2d[:num_mesh] |
|
|
| |
| 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] |
|
|
| |
| with torch.no_grad(): |
| tracks_fwd, vis_fwd = cotracker( |
| video_tensor, |
| queries=queries_tensor, |
| backward_tracking=False |
| ) |
|
|
| |
| with torch.no_grad(): |
| tracks_bwd, vis_bwd = cotracker( |
| video_tensor, |
| queries=queries_tensor, |
| backward_tracking=True |
| ) |
|
|
| |
| tracks = (tracks_fwd + tracks_bwd) / 2.0 |
| vis = (vis_fwd + vis_bwd) / 2.0 |
|
|
| |
| |
| variance = torch.var(tracks[0], dim=0).sum(dim=-1) |
|
|
| |
| if preserve_indices is not None: |
| variance[preserve_indices] = float('inf') |
|
|
| |
| valid_idx = torch.where(variance > var_threshold)[0] |
|
|
| |
| if len(valid_idx) < N: |
| n_needed = N - len(valid_idx) |
|
|
| |
| resample_idx = valid_idx[torch.randint(len(valid_idx), (n_needed,), device=device)] |
| new_queries = queries_tensor[:, resample_idx].clone() |
|
|
| |
| noise = torch.randn_like(new_queries[:, :, 1:]) * 0.05 * H |
| new_queries[:, :, 1:] = torch.clamp(new_queries[:, :, 1:] + noise, 0, None) |
|
|
| |
| with torch.no_grad(): |
| new_tracks, new_vis = cotracker( |
| video_tensor, |
| queries=new_queries, |
| backward_tracking=True |
| ) |
|
|
| |
| tracks = torch.cat([tracks[:, :, valid_idx], new_tracks], dim=2) |
| vis = torch.cat([vis[:, :, valid_idx], new_vis], dim=2) |
| else: |
| |
| 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] |
|
|
| |
| num_batches = (N + batch_size - 1) // batch_size |
| print(f" [BATCHED] Tracking {N} points in {num_batches} batches of {batch_size}") |
|
|
| |
| 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) |
|
|
| |
| torch.cuda.empty_cache() |
|
|
| |
| tracks_fwd = torch.cat(tracks_fwd_list, dim=2) |
| vis_fwd = torch.cat(vis_fwd_list, dim=2) |
|
|
| |
| 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) |
|
|
| |
| torch.cuda.empty_cache() |
|
|
| |
| tracks_bwd = torch.cat(tracks_bwd_list, dim=2) |
| vis_bwd = torch.cat(vis_bwd_list, dim=2) |
|
|
| |
| tracks = (tracks_fwd + tracks_bwd) / 2.0 |
| vis = (vis_fwd + vis_bwd) / 2.0 |
|
|
| |
| variance = torch.var(tracks[0], dim=0).sum(dim=-1) |
|
|
| |
| if preserve_indices is not None: |
| variance[preserve_indices] = float('inf') |
|
|
| |
| valid_idx = torch.where(variance > var_threshold)[0] |
|
|
| |
| if len(valid_idx) < N: |
| n_needed = N - len(valid_idx) |
|
|
| |
| resample_idx = valid_idx[torch.randint(len(valid_idx), (n_needed,), device=device)] |
| new_queries = queries_tensor[:, resample_idx].clone() |
|
|
| |
| noise = torch.randn_like(new_queries[:, :, 1:]) * 0.05 * H |
| new_queries[:, :, 1:] = torch.clamp(new_queries[:, :, 1:] + noise, 0, None) |
|
|
| |
| |
| 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 |
| ) |
|
|
| |
| tracks = torch.cat([tracks[:, :, valid_idx], new_tracks], dim=2) |
| vis = torch.cat([vis[:, :, valid_idx], new_vis], dim=2) |
| else: |
| |
| 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') |
|
|
| |
| 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: |
| |
| file_path = episode['episode_metadata']['file_path'].numpy().decode('utf-8') |
| |
| 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)) |
|
|
| |
| closest_uuid = None |
| min_diff = None |
|
|
| for uuid in uuid_list: |
| try: |
| |
| 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 |
| """ |
| |
| 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'] |
|
|
| |
| 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: |
| |
| return None |
|
|
| |
| if valid_frame_count < 10: |
| return None |
|
|
| |
| 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] |
|
|
| |
| all_mesh_3d = [] |
| all_mesh_2d_ext = [] |
| all_mesh_vis_ext = [] |
|
|
| for action in actions: |
| |
| gripper_3d = transform_gripper_offsets(action) |
|
|
| |
| 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) |
| all_mesh_vis_ext = np.array(all_mesh_vis_ext) |
|
|
| |
| if np.sum(all_mesh_vis_ext[0]) < 2: |
| return None |
|
|
| |
| 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) |
| |
| all_mesh_vis_wrist_fixed = np.ones((T, 7), dtype=bool) |
|
|
| |
| |
| mesh_2d_0 = all_mesh_2d_ext[0] |
|
|
| |
| grid_points_ext = sample_double_grid(n=7, img_h=img_h, img_w=img_w) |
|
|
| |
| 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) |
|
|
| |
| query_points_ext = np.vstack([mesh_2d_0, grid_points_ext, random_points_ext]) |
| num_mesh_ext = 7 |
| num_grid_ext = 98 |
|
|
| |
| |
| |
| gripper_state_0 = actions[0][6] |
| mesh_2d_wrist_tracked = get_wrist_gripper_mesh_2d(gripper_state_0, img_h, img_w) |
|
|
| |
| 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, |
| ) |
| |
| 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) |
| |
| support_grid_wrist = sample_double_grid(n=7, img_h=img_h, img_w=img_w)[:73] |
| grid_points_wrist = np.vstack([fixed_grid_wrist, support_grid_wrist]).astype(np.float32) |
| fixed_grid_wrist_indices = np.arange(7, 7 + len(fixed_grid_wrist), dtype=np.int32) |
|
|
| |
| if episode_idx is not None: |
| np.random.seed(episode_idx + 1000) |
| random_points_wrist = np.random.rand(1000, 2) * [img_w, img_h] |
| random_points_wrist = random_points_wrist.astype(np.float32) |
|
|
| |
| query_points_wrist = np.vstack([mesh_2d_wrist_tracked, grid_points_wrist, random_points_wrist]) |
| num_mesh_wrist = 7 |
| num_grid_wrist = 98 |
|
|
| |
| |
| video_ext_np = np.array(frames_ext).transpose(0, 3, 1, 2) |
| video_ext_tensor = torch.from_numpy(video_ext_np).float() / 255.0 |
| video_ext_tensor = video_ext_tensor.unsqueeze(0).to(device) |
|
|
| |
| 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) |
|
|
| |
| |
| |
| preserve_indices_ext = list(range(num_mesh_ext + num_grid_ext)) |
|
|
| |
| 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 |
| ) |
| |
|
|
| |
| 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) |
|
|
| |
| 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) |
|
|
| |
| |
| |
| preserve_indices_wrist = list(range(num_mesh_wrist + num_grid_wrist)) |
|
|
| 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 |
| ) |
| |
| |
| |
|
|
| |
| if save_video and output_dir: |
| video_frames = [] |
| for t in range(T): |
| |
| viz_ext = frames_ext[t].copy() |
|
|
| |
| 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) |
| cv2.putText(viz_ext, str(i), (pt[0]+6, pt[1]-6), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.3, (255, 0, 0), 1) |
|
|
| |
| 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) |
|
|
| |
| 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) |
|
|
| |
| viz_wrist = frames_wrist[t].copy() |
|
|
| |
| 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) |
|
|
| |
| 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) |
| |
| if i in [1, 2, 3, 4]: |
| cv2.putText(viz_wrist, str(i), (pt[0]+5, pt[1]-5), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.25, (255, 255, 0), 1) |
|
|
| |
| 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) |
|
|
| 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) |
|
|
| |
| 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 { |
| 'episode_idx': episode_idx, |
| 'uuid': uuid, |
| 'frames_exterior': np.array(frames_ext), |
| 'frames_wrist': np.array(frames_wrist), |
| 'actions': np.array(actions), |
| 'mesh_vertices_2d_exterior': all_mesh_2d_ext, |
| 'mesh_vertices_vis_exterior': all_mesh_vis_ext, |
| 'mesh_vertices_2d_wrist_fixed': all_mesh_2d_wrist_fixed, |
| 'mesh_vertices_vis_wrist_fixed': all_mesh_vis_wrist_fixed, |
| 'tracks_exterior': tracks_ext, |
| 'tracks_vis_exterior': vis_ext, |
| 'tracks_wrist': tracks_wrist, |
| 'tracks_vis_wrist': vis_wrist, |
| 'wrist_fixed_grid_points': fixed_grid_wrist, |
| 'wrist_fixed_grid_indices': fixed_grid_wrist_indices, |
| } |
|
|
|
|
| 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() |
|
|
| |
| if args.end_episode is None and args.num_episodes is not None: |
| args.end_episode = args.start_episode + args.num_episodes |
|
|
| |
| 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) |
|
|
| |
| |
| |
| 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") |
|
|
| |
| 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') |
|
|
| |
| processed_count = 0 |
| skipped_count = 0 |
|
|
| |
| 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) |
|
|
| |
| npz_path = data_dir / f"episode_{episode_idx:06d}.npz" |
| if npz_path.exists(): |
| continue |
|
|
| |
| episode = dataset.skip(episode_idx).take(1) |
| episode = next(iter(episode)) |
|
|
| |
| uuid = find_closest_calibration(episode, uuid_list) |
| if uuid is None or not calib_loader.has_refined_extrinsics(uuid): |
| skipped_count += 1 |
| continue |
|
|
| |
| save_video = processed_count < args.save_previews |
|
|
| try: |
| |
| 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 |
|
|
| |
| 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() |
|
|
| |
| else: |
| |
| 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): |
| |
| episode_idx = args.start_episode + local_idx |
|
|
| |
| npz_path = data_dir / f"episode_{episode_idx:06d}.npz" |
| if npz_path.exists(): |
| pbar.update(1) |
| continue |
|
|
| |
| 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 |
|
|
| |
| 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 |
|
|
| |
| save_video = processed_count < args.save_previews |
|
|
| try: |
| |
| 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 |
|
|
| |
| 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() |
|
|
| |
| 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, |
| 'additional_points': 993, |
| '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, |
| 'dense_bottom': 700 |
| } |
| }, |
| '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() |
|
|