openpi / droid /extract_depth_for_tracking.py
zhicao's picture
Upload folder using huggingface_hub
b584148 verified
Raw
History Blame Contribute Delete
16.5 kB
#!/usr/bin/env python3
"""
Extract depth maps from SVO files for depth-enhanced tracking
Organizes depth data to match the MP4 file structure
"""
import os
import sys
from pathlib import Path
import numpy as np
import json
from tqdm import tqdm
import argparse
import imageio
import cv2
# Add paths
sys.path.append(str(script_dir.parent))
sys.path.append(str(script_dir.parent / 'droid-repo'))
try:
import pyzed.sl as sl
print("✓ pyzed imported successfully")
except ImportError as e:
print(f"✗ Failed to import pyzed: {e}")
print("\nPlease ensure:")
print("1. conda activate DROID2")
print("2. export LD_LIBRARY_PATH=/usr/local/zed/lib:$LD_LIBRARY_PATH")
print("3. export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6")
sys.exit(1)
class DepthExtractorForTracking:
"""Extract and organize depth maps for tracking pipeline"""
def __init__(self, data_dir: Path, output_dir: Path = None):
self.data_dir = Path(data_dir)
if output_dir is None:
self.output_dir = self.data_dir / 'depth_maps'
else:
self.output_dir = Path(output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
# Find metadata
metadata_files = list(self.data_dir.glob('metadata_*.json'))
if not metadata_files:
raise FileNotFoundError(f"No metadata file found in {data_dir}")
self.metadata_path = metadata_files[0]
with open(self.metadata_path, 'r') as f:
self.metadata = json.load(f)
print(f"Initialized depth extractor")
print(f" Data dir: {self.data_dir}")
print(f" Output dir: {self.output_dir}")
print(f" Metadata: {self.metadata_path.name}")
def extract_depth_from_svo(self, svo_path: Path, camera_serial: str,
frequency: int = 1, max_frames: int = None,
skip_if_exists: bool = True) -> bool:
"""Extract depth maps from a single SVO file
Args:
svo_path: Path to SVO file
camera_serial: Camera serial number (for output organization)
frequency: Extract every N frames (1 = all frames)
max_frames: Maximum frames to extract (None = all)
skip_if_exists: Skip extraction if depth maps already exist
Returns:
Success status
"""
if not svo_path.exists():
print(f"✗ SVO file not found: {svo_path}")
return False
# Create output directory for this camera
camera_depth_dir = self.output_dir / camera_serial
# Check if depth maps already exist
if skip_if_exists and camera_depth_dir.exists():
existing_depth_files = list(camera_depth_dir.glob('depth_*.npy'))
if existing_depth_files:
# Check if we have depth info file
depth_info_path = camera_depth_dir / 'depth_info.json'
if depth_info_path.exists():
with open(depth_info_path, 'r') as f:
depth_info = json.load(f)
print(f"✓ Depth maps already exist for {camera_serial}:")
print(f" Found {len(existing_depth_files)} depth files")
print(f" Extracted frames: {depth_info.get('extracted_frames', 'unknown')}")
print(f" Frequency: {depth_info.get('frequency', 'unknown')}")
print(f" Skipping extraction (use --force to override)")
return True
camera_depth_dir.mkdir(exist_ok=True)
# Initialize ZED
init_params = sl.InitParameters()
init_params.set_from_svo_file(str(svo_path))
init_params.svo_real_time_mode = False
init_params.depth_mode = sl.DEPTH_MODE.ULTRA
init_params.coordinate_units = sl.UNIT.MILLIMETER # Use millimeters like DROID
init_params.depth_minimum_distance = 300 # 300mm (30cm) minimum
init_params.depth_maximum_distance = 20000 # 20000mm (20m) maximum
zed = sl.Camera()
err = zed.open(init_params)
if err != sl.ERROR_CODE.SUCCESS:
print(f"✗ Failed to open SVO: {err}")
zed.close()
return False
# Get camera info
cam_info = zed.get_camera_information()
resolution = cam_info.camera_configuration.resolution
fps = cam_info.camera_configuration.fps
total_frames = zed.get_svo_number_of_frames()
print(f"\nProcessing {camera_serial}:")
print(f" Resolution: {resolution.width}x{resolution.height}")
print(f" FPS: {fps}")
print(f" Total frames: {total_frames}")
# Prepare containers
depth_mat = sl.Mat()
runtime_params = sl.RuntimeParameters()
runtime_params.enable_fill_mode = True # Fill holes in depth
# Process frames
frame_count = 0
extracted_count = 0
if max_frames:
total_frames = min(total_frames, max_frames)
pbar = tqdm(total=total_frames, desc=f"Extracting depth for {camera_serial}")
# Store depth statistics
depth_stats = {
'min_depths': [],
'max_depths': [],
'mean_depths': []
}
# Process frames - we need to grab one extra time to reach the last frame
# because grab() moves to the next frame before we can retrieve the current one
frames_to_process = total_frames
while frame_count < frames_to_process:
err = zed.grab(runtime_params)
if err == sl.ERROR_CODE.SUCCESS:
# Check if we should extract this frame
if frame_count % frequency == 0:
# Get depth
zed.retrieve_measure(depth_mat, sl.MEASURE.DEPTH)
depth_np = depth_mat.get_data()
# Clean invalid values
depth_np[np.isnan(depth_np)] = 0
depth_np[np.isinf(depth_np)] = 0
# Save as NPY (float32 in millimeters)
depth_path = camera_depth_dir / f'depth_{frame_count:06d}.npy'
np.save(depth_path, depth_np.astype(np.float32))
# Collect statistics (excluding invalid pixels)
valid_mask = depth_np > 0
if np.any(valid_mask):
depth_stats['min_depths'].append(float(depth_np[valid_mask].min()))
depth_stats['max_depths'].append(float(depth_np[valid_mask].max()))
depth_stats['mean_depths'].append(float(depth_np[valid_mask].mean()))
extracted_count += 1
frame_count += 1
pbar.update(1)
else:
# Check if this is the last frame and we haven't processed it yet
if frame_count == frames_to_process - 1 and (frame_count % frequency == 0):
# Try to retrieve the last frame's depth even though grab failed
zed.retrieve_measure(depth_mat, sl.MEASURE.DEPTH)
depth_np = depth_mat.get_data()
if depth_np is not None and depth_np.size > 0:
# Clean invalid values
depth_np[np.isnan(depth_np)] = 0
depth_np[np.isinf(depth_np)] = 0
# Save as NPY (float32 in millimeters)
depth_path = camera_depth_dir / f'depth_{frame_count:06d}.npy'
np.save(depth_path, depth_np.astype(np.float32))
# Collect statistics
valid_mask = depth_np > 0
if np.any(valid_mask):
depth_stats['min_depths'].append(float(depth_np[valid_mask].min()))
depth_stats['max_depths'].append(float(depth_np[valid_mask].max()))
depth_stats['mean_depths'].append(float(depth_np[valid_mask].mean()))
extracted_count += 1
frame_count += 1
pbar.update(1)
break
pbar.close()
zed.close()
# Save depth statistics
if depth_stats['min_depths']:
stats_summary = {
'camera_serial': camera_serial,
'total_frames': total_frames,
'extracted_frames': extracted_count,
'frequency': frequency,
'resolution': {'width': resolution.width, 'height': resolution.height},
'fps': fps,
'depth_range': {
'global_min': float(np.min(depth_stats['min_depths'])),
'global_max': float(np.max(depth_stats['max_depths'])),
'global_mean': float(np.mean(depth_stats['mean_depths']))
}
}
with open(camera_depth_dir / 'depth_info.json', 'w') as f:
json.dump(stats_summary, f, indent=2)
print(f"✓ Extracted {extracted_count} depth maps")
print(f" Depth range: [{stats_summary['depth_range']['global_min']:.0f}, "
f"{stats_summary['depth_range']['global_max']:.0f}] mm")
return True
def identify_camera_type(self, camera_serial: str) -> str:
"""Identify if camera is wrist or exterior based on metadata"""
if camera_serial == self.metadata.get('wrist_cam_serial'):
return 'wrist'
elif camera_serial == self.metadata.get('ext1_cam_serial'):
return 'exterior_1'
elif camera_serial == self.metadata.get('ext2_cam_serial'):
return 'exterior_2'
else:
return 'unknown'
def process_all_cameras(self, frequency: int = 1, max_frames: int = None,
skip_if_exists: bool = True):
"""Process all SVO files in the episode"""
svo_dir = self.data_dir / 'recordings' / 'SVO'
if not svo_dir.exists():
print(f"✗ SVO directory not found: {svo_dir}")
return
svo_files = list(svo_dir.glob('*.svo'))
print(f"Found {len(svo_files)} SVO files")
# Process each SVO file
results = {}
for svo_path in svo_files:
camera_serial = svo_path.stem
camera_type = self.identify_camera_type(camera_serial)
if camera_type == 'unknown':
print(f"⚠️ Unknown camera serial: {camera_serial}, skipping")
continue
print(f"\n{'='*60}")
print(f"Processing {camera_type} camera: {camera_serial}")
print(f"{'='*60}")
success = self.extract_depth_from_svo(
svo_path, camera_serial, frequency, max_frames, skip_if_exists
)
results[camera_type] = {
'serial': camera_serial,
'success': success,
'svo_path': str(svo_path),
'depth_dir': str(self.output_dir / camera_serial)
}
# Save processing summary
summary = {
'episode_id': self.metadata.get('uuid', 'unknown'),
'timestamp': self.metadata.get('timestamp', 'unknown'),
'depth_extraction': results,
'frequency': frequency,
'max_frames': max_frames
}
with open(self.output_dir / 'extraction_summary.json', 'w') as f:
json.dump(summary, f, indent=2)
print(f"\n{'='*60}")
print("Depth extraction complete!")
print(f"Results saved to: {self.output_dir}")
# Show summary
for cam_type, result in results.items():
status = "✓" if result['success'] else "✗"
print(f" {status} {cam_type}: {result['serial']}")
def create_depth_visualization(self, camera_serial: str, frame_idx: int = 0):
"""Create a visualization of a single depth frame"""
depth_dir = self.output_dir / camera_serial
depth_path = depth_dir / f'depth_{frame_idx:06d}.npy'
if not depth_path.exists():
print(f"Depth file not found: {depth_path}")
return
# Load depth
depth = np.load(depth_path)
# Create visualization
valid_mask = depth > 0
if np.any(valid_mask):
# Normalize to 0-255 for visualization
depth_vis = depth.copy()
depth_vis[~valid_mask] = 0
# Clip to reasonable range (0-5000mm = 0-5m)
depth_vis = np.clip(depth_vis, 0, 5000)
depth_norm = (depth_vis / 5000 * 255).astype(np.uint8)
# Apply colormap
depth_colored = cv2.applyColorMap(depth_norm, cv2.COLORMAP_TURBO)
# Save visualization
vis_path = depth_dir / f'depth_vis_{frame_idx:06d}.jpg'
cv2.imwrite(str(vis_path), depth_colored)
print(f"Saved visualization to: {vis_path}")
# Also load and show corresponding RGB if available
mp4_dir = self.data_dir / 'recordings' / 'MP4'
mp4_path = mp4_dir / f'{camera_serial}.mp4'
if mp4_path.exists():
cap = cv2.VideoCapture(str(mp4_path))
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
ret, rgb_frame = cap.read()
cap.release()
if ret:
# Create side-by-side visualization
combined = np.hstack([rgb_frame, depth_colored])
combined_path = depth_dir / f'combined_vis_{frame_idx:06d}.jpg'
cv2.imwrite(str(combined_path), combined)
print(f"Saved combined visualization to: {combined_path}")
def main():
parser = argparse.ArgumentParser(description='Extract depth maps for tracking')
parser.add_argument('--data-dir', type=str, required=True,
help='Path to raw DROID episode directory')
parser.add_argument('--output-dir', type=str, default=None,
help='Output directory for depth maps (default: data_dir/depth_maps)')
parser.add_argument('--frequency', type=int, default=1,
help='Extract every N frames (default: 1 = all frames)')
parser.add_argument('--max-frames', type=int, default=None,
help='Maximum frames to extract per camera (default: all)')
parser.add_argument('--visualize', action='store_true',
help='Create visualization for first frame of each camera')
parser.add_argument('--force', action='store_true',
help='Force re-extraction even if depth maps exist')
args = parser.parse_args()
# Check environment
if 'DROID2' not in os.environ.get('CONDA_DEFAULT_ENV', ''):
print("⚠️ Not in DROID2 environment")
print("Run: conda activate DROID2")
# Create extractor
extractor = DepthExtractorForTracking(
Path(args.data_dir),
Path(args.output_dir) if args.output_dir else None
)
# Process all cameras
extractor.process_all_cameras(
args.frequency,
args.max_frames,
skip_if_exists=not args.force
)
# Create visualizations if requested
if args.visualize:
print("\nCreating visualizations...")
summary_path = extractor.output_dir / 'extraction_summary.json'
if summary_path.exists():
with open(summary_path, 'r') as f:
summary = json.load(f)
for cam_type, result in summary['depth_extraction'].items():
if result['success']:
extractor.create_depth_visualization(result['serial'], frame_idx=0)
if __name__ == '__main__':
main()