File size: 12,634 Bytes
b584148 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 | """
Validation Script for Cartesian-Based Mesh Projection
Tests and compares:
1. FK-based projection (joint_position → PyBullet FK → mesh points)
2. Cartesian-based projection (cartesian_position → direct transform → mesh points)
Outputs visualization showing both methods side-by-side.
"""
import numpy as np
import tensorflow_datasets as tfds
from pathlib import Path
import argparse
import cv2
import sys
# 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_comparison(img: np.ndarray,
points_fk: np.ndarray,
points_cart: np.ndarray,
vis_fk: np.ndarray,
vis_cart: np.ndarray,
title: str = "") -> np.ndarray:
"""
Create side-by-side comparison of FK vs Cartesian projections.
Args:
img: Base image (H, W, 3)
points_fk: Points from FK method (32, 2)
points_cart: Points from Cartesian method (32, 2)
vis_fk: Visibility mask from FK (32,)
vis_cart: Visibility mask from Cartesian (32,)
title: Title for visualization
Returns:
Combined visualization image
"""
# Create two copies of the image
img_fk = img.copy()
img_cart = img.copy()
# Draw FK points (blue for grid, green for mesh)
for i in range(32):
if vis_fk[i]:
pt = tuple(points_fk[i].astype(int))
color = (0, 0, 255) if i < 25 else (0, 255, 0) # Blue grid, green mesh
cv2.circle(img_fk, pt, 3, color, -1)
cv2.putText(img_fk, str(i), (pt[0]+5, pt[1]-5),
cv2.FONT_HERSHEY_SIMPLEX, 0.3, color, 1)
# Draw Cartesian points (blue for grid, red for mesh)
for i in range(32):
if vis_cart[i]:
pt = tuple(points_cart[i].astype(int))
color = (0, 0, 255) if i < 25 else (255, 0, 0) # Blue grid, red mesh
cv2.circle(img_cart, pt, 3, color, -1)
cv2.putText(img_cart, str(i), (pt[0]+5, pt[1]-5),
cv2.FONT_HERSHEY_SIMPLEX, 0.3, color, 1)
# Add labels
cv2.putText(img_fk, "FK (Joint → PyBullet)", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
cv2.putText(img_cart, "Cartesian (Direct Transform)", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
# Compute difference for mesh points (last 7)
mesh_diff = np.linalg.norm(points_fk[25:] - points_cart[25:], axis=1)
avg_diff = np.mean(mesh_diff)
max_diff = np.max(mesh_diff)
cv2.putText(img_cart, f"Avg diff: {avg_diff:.1f}px", (10, 60),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2)
cv2.putText(img_cart, f"Max diff: {max_diff:.1f}px", (10, 90),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2)
# Combine side-by-side
combined = np.hstack([img_fk, img_cart])
# Add title
if title:
title_bar = np.zeros((50, combined.shape[1], 3), dtype=np.uint8)
cv2.putText(title_bar, title, (10, 35),
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2)
combined = np.vstack([title_bar, combined])
return combined
def validate_episode(droid_path: str,
calib_dir: str,
episode_index: int = 0,
num_frames: int = 5,
output_dir: str = "/tmp/droid_validation"):
"""
Validate cartesian projection on a single DROID episode.
Args:
droid_path: Path to DROID RLDS dataset
calib_dir: Path to camera calibration directory
episode_index: Episode index to test
num_frames: Number of frames to visualize
output_dir: Directory for output images
"""
print(f"Loading DROID episode {episode_index}...")
# Load RLDS dataset
builder = tfds.builder_from_directory(droid_path)
dataset = builder.as_dataset(split='train')
# Initialize tools
calib_loader = CameraCalibrationLoader(calib_dir)
projector = FrankaMeshProjector(use_gui=False)
# Find episode
for idx, episode in enumerate(dataset):
if idx != episode_index:
continue
# Extract metadata
try:
recording_path = episode['episode_metadata']['recording_folderpath'].numpy().decode('utf-8')
print(f" Recording: {recording_path}")
except:
print(f" Warning: Could not extract recording path")
# Get steps
steps = list(episode['steps'])
print(f" Total steps: {len(steps)}")
# Try to extract UUID from episode metadata
uuid = None
try:
# DROID stores UUID in different possible fields
if 'uuid' in episode['episode_metadata']:
uuid = episode['episode_metadata']['uuid'].numpy().decode('utf-8')
print(f" UUID from metadata: {uuid}")
else:
# Try to find it from file_path or other fields
print(f" Warning: UUID not found in episode_metadata")
print(f" Available keys: {list(episode['episode_metadata'].keys())}")
# List all camera calibration files to find potential matches
from pathlib import Path
calib_path = Path(calib_dir)
calib_files = sorted(calib_path.glob("*_cameras.json"))
print(f" Found {len(calib_files)} calibration files")
if len(calib_files) > 0:
# Try first calibration file as test
uuid = calib_files[episode_index % len(calib_files)].stem.replace('_cameras', '')
print(f" Using test UUID: {uuid}")
else:
print(f"✗ No calibration files found")
return
except Exception as e:
print(f"✗ Error extracting UUID: {e}")
import traceback
traceback.print_exc()
return
if uuid is None:
print(f"✗ Could not determine UUID for episode")
return
try:
# Check if refined extrinsics available
has_refined = calib_loader.has_refined_extrinsics(uuid)
print(f" Refined extrinsics: {has_refined}")
# Load calibration (with fallback)
dual_params = calib_loader.get_dual_view_params(
uuid,
param_type='refined',
require_refined=False
)
if dual_params is None:
print(f"✗ No camera calibration available for UUID: {uuid}")
return
except Exception as e:
print(f"✗ Error loading calibration for {uuid}: {e}")
import traceback
traceback.print_exc()
return
# Create output directory
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
# Sample frames uniformly
sample_indices = np.linspace(0, len(steps)-1, num_frames, dtype=int)
print(f"\nProcessing {num_frames} frames...")
print("=" * 80)
for i, step_idx in enumerate(sample_indices):
step = steps[step_idx]
# Get robot states
joint_pos = step['observation']['joint_position'].numpy()
cart_pos = step['observation']['cartesian_position'].numpy()
print(f"\nFrame {step_idx} ({i+1}/{num_frames}):")
print(f" Joint position: {joint_pos}")
print(f" Cartesian position: {cart_pos}")
# Process exterior camera
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)
if img_ext is None:
print(f" ✗ Failed to decode exterior image")
continue
img_ext = cv2.resize(img_ext, (448, 448))
img_ext_rgb = cv2.cvtColor(img_ext, cv2.COLOR_BGR2RGB)
K_ext, E_ext = dual_params['exterior_1']
# FK-based projection
points_fk, vis_fk = projector.project_32_points(
joint_pos, K_ext, E_ext, img_h=448, img_w=448
)
# Cartesian-based projection (Euler XYZ - confirmed by rotation format test)
points_cart, vis_cart = projector.project_32_points_cartesian(
cart_pos, K_ext, E_ext, img_h=448, img_w=448, rotation_format='euler_xyz'
)
# Compute differences for mesh points (indices 25-31)
mesh_diff = np.linalg.norm(points_fk[25:] - points_cart[25:], axis=1)
print(f" Mesh point differences (FK vs Cartesian):")
for j, diff in enumerate(mesh_diff):
vis_str = "✓" if (vis_fk[25+j] and vis_cart[25+j]) else "✗"
print(f" Point {25+j}: {diff:6.2f}px {vis_str}")
print(f" Average: {np.mean(mesh_diff):.2f}px")
print(f" Maximum: {np.max(mesh_diff):.2f}px")
# Create visualization
viz = visualize_comparison(
img_ext_rgb,
points_fk,
points_cart,
vis_fk,
vis_cart,
title=f"Episode {episode_index} | Frame {step_idx} | Exterior Camera"
)
# Save
output_file = output_path / f"frame_{step_idx:04d}_exterior.jpg"
cv2.imwrite(str(output_file), cv2.cvtColor(viz, cv2.COLOR_RGB2BGR))
print(f" ✓ Saved: {output_file}")
# Process wrist camera
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_wrist is not None:
img_wrist = cv2.resize(img_wrist, (448, 448))
img_wrist_rgb = cv2.cvtColor(img_wrist, cv2.COLOR_BGR2RGB)
K_wrist, E_wrist = dual_params['wrist']
points_fk_w, vis_fk_w = projector.project_32_points(
joint_pos, K_wrist, E_wrist, img_h=448, img_w=448
)
points_cart_w, vis_cart_w = projector.project_32_points_cartesian(
cart_pos, K_wrist, E_wrist, img_h=448, img_w=448, rotation_format='auto'
)
viz_wrist = visualize_comparison(
img_wrist_rgb,
points_fk_w,
points_cart_w,
vis_fk_w,
vis_cart_w,
title=f"Episode {episode_index} | Frame {step_idx} | Wrist Camera"
)
output_file_wrist = output_path / f"frame_{step_idx:04d}_wrist.jpg"
cv2.imwrite(str(output_file_wrist), cv2.cvtColor(viz_wrist, cv2.COLOR_RGB2BGR))
print(f" ✓ Saved: {output_file_wrist}")
print(f"\n{'='*80}")
print(f"✓ Validation complete. Output saved to: {output_path}")
return
print(f"✗ Episode {episode_index} not found")
def main():
parser = argparse.ArgumentParser(
description="Validate cartesian-based mesh projection on DROID data"
)
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(
'--episode-index',
type=int,
default=0,
help='Episode index to validate'
)
parser.add_argument(
'--num-frames',
type=int,
default=5,
help='Number of frames to visualize'
)
parser.add_argument(
'--output-dir',
type=str,
default='/tmp/droid_validation',
help='Output directory for visualizations'
)
args = parser.parse_args()
print("=" * 80)
print("DROID Cartesian Projection Validation")
print("=" * 80)
print()
validate_episode(
args.droid_path,
args.calib_dir,
args.episode_index,
args.num_frames,
args.output_dir
)
if __name__ == "__main__":
main()
|