| |
| """ |
| Reprocess mesh vertices in existing DROID NPZ files. |
| |
| FIXES: |
| 1. Wrist view: Interpolate FIXED 2D mesh based on actual gripper_state values |
| 2. Exterior view: (TODO) May need different camera offsets for OPEN vs CLOSED |
| |
| This script: |
| - Loads existing NPZ files |
| - Recalculates mesh vertices with proper gripper state interpolation |
| - Saves back to NPZ (overwrites mesh_vertices_2d_wrist_fixed) |
| - Keeps all other data unchanged |
| |
| Usage: |
| python reprocess_mesh_vertices.py --start 0 --end 100 # Test on first 100 episodes |
| python reprocess_mesh_vertices.py --all # Reprocess all episodes |
| """ |
| import sys |
| from pathlib import Path |
| sys.path.append(str(Path(__file__).parent.parent)) |
|
|
| import argparse |
| import numpy as np |
| from tqdm import tqdm |
|
|
| def get_wrist_fixed_mesh_interpolated(gripper_state: float) -> np.ndarray: |
| """ |
| Get wrist mesh vertices with proper gripper state interpolation. |
| |
| IMPORTANT: DROID convention (INVERTED): |
| 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] |
| |
| Returns: |
| mesh_2d: [7, 2] array of mesh vertex coordinates |
| """ |
| |
| |
|
|
| |
| mesh_open = np.array([ |
| [141, 108], |
| [253, 106], |
| [221, 97], |
| [49, 108], |
| [86, 101], |
| [195, 141], |
| [95, 138], |
| ], dtype=np.float32) |
|
|
| |
| mesh_closed = np.array([ |
| [190, 102], |
| [198, 102], |
| [195, 98], |
| [186, 104], |
| [188, 100], |
| [195, 141], |
| [95, 138], |
| ], dtype=np.float32) |
|
|
| |
| |
| alpha = np.clip(gripper_state, 0.0, 1.0) |
| mesh_interpolated = (1.0 - alpha) * mesh_open + alpha * mesh_closed |
|
|
| return mesh_interpolated |
|
|
|
|
| def reprocess_episode(npz_path: Path, dry_run: bool = False) -> dict: |
| """ |
| Reprocess mesh vertices for a single episode. |
| |
| Args: |
| npz_path: Path to NPZ file |
| dry_run: If True, don't save changes |
| |
| Returns: |
| dict with statistics |
| """ |
| data = np.load(npz_path, allow_pickle=True) |
|
|
| |
| actions = data['actions'] |
| gripper_states = actions[:, 6] |
| T = len(actions) |
|
|
| |
| mesh_vertices_2d_exterior = data['mesh_vertices_2d_exterior'] |
| mesh_vertices_vis_exterior = data['mesh_vertices_vis_exterior'] |
| mesh_vertices_2d_wrist_old = data['mesh_vertices_2d_wrist_fixed'] |
| mesh_vertices_vis_wrist = data['mesh_vertices_vis_wrist_fixed'] |
|
|
| |
| mesh_vertices_2d_wrist_new = np.zeros((T, 7, 2), dtype=np.float32) |
| for t in range(T): |
| mesh_vertices_2d_wrist_new[t] = get_wrist_fixed_mesh_interpolated(gripper_states[t]) |
|
|
| |
| max_change = np.abs(mesh_vertices_2d_wrist_new - mesh_vertices_2d_wrist_old).max() |
| mean_change = np.abs(mesh_vertices_2d_wrist_new - mesh_vertices_2d_wrist_old).mean() |
|
|
| |
| def calc_finger_spread(mesh_2d, vis): |
| spreads = [] |
| for t in range(len(mesh_2d)): |
| if vis[t, 1] and vis[t, 3]: |
| spread = np.linalg.norm(mesh_2d[t, 1] - mesh_2d[t, 3]) |
| spreads.append(spread) |
| return np.array(spreads) |
|
|
| spread_old = calc_finger_spread(mesh_vertices_2d_wrist_old, mesh_vertices_vis_wrist) |
| spread_new = calc_finger_spread(mesh_vertices_2d_wrist_new, mesh_vertices_vis_wrist) |
|
|
| stats = { |
| 'npz_path': npz_path.name, |
| 'frames': T, |
| 'gripper_min': gripper_states.min(), |
| 'gripper_max': gripper_states.max(), |
| 'gripper_mean': gripper_states.mean(), |
| 'max_change': max_change, |
| 'mean_change': mean_change, |
| 'spread_old_min': spread_old.min() if len(spread_old) > 0 else np.nan, |
| 'spread_old_max': spread_old.max() if len(spread_old) > 0 else np.nan, |
| 'spread_new_min': spread_new.min() if len(spread_new) > 0 else np.nan, |
| 'spread_new_max': spread_new.max() if len(spread_new) > 0 else np.nan, |
| } |
|
|
| |
| if not dry_run: |
| |
| |
| new_data = {key: data[key] for key in data.keys()} |
| |
| new_data['mesh_vertices_2d_wrist_fixed'] = mesh_vertices_2d_wrist_new |
|
|
| |
| temp_path = npz_path.with_suffix('.npz.tmp') |
| np.savez_compressed(temp_path, **new_data) |
| temp_path.replace(npz_path) |
|
|
| data.close() |
| return stats |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description='Reprocess mesh vertices in DROID NPZ files') |
| parser.add_argument('--data-dir', type=str, default='/mnt/kevin/data/droid_preprocessed/data', |
| help='Directory containing NPZ files') |
| parser.add_argument('--start', type=int, default=None, help='Start episode index') |
| parser.add_argument('--end', type=int, default=None, help='End episode index (exclusive)') |
| parser.add_argument('--all', action='store_true', help='Process all episodes') |
| parser.add_argument('--dry-run', action='store_true', help='Test without saving changes') |
| parser.add_argument('--visualize', type=int, default=0, |
| help='Number of episodes to visualize for verification') |
| args = parser.parse_args() |
|
|
| data_path = Path(args.data_dir) |
| if not data_path.exists(): |
| print(f"Error: Data directory not found: {data_path}") |
| return |
|
|
| |
| episode_files = sorted(list(data_path.glob("episode_*.npz"))) |
| print(f"Found {len(episode_files)} episodes in {data_path}") |
|
|
| |
| if args.all: |
| start_idx = 0 |
| end_idx = len(episode_files) |
| else: |
| start_idx = args.start if args.start is not None else 0 |
| end_idx = args.end if args.end is not None else min(start_idx + 100, len(episode_files)) |
|
|
| episodes_to_process = episode_files[start_idx:end_idx] |
| print(f"\nProcessing episodes {start_idx} to {end_idx-1} ({len(episodes_to_process)} total)") |
|
|
| if args.dry_run: |
| print("DRY RUN MODE - no changes will be saved") |
|
|
| |
| all_stats = [] |
| for npz_path in tqdm(episodes_to_process, desc="Reprocessing"): |
| try: |
| stats = reprocess_episode(npz_path, dry_run=args.dry_run) |
| all_stats.append(stats) |
| except Exception as e: |
| print(f"\nError processing {npz_path.name}: {e}") |
| continue |
|
|
| |
| print("\n" + "=" * 80) |
| print("Reprocessing Summary") |
| print("=" * 80) |
| print(f"Episodes processed: {len(all_stats)}") |
|
|
| if len(all_stats) > 0: |
| max_changes = [s['max_change'] for s in all_stats] |
| mean_changes = [s['mean_change'] for s in all_stats] |
|
|
| print(f"\nMesh vertex changes:") |
| print(f" Max change per episode: {np.max(max_changes):.2f} pixels") |
| print(f" Mean change per episode: {np.mean(mean_changes):.2f} pixels") |
| print(f" Median change per episode: {np.median(mean_changes):.2f} pixels") |
|
|
| |
| sorted_by_change = sorted(all_stats, key=lambda x: x['max_change'], reverse=True) |
| print(f"\nTop 5 episodes with biggest changes:") |
| for i, s in enumerate(sorted_by_change[:5]): |
| print(f" {i+1}. {s['npz_path']}: max_change={s['max_change']:.2f}px, " |
| f"gripper_range=[{s['gripper_min']:.3f}, {s['gripper_max']:.3f}]") |
|
|
| |
| spread_old_min = np.nanmin([s['spread_old_min'] for s in all_stats]) |
| spread_old_max = np.nanmax([s['spread_old_max'] for s in all_stats]) |
| spread_new_min = np.nanmin([s['spread_new_min'] for s in all_stats]) |
| spread_new_max = np.nanmax([s['spread_new_max'] for s in all_stats]) |
|
|
| print(f"\nFinger spread (wrist view):") |
| print(f" OLD (fixed): [{spread_old_min:.1f}, {spread_old_max:.1f}] pixels") |
| print(f" NEW (interpolated): [{spread_new_min:.1f}, {spread_new_max:.1f}] pixels") |
|
|
| print("=" * 80) |
|
|
| if args.dry_run: |
| print("\n⚠ DRY RUN - No changes were saved!") |
| print("Remove --dry-run flag to actually update the NPZ files.") |
| else: |
| print(f"\n✓ Successfully updated {len(all_stats)} episodes") |
| print(f" NPZ files in: {data_path}") |
|
|
| |
| if args.visualize > 0: |
| print(f"\n⚠ Visualization not implemented yet") |
| print(f" Use visualize_gripper_mesh_alignment.py to check results") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|