Download droid/scripts/test_preprocessing_with_viz.py from zhicao/openpi: direct link, hf CLI and curl.
- Browser
- Download file 14.4 kB
-
https://huggingface.co/datasets/zhicao/openpi/resolve/main/droid/scripts/test_preprocessing_with_viz.py
- Command line
-
hf download hf://datasets/zhicao/openpi/droid/scripts/test_preprocessing_with_viz.py
-
curl -L -o test_preprocessing_with_viz.py https://huggingface.co/datasets/zhicao/openpi/resolve/main/droid/scripts/test_preprocessing_with_viz.py
14.4 kB
| """ | |
| Test Preprocessing with Visualizations | |
| Quick test of DROID preprocessing pipeline with visual output: | |
| - Processes small number of episodes (5-10) | |
| - Uses cartesian_position + refined_extrinsics filtering | |
| - Generates visualization images showing projected tracks | |
| - Saves NPZ files for inspection | |
| """ | |
| import numpy as np | |
| import tensorflow_datasets as tfds | |
| from pathlib import Path | |
| import argparse | |
| import cv2 | |
| import sys | |
| from tqdm import tqdm | |
| import os | |
| # Force TensorFlow to use CPU to avoid GPU memory issues | |
| os.environ['CUDA_VISIBLE_DEVICES'] = '' | |
| os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true' | |
| # Add parent directory to path | |
| sys.path.append(str(Path(__file__).parent.parent)) | |
| from utils.load_camera_calibration import CameraCalibrationLoader | |
| from utils.franka_mesh_projection import FrankaMeshProjector | |
| def visualize_tracks(img: np.ndarray, | |
| tracks: np.ndarray, | |
| visibility: np.ndarray, | |
| title: str = "") -> np.ndarray: | |
| """ | |
| Visualize 32 tracks on image. | |
| Args: | |
| img: RGB image (H, W, 3) | |
| tracks: Track points (32, 2) | |
| visibility: Visibility mask (32,) | |
| title: Title for image | |
| Returns: | |
| Annotated image | |
| """ | |
| viz = img.copy() | |
| # Draw grid points (0-24) in blue | |
| for i in range(25): | |
| if visibility[i]: | |
| pt = tuple(tracks[i].astype(int)) | |
| cv2.circle(viz, pt, 4, (0, 0, 255), -1) | |
| # Draw mesh points (25-31) in green | |
| for i in range(25, 32): | |
| if visibility[i]: | |
| pt = tuple(tracks[i].astype(int)) | |
| cv2.circle(viz, pt, 5, (0, 255, 0), -1) | |
| cv2.putText(viz, str(i-25), (pt[0]+7, pt[1]-7), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 255, 0), 1) | |
| # Add title | |
| cv2.putText(viz, title, (10, 30), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2) | |
| # Add statistics | |
| visible_grid = np.sum(visibility[:25]) | |
| visible_mesh = np.sum(visibility[25:]) | |
| cv2.putText(viz, f"Grid: {visible_grid}/25 Mesh: {visible_mesh}/7", (10, 60), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 1) | |
| return viz | |
| def test_preprocessing(droid_path: str, | |
| calib_dir: str, | |
| output_dir: str, | |
| num_episodes: int = 5, | |
| use_cartesian: bool = True, | |
| require_refined: bool = True): | |
| """ | |
| Test preprocessing with visualizations. | |
| Args: | |
| droid_path: Path to DROID RLDS dataset | |
| calib_dir: Path to camera calibration directory | |
| output_dir: Output directory for test results | |
| num_episodes: Number of episodes to process | |
| use_cartesian: Use cartesian_position (vs FK) | |
| require_refined: Require refined_extrinsics | |
| """ | |
| print("=" * 80) | |
| print("DROID Preprocessing Test with Visualizations") | |
| print("=" * 80) | |
| print(f" Output: {output_dir}") | |
| print(f" Episodes: {num_episodes}") | |
| print(f" Projection: {'cartesian_position' if use_cartesian else 'joint_position (FK)'}") | |
| print(f" Require refined: {require_refined}") | |
| print() | |
| # Create output directories | |
| output_path = Path(output_dir) | |
| npz_path = output_path / "npz_files" | |
| viz_path = output_path / "visualizations" | |
| npz_path.mkdir(parents=True, exist_ok=True) | |
| viz_path.mkdir(parents=True, exist_ok=True) | |
| # Initialize tools | |
| calib_loader = CameraCalibrationLoader(calib_dir) | |
| projector = FrankaMeshProjector(use_gui=False) | |
| # Load RLDS dataset | |
| print("Loading DROID dataset...") | |
| builder = tfds.builder_from_directory(droid_path) | |
| dataset = builder.as_dataset(split='train') | |
| # Get list of all calibration files for UUID matching | |
| calib_path = Path(calib_dir) | |
| calib_files = sorted(calib_path.glob("*_cameras.json")) | |
| uuid_list = [f.stem.replace('_cameras', '') for f in calib_files] | |
| print(f"Found {len(uuid_list)} camera calibration files") | |
| # Filter to refined only | |
| if require_refined: | |
| refined_uuids = [uuid for uuid in uuid_list if calib_loader.has_refined_extrinsics(uuid)] | |
| print(f" {len(refined_uuids)}/{len(uuid_list)} have refined_extrinsics ({100*len(refined_uuids)/len(uuid_list):.1f}%)") | |
| uuid_list = refined_uuids | |
| # Process episodes | |
| processed = 0 | |
| skipped = 0 | |
| skipped_reasons = { | |
| 'no_uuid': 0, | |
| 'no_calib': 0, | |
| 'decode_error': 0, | |
| 'other': 0 | |
| } | |
| pbar = tqdm(total=num_episodes, desc="Processing") | |
| for episode_idx, episode in enumerate(dataset): | |
| if processed >= num_episodes: | |
| break | |
| try: | |
| # Try to match UUID first (before loading steps) | |
| uuid = uuid_list[episode_idx % len(uuid_list)] | |
| # Load calibration | |
| try: | |
| dual_params = calib_loader.get_dual_view_params( | |
| uuid, | |
| param_type='refined', | |
| require_refined=require_refined | |
| ) | |
| if dual_params is None: | |
| skipped += 1 | |
| skipped_reasons['no_calib'] += 1 | |
| continue | |
| except Exception as e: | |
| skipped += 1 | |
| skipped_reasons['no_calib'] += 1 | |
| continue | |
| # IMPORTANT: Don't call list() on episode['steps'] - iterate directly | |
| # This avoids loading entire episode into memory | |
| all_tracks_ext = [] | |
| all_tracks_wrist = [] | |
| all_vis_ext = [] | |
| all_vis_wrist = [] | |
| all_images_ext = [] | |
| all_images_wrist = [] | |
| decode_failed = False | |
| step_count = 0 | |
| max_steps_per_episode = 30 # Limit to 30 steps for testing | |
| # Iterate steps incrementally without loading all at once | |
| for step_idx, step in enumerate(episode['steps']): | |
| # Limit steps per episode | |
| if step_idx >= max_steps_per_episode: | |
| break | |
| step_count += 1 | |
| # Get robot state | |
| if use_cartesian: | |
| cart_pos = step['observation']['cartesian_position'].numpy() | |
| else: | |
| joint_pos = step['observation']['joint_position'].numpy() | |
| # Load images | |
| img_ext_bytes = step['observation']['exterior_image_1_left'].numpy() | |
| img_ext = cv2.imdecode(np.frombuffer(img_ext_bytes, dtype=np.uint8), cv2.IMREAD_COLOR) | |
| img_wrist_bytes = step['observation']['wrist_image_left'].numpy() | |
| img_wrist = cv2.imdecode(np.frombuffer(img_wrist_bytes, dtype=np.uint8), cv2.IMREAD_COLOR) | |
| if img_ext is None or img_wrist is None: | |
| decode_failed = True | |
| break | |
| # Resize and convert | |
| img_ext = cv2.resize(img_ext, (448, 448)) | |
| img_ext = cv2.cvtColor(img_ext, cv2.COLOR_BGR2RGB) | |
| all_images_ext.append(img_ext) | |
| img_wrist = cv2.resize(img_wrist, (448, 448)) | |
| img_wrist = cv2.cvtColor(img_wrist, cv2.COLOR_BGR2RGB) | |
| all_images_wrist.append(img_wrist) | |
| # Project tracks | |
| K_ext, E_ext = dual_params['exterior_1'] | |
| K_wrist, E_wrist = dual_params['wrist'] | |
| if use_cartesian: | |
| tracks_ext, vis_ext = projector.project_32_points_cartesian( | |
| cart_pos, K_ext, E_ext, img_h=448, img_w=448, rotation_format='euler_xyz' | |
| ) | |
| tracks_wrist, vis_wrist = projector.project_32_points_cartesian( | |
| cart_pos, K_wrist, E_wrist, img_h=448, img_w=448, rotation_format='euler_xyz' | |
| ) | |
| else: | |
| tracks_ext, vis_ext = projector.project_32_points( | |
| joint_pos, K_ext, E_ext, img_h=448, img_w=448 | |
| ) | |
| tracks_wrist, vis_wrist = projector.project_32_points( | |
| joint_pos, K_wrist, E_wrist, img_h=448, img_w=448 | |
| ) | |
| all_tracks_ext.append(tracks_ext) | |
| all_tracks_wrist.append(tracks_wrist) | |
| all_vis_ext.append(vis_ext) | |
| all_vis_wrist.append(vis_wrist) | |
| # Create visualizations for first, middle, and last frames | |
| viz_indices = [0, max_steps_per_episode//2, max_steps_per_episode-1] | |
| if step_idx in viz_indices: | |
| viz_ext = visualize_tracks( | |
| img_ext, | |
| tracks_ext, | |
| vis_ext, | |
| title=f"Episode {processed} | Frame {step_idx} | Exterior" | |
| ) | |
| viz_wrist = visualize_tracks( | |
| img_wrist, | |
| tracks_wrist, | |
| vis_wrist, | |
| title=f"Episode {processed} | Frame {step_idx} | Wrist" | |
| ) | |
| # Save visualizations | |
| cv2.imwrite( | |
| str(viz_path / f"ep{processed:03d}_frame{step_idx:04d}_exterior.jpg"), | |
| cv2.cvtColor(viz_ext, cv2.COLOR_RGB2BGR) | |
| ) | |
| cv2.imwrite( | |
| str(viz_path / f"ep{processed:03d}_frame{step_idx:04d}_wrist.jpg"), | |
| cv2.cvtColor(viz_wrist, cv2.COLOR_RGB2BGR) | |
| ) | |
| if decode_failed: | |
| skipped += 1 | |
| skipped_reasons['decode_error'] += 1 | |
| continue | |
| # Skip if too few steps | |
| if step_count < 10: | |
| skipped += 1 | |
| skipped_reasons['other'] += 1 | |
| continue | |
| # Convert to arrays | |
| tracks_ext = np.array(all_tracks_ext) | |
| tracks_wrist = np.array(all_tracks_wrist) | |
| vis_ext = np.array(all_vis_ext) | |
| vis_wrist = np.array(all_vis_wrist) | |
| images_ext = np.array(all_images_ext) | |
| images_wrist = np.array(all_images_wrist) | |
| # Get language instruction from first stored step | |
| language = "unknown" # Default if not available | |
| # Save NPZ | |
| npz_file = npz_path / f"episode_{processed:03d}.npz" | |
| np.savez_compressed( | |
| npz_file, | |
| tracks_exterior=tracks_ext, | |
| tracks_wrist=tracks_wrist, | |
| vis_exterior=vis_ext, | |
| vis_wrist=vis_wrist, | |
| images_exterior=images_ext, | |
| images_wrist=images_wrist, | |
| language=language, | |
| uuid=uuid, | |
| num_steps=step_count | |
| ) | |
| processed += 1 | |
| pbar.update(1) | |
| except Exception as e: | |
| print(f"\nError processing episode {episode_idx}: {e}") | |
| skipped += 1 | |
| skipped_reasons['other'] += 1 | |
| continue | |
| pbar.close() | |
| # Print summary | |
| print("\n" + "=" * 80) | |
| print("Test Preprocessing Complete") | |
| print("=" * 80) | |
| print(f" Processed: {processed} episodes") | |
| print(f" Skipped: {skipped} episodes") | |
| print(f" No calibration: {skipped_reasons['no_calib']}") | |
| print(f" Decode error: {skipped_reasons['decode_error']}") | |
| print(f" Other: {skipped_reasons['other']}") | |
| print() | |
| print(f" NPZ files: {npz_path}") | |
| print(f" Visualizations: {viz_path}") | |
| print(f" ({processed * 6} images generated)") | |
| print("=" * 80) | |
| # Create montage of first episode visualizations | |
| if processed > 0: | |
| print("\nCreating summary montage...") | |
| montage_images = [] | |
| # Look for existing visualization files for first episode | |
| viz_files = sorted(viz_path.glob("ep000_frame*_exterior.jpg")) | |
| for ext_file in viz_files[:3]: # Take up to 3 frames | |
| wrist_file = ext_file.parent / ext_file.name.replace('_exterior.jpg', '_wrist.jpg') | |
| if ext_file.exists() and wrist_file.exists(): | |
| img_ext = cv2.imread(str(ext_file)) | |
| img_wrist = cv2.imread(str(wrist_file)) | |
| if img_ext is not None and img_wrist is not None: | |
| montage_images.append(np.hstack([img_ext, img_wrist])) | |
| if montage_images: | |
| montage = np.vstack(montage_images) | |
| montage_file = viz_path / "summary_montage.jpg" | |
| cv2.imwrite(str(montage_file), montage) | |
| print(f" ✓ Saved summary montage: {montage_file}") | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| description="Test DROID preprocessing with visualizations" | |
| ) | |
| parser.add_argument( | |
| '--droid-path', | |
| type=str, | |
| default='/mnt/kevin/data/droid/droid/1.0.0', | |
| help='Path to DROID RLDS dataset' | |
| ) | |
| parser.add_argument( | |
| '--calib-dir', | |
| type=str, | |
| default='/root/workspace/code/wmrl/Dual-Dynamics-Models/DROID-main/vision/u/wenlongh/datasets/droid_v4/cameras', | |
| help='Path to camera calibration directory' | |
| ) | |
| parser.add_argument( | |
| '--output-dir', | |
| type=str, | |
| default='/tmp/droid_preprocessing_test', | |
| help='Output directory for test results' | |
| ) | |
| parser.add_argument( | |
| '--num-episodes', | |
| type=int, | |
| default=5, | |
| help='Number of episodes to process' | |
| ) | |
| parser.add_argument( | |
| '--use-cartesian', | |
| action='store_true', | |
| default=True, | |
| help='Use cartesian_position (default: True)' | |
| ) | |
| parser.add_argument( | |
| '--use-joints', | |
| dest='use_cartesian', | |
| action='store_false', | |
| help='Use joint_position with FK' | |
| ) | |
| parser.add_argument( | |
| '--require-refined', | |
| action='store_true', | |
| default=True, | |
| help='Require refined_extrinsics (default: True)' | |
| ) | |
| parser.add_argument( | |
| '--no-require-refined', | |
| dest='require_refined', | |
| action='store_false', | |
| help='Allow measured extrinsics' | |
| ) | |
| args = parser.parse_args() | |
| test_preprocessing( | |
| args.droid_path, | |
| args.calib_dir, | |
| args.output_dir, | |
| args.num_episodes, | |
| args.use_cartesian, | |
| args.require_refined | |
| ) | |
| if __name__ == "__main__": | |
| main() | |