openpi / droid /droid_tracker_with_depth.py
zhicao's picture
Upload folder using huggingface_hub
b584148 verified
Raw
History Blame Contribute Delete
17.2 kB
#!/usr/bin/env python3
"""
DROID Tracker with Depth Information
Uses the original motion-based tracking but adds depth information to the results
"""
import os
os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import numpy as np
import torch
import h5py
from pathlib import Path
from tqdm import tqdm
import json
import sys
import gc
import cv2
from typing import Dict, Optional, Tuple
from datetime import datetime
# Import the original tracker
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from droid_raw_mp4_tracker import RawDROIDTracker, clear_gpu_memory
class TrackerWithDepth(RawDROIDTracker):
"""
Minimal extension of RawDROIDTracker that adds depth information
Uses exact same tracking method, just adds depth data to results
"""
def __init__(self, **kwargs):
"""Initialize tracker - all parameters same as RawDROIDTracker"""
super().__init__(**kwargs)
print(" Depth data: Will be added if available (tracking unchanged)")
def load_depth_for_tracks(self, depth_dir: Path, camera_serial: str,
tracks: np.ndarray,
scale_factors: Optional[Tuple[float, float]] = None,
frame_skip_multiplier: int = 1) -> Optional[np.ndarray]:
"""Load depth values at tracked point locations
Args:
depth_dir: Directory containing depth maps
camera_serial: Camera serial number
tracks: Tracked points of shape (B, T, N, 2)
scale_factors: Scale factors if tracks are at different resolution
frame_skip_multiplier: Multiplier for frame indices (2 for 60->30fps)
Returns:
Track depths of shape (B, T, N) or None if not found
"""
camera_depth_dir = depth_dir / camera_serial
if not camera_depth_dir.exists():
print(f" ⚠️ No depth data found for camera {camera_serial}")
return None
# Load depth info
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" Found depth data: {depth_info['extracted_frames']} frames")
print(f" Depth range: [{depth_info['depth_range']['global_min']:.0f}, "
f"{depth_info['depth_range']['global_max']:.0f}] mm")
B, T, N, _ = tracks.shape
track_depths = np.zeros((B, T, N))
missing_frames = 0
# Debug info
print(f" Loading depth for {T} frames, {N} points")
if scale_factors:
print(f" Scale factors: {scale_factors}")
print(f" save_at_downsample_res: {self.save_at_downsample_res}")
for t in range(T):
# Map from downsampled frame index to actual video frame
actual_frame = t * frame_skip_multiplier
depth_path = camera_depth_dir / f'depth_{actual_frame:06d}.npy'
if depth_path.exists():
depth_map = np.load(depth_path)
# Downsample depth map if tracks are at downsampled resolution
if scale_factors is not None and self.save_at_downsample_res:
# Tracks are saved at downsampled resolution, need to downsample depth to match
h, w = depth_map.shape
new_h = int(h * scale_factors[1])
new_w = int(w * scale_factors[0])
depth_map = cv2.resize(depth_map, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
if t == 0:
print(f" Downsampled depth from {h}x{w} to {new_h}x{new_w}")
# Debug: print depth map shape for first frame
if t == 0:
print(f" Working depth map shape: {depth_map.shape}")
# Extract depth at each track location
for n in range(N):
x, y = tracks[0, t, n] # Now at same resolution as depth_map
# Convert to integer indices
x_int = int(np.clip(x, 0, depth_map.shape[1] - 1))
y_int = int(np.clip(y, 0, depth_map.shape[0] - 1))
# Extract depth value
track_depths[0, t, n] = depth_map[y_int, x_int]
else:
missing_frames += 1
if missing_frames > 0:
print(f" ⚠️ Missing {missing_frames} depth frames")
if frame_skip_multiplier > 1:
print(f" (Note: Looking for every {frame_skip_multiplier} frames due to 60->30fps conversion)")
return track_depths
def process_single_video_with_optional_depth(self, video_path: Path, camera_type: str,
camera_serial: str, depth_dir: Optional[Path],
max_points_per_frame: int = 200) -> Optional[Dict]:
"""Process video using original tracking, add depth if available"""
# Run original tracking
result = self.process_single_video(video_path, camera_type, max_points_per_frame)
if result is None:
return None
# Try to add depth information
if depth_dir and depth_dir.exists():
print(f" Adding depth information from: {depth_dir}")
# Get scale factors
scale_factors = result.get('scale_factors', None)
# Determine frame skip multiplier
# If we downsampled 60fps to 30fps, we need to skip every other depth frame
fps = result.get('fps', 30.0)
effective_fps = result.get('effective_fps', fps)
frame_skip_multiplier = 2 if (fps >= 59 and effective_fps <= 31) else 1
if frame_skip_multiplier > 1:
print(f" Detected 60->30fps downsampling, will load every {frame_skip_multiplier} depth frames")
# Load depth at track locations
track_depths = self.load_depth_for_tracks(
depth_dir, camera_serial, result['tracks'], scale_factors, frame_skip_multiplier
)
if track_depths is not None:
result['track_depths'] = track_depths
result['has_depth'] = True
# Also get depth at initial query points
query_depths = []
for point in result['query_points']:
frame_idx = int(point[0])
x, y = point[1], point[2]
# Map to actual frame number
actual_frame = frame_idx * frame_skip_multiplier
depth_path = depth_dir / camera_serial / f'depth_{actual_frame:06d}.npy'
if depth_path.exists():
depth_map = np.load(depth_path)
# Downsample depth map if needed
if scale_factors is not None and self.save_at_downsample_res:
# Query points are saved at downsampled resolution, need to downsample depth to match
h, w = depth_map.shape
new_h = int(h * scale_factors[1])
new_w = int(w * scale_factors[0])
depth_map = cv2.resize(depth_map, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
x_int = int(np.clip(x, 0, depth_map.shape[1] - 1))
y_int = int(np.clip(y, 0, depth_map.shape[0] - 1))
query_depths.append(depth_map[y_int, x_int])
else:
query_depths.append(0.0)
result['query_depths'] = np.array(query_depths)
else:
result['has_depth'] = False
result['track_depths'] = np.zeros((result['tracks'].shape[0],
result['tracks'].shape[1],
result['tracks'].shape[2]))
result['query_depths'] = np.zeros(len(result['query_points']))
else:
result['has_depth'] = False
result['track_depths'] = np.zeros((result['tracks'].shape[0],
result['tracks'].shape[1],
result['tracks'].shape[2]))
result['query_depths'] = np.zeros(len(result['query_points']))
return result
def process_with_optional_depth(data_dir: Path,
output_dir: Path = None,
depth_dir: Path = None,
max_points_per_frame: int = 200,
**tracker_kwargs):
"""Process episode using original tracking method, adding depth if available"""
if output_dir is None:
output_dir = data_dir / 'tracked_results_with_depth'
output_dir.mkdir(parents=True, exist_ok=True)
if depth_dir is None:
depth_dir = data_dir / 'depth_maps'
# Check if depth maps exist
has_depth = depth_dir.exists()
if has_depth:
print(f"✓ Depth directory found: {depth_dir}")
else:
print(f"⚠️ No depth directory found at {depth_dir}")
print(" Tracking will proceed without depth information")
# Find metadata file
metadata_files = list(data_dir.glob('metadata_*.json'))
if not metadata_files:
print("No metadata file found!")
return
metadata_path = metadata_files[0]
print(f"Using metadata: {metadata_path}")
# Initialize tracker (uses all original parameters)
tracker = TrackerWithDepth(**tracker_kwargs)
# Load metadata
metadata = tracker.load_metadata(metadata_path)
# Find MP4 files
mp4_dir = data_dir / 'recordings' / 'MP4'
mp4_files = [f for f in mp4_dir.glob('*.mp4') if not f.name.endswith('-stereo.mp4')]
print(f"Found {len(mp4_files)} mono MP4 files")
print("Using original motion-based tracking method")
# Process each video
results_by_camera = {}
for mp4_file in mp4_files:
camera_serial = mp4_file.stem
camera_type = tracker.identify_camera_type(camera_serial, metadata)
if camera_type == 'unknown':
print(f"Unknown camera serial: {camera_serial}, skipping")
continue
try:
result = tracker.process_single_video_with_optional_depth(
mp4_file,
camera_type,
camera_serial,
depth_dir if has_depth else None,
max_points_per_frame=max_points_per_frame
)
if result is not None:
results_by_camera[camera_type] = result
# Force cleanup
gc.collect()
clear_gpu_memory()
except Exception as e:
print(f"Error processing {mp4_file}: {e}")
import traceback
traceback.print_exc()
continue
# Save results
if results_by_camera:
timestamp = metadata['timestamp']
output_path = output_dir / f'tracked_with_depth_{timestamp}.hdf5'
save_results_with_depth(output_path, results_by_camera, metadata)
print(f"\nResults saved to {output_path}")
return output_path
return None
def save_results_with_depth(output_path: Path, results_by_camera: Dict, metadata: Dict):
"""Save tracking results including optional depth information"""
with h5py.File(output_path, 'w') as f:
# Metadata
meta_group = f.create_group('metadata')
meta_group.attrs['tracker'] = 'TrackerWithDepth'
meta_group.attrs['tracking_mode'] = 'original_motion_with_optional_depth'
meta_group.attrs['creation_time'] = datetime.now().isoformat()
meta_group.attrs['episode_uuid'] = metadata['uuid']
# Results by camera
views_group = f.create_group('views')
for camera_type, result in results_by_camera.items():
view_group = views_group.create_group(camera_type)
# Metadata
view_group.attrs['width'] = result['width']
view_group.attrs['height'] = result['height']
view_group.attrs['original_width'] = result['original_width']
view_group.attrs['original_height'] = result['original_height']
view_group.attrs['frame_count'] = result['frame_count']
view_group.attrs['num_points_tracked'] = result['tracks'].shape[2]
view_group.attrs['camera_type'] = result['camera_type']
view_group.attrs['video_path'] = result['video_path']
view_group.attrs['original_fps'] = result['fps']
view_group.attrs['effective_fps'] = result['effective_fps']
view_group.attrs['has_depth'] = result['has_depth']
# Data
compression_opts = {'compression': 'gzip', 'compression_opts': 4}
# Save tracks and visibility
view_group.create_dataset('tracks', data=result['tracks'], **compression_opts)
view_group.create_dataset('visibility', data=result['visibility'], **compression_opts)
view_group.create_dataset('query_points', data=result['query_points'], **compression_opts)
# Save depth information (will be zeros if no depth available)
view_group.create_dataset('track_depths', data=result['track_depths'], **compression_opts)
view_group.create_dataset('query_depths', data=result['query_depths'], **compression_opts)
# Also save normalized coordinates for compatibility
tracks_norm = result['tracks'].copy()
tracks_norm[:, :, :, 0] = tracks_norm[:, :, :, 0] / result['width']
tracks_norm[:, :, :, 1] = tracks_norm[:, :, :, 1] / result['height']
view_group.create_dataset('tracks_normalized', data=tracks_norm, **compression_opts)
print(f" {camera_type}: {result['tracks'].shape[2]} points tracked "
f"({'with' if result['has_depth'] else 'without'} depth)")
def main():
"""Main entry point"""
import argparse
parser = argparse.ArgumentParser(description='DROID Tracker with Optional Depth')
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 tracking results')
parser.add_argument('--depth-dir', type=str, default=None,
help='Directory containing depth maps (default: data-dir/depth_maps)')
# All original tracking parameters
parser.add_argument('--motion-threshold', type=float, default=0.15)
parser.add_argument('--motion-threshold-exterior', type=float, default=None)
parser.add_argument('--grid-stride', type=int, default=6)
parser.add_argument('--target-height', type=int, default=128)
parser.add_argument('--tracking-batch-size', type=int, default=500)
parser.add_argument('--max-points-per-frame', type=int, default=200)
parser.add_argument('--use-online-model', action='store_true')
parser.add_argument('--frame-skip', type=int, default=0)
parser.add_argument('--target-points', type=int, default=None)
parser.add_argument('--noise-scale', type=float, default=5.0)
parser.add_argument('--disable-downsizing', action='store_true')
parser.add_argument('--save-at-downsample-res', action='store_true')
parser.add_argument('--auto-downsample-60fps', action='store_true')
args = parser.parse_args()
# Process episode
process_with_optional_depth(
data_dir=Path(args.data_dir),
output_dir=Path(args.output_dir) if args.output_dir else None,
depth_dir=Path(args.depth_dir) if args.depth_dir else None,
motion_threshold=args.motion_threshold,
motion_threshold_exterior=args.motion_threshold_exterior,
grid_stride=args.grid_stride,
tracking_batch_size=args.tracking_batch_size,
target_height=args.target_height,
enable_downsizing=not args.disable_downsizing,
max_points_per_frame=args.max_points_per_frame,
target_points=args.target_points,
noise_scale=args.noise_scale,
use_online_model=args.use_online_model,
frame_skip=args.frame_skip,
save_at_downsample_res=args.save_at_downsample_res,
auto_downsample_60fps=args.auto_downsample_60fps
)
if __name__ == '__main__':
main()