openpi / droid /scripts /reprocess_mesh_vertices.py
zhicao's picture
Upload folder using huggingface_hub
b584148 verified
Raw
History Blame Contribute Delete
9.58 kB
#!/usr/bin/env python3
"""
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
"""
# 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 (far right)
[221, 97], # 2: RIGHT finger joint
[49, 108], # 3: LEFT finger tip (far left)
[86, 101], # 4: LEFT finger joint
[195, 141], # 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 (shifted center)
[198, 102], # 1: RIGHT finger tip (only 8px from left!)
[195, 98], # 2: RIGHT finger joint
[186, 104], # 3: LEFT finger tip (only 8px from right!)
[188, 100], # 4: LEFT finger joint
[195, 141], # 5: right palm interior (same)
[95, 138], # 6: left palm interior (same)
], dtype=np.float32)
# Linear interpolation: 0.0 (OPEN) → 1.0 (CLOSED)
# mesh = (1 - gripper_state) * mesh_open + gripper_state * mesh_closed
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)
# Load actions
actions = data['actions'] # [T, 7]
gripper_states = actions[:, 6] # [T]
T = len(actions)
# Load existing mesh data (we'll only modify wrist mesh for now)
mesh_vertices_2d_exterior = data['mesh_vertices_2d_exterior'] # [T, 7, 2]
mesh_vertices_vis_exterior = data['mesh_vertices_vis_exterior'] # [T, 7]
mesh_vertices_2d_wrist_old = data['mesh_vertices_2d_wrist_fixed'] # [T, 7, 2]
mesh_vertices_vis_wrist = data['mesh_vertices_vis_wrist_fixed'] # [T, 7]
# Recompute wrist mesh with interpolation
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])
# Calculate how much changed
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()
# Calculate finger spread before and after
def calc_finger_spread(mesh_2d, vis):
spreads = []
for t in range(len(mesh_2d)):
if vis[t, 1] and vis[t, 3]: # Both finger tips visible
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,
}
# Save if not dry run
if not dry_run:
# Create new NPZ with updated wrist mesh
# Load all arrays from original NPZ
new_data = {key: data[key] for key in data.keys()}
# Replace wrist mesh
new_data['mesh_vertices_2d_wrist_fixed'] = mesh_vertices_2d_wrist_new
# Save atomically (write to temp file, then rename)
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
# Get episode files
episode_files = sorted(list(data_path.glob("episode_*.npz")))
print(f"Found {len(episode_files)} episodes in {data_path}")
# Determine range
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")
# Process episodes
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 summary
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")
# Show episodes with biggest changes
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}]")
# Finger spread statistics
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}")
# TODO: Add visualization if requested
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()