File size: 10,194 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 | """
Debug what cartesian_position represents in DROID data.
Compare:
1. cartesian_position from observation
2. FK from joint_position using different links (wrist, flange, gripper)
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
import os
import numpy as np
# Import torch first
import torch
import mediapy as media
# Import TensorFlow and configure for CPU
import tensorflow as tf
tf.config.set_visible_devices([], 'GPU')
import tensorflow_datasets as tfds
import cv2
import datetime
import re
import pybullet as p
from utils.load_camera_calibration import CameraCalibrationLoader
from utils.franka_mesh_projection import FrankaMeshProjector
def load_cotracker():
"""Load CoTracker v3 model."""
from cotracker.predictor import CoTrackerPredictor
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = CoTrackerPredictor(checkpoint='/mnt/kevin/vlm_models/cotracker/scaled_offline.pth')
model = model.to(device)
model.eval()
return model, device
def find_closest_calibration(episode, uuid_list):
"""Find closest calibration by timestamp."""
try:
recording_path = episode['episode_metadata']['recording_folderpath'].numpy().decode('utf-8')
match = re.search(r'/([A-Z]+)/success/(\d{4}-\d{2}-\d{2})/\w+_\w+_+\d+_(\d{2}):(\d{2}):(\d{2})_\d{4}/', recording_path)
if not match:
return None
lab, date, hour, minute, second = match.groups()
episode_time = datetime.datetime.strptime(f"{date} {hour}:{minute}:{second}", "%Y-%m-%d %H:%M:%S")
matching_calibs = [uuid for uuid in uuid_list if uuid.startswith(f"{lab}+") and f"+{date}-" in uuid]
if len(matching_calibs) == 0:
return None
best_uuid = None
min_time_diff = float('inf')
for calib_uuid in matching_calibs:
parts = calib_uuid.split('+')
if len(parts) >= 3:
time_str = parts[2].replace('_cameras', '')
match_time = re.search(r'(\d{2})h-(\d{2})m-(\d{2})s', time_str)
if match_time:
calib_hour = int(match_time.group(1))
calib_min = int(match_time.group(2))
calib_sec = int(match_time.group(3))
calib_time = datetime.datetime.strptime(
f"{date} {calib_hour}:{calib_min}:{calib_sec}",
"%Y-%m-%d %H:%M:%S"
)
time_diff = abs((episode_time - calib_time).total_seconds())
if time_diff < min_time_diff:
min_time_diff = time_diff
best_uuid = calib_uuid
return best_uuid
except Exception as e:
return None
def get_link_position_from_fk(projector, joint_positions, link_idx):
"""Get 3D position of a specific link using FK."""
# Set joint positions
for i in range(min(7, projector.num_joints)):
p.resetJointState(projector.robot_id, i, joint_positions[i])
# Get link state
link_state = p.getLinkState(projector.robot_id, link_idx)
link_pos = np.array(link_state[4]) # world position
return link_pos
def main():
output_dir = Path('/tmp/droid_debug_cartesian')
output_dir.mkdir(parents=True, exist_ok=True)
print("=" * 80)
print("Debugging cartesian_position vs FK")
print("=" * 80)
# Initialize
calib_dir = '/root/workspace/code/wmrl/Dual-Dynamics-Models/DROID-main/vision/u/wenlongh/datasets/droid_v4/cameras'
calib_loader = CameraCalibrationLoader(calib_dir)
projector = FrankaMeshProjector(use_gui=False)
cotracker, device = load_cotracker()
# Get UUID list
calib_path = Path(calib_dir)
calib_files = sorted(calib_path.glob("*_cameras.json"))
uuid_list = [f.stem.replace('_cameras', '') for f in calib_files]
# Load dataset
droid_path = '/mnt/kevin/data/droid/droid/1.0.0'
print("Loading DROID dataset...")
builder = tfds.builder_from_directory(droid_path)
dataset = builder.as_dataset(split='train')
# Find first valid episode
episode_found = None
uuid_found = None
for episode_idx, episode in enumerate(dataset):
uuid = find_closest_calibration(episode, uuid_list)
if uuid is None:
continue
if not calib_loader.has_refined_extrinsics(uuid):
continue
episode_found = episode
uuid_found = uuid
print(f"\nUsing episode {episode_idx}, UUID: {uuid}")
break
if episode_found is None:
print("No valid episode found!")
return
# Get calibration
calib = calib_loader.load_calibration(uuid_found)
available_serials = [k for k in calib.keys() if k not in ['uuid', 'scene_path', 'optimization_summary']]
camera_serial = available_serials[0] # exterior
cam_data = calib[camera_serial]
K = np.array(cam_data['measured_intrinsics'])
E = np.array(cam_data['refined_extrinsics'])
# Collect frames
frames = []
cart_positions = []
joint_positions_list = []
max_frames = 16
for step_idx, step in enumerate(episode_found['steps']):
if step_idx >= max_frames:
break
cart_pos = step['observation']['cartesian_position'].numpy()
joint_pos = step['observation']['joint_position'].numpy()
img = step['observation']['exterior_image_1_left'].numpy()
cart_positions.append(cart_pos)
joint_positions_list.append(joint_pos)
frames.append(img)
img_h, img_w = frames[0].shape[:2]
# Compare cartesian_position vs FK for different links
print("\n" + "=" * 80)
print("Comparing cartesian_position vs FK positions")
print("=" * 80)
cart_pos_0 = cart_positions[0]
joint_pos_0 = joint_positions_list[0]
print(f"\ncartesian_position: {cart_pos_0[:3]}")
print(f"joint_position: {joint_pos_0}")
# Test different links
link_names = {
5: "Link 5 (wrist)",
7: "Link 7 (flange)",
8: "Link 8 (panda_hand)",
9: "Link 9 (panda_leftfinger)",
10: "Link 10 (panda_rightfinger)",
}
fk_positions = {}
for link_idx, link_name in link_names.items():
fk_pos = get_link_position_from_fk(projector, joint_pos_0, link_idx)
fk_positions[link_idx] = fk_pos
diff = np.linalg.norm(fk_pos - cart_pos_0[:3])
print(f"\n{link_name:25s}: {fk_pos}")
print(f" Distance from cartesian_position: {diff:.4f}")
# Find closest link
closest_link = min(fk_positions.items(), key=lambda x: np.linalg.norm(x[1] - cart_pos_0[:3]))
print(f"\nClosest match: {link_names[closest_link[0]]}")
# Now visualize tracking each link
print("\n" + "=" * 80)
print("Generating visualization videos")
print("=" * 80)
for link_idx, link_name in link_names.items():
print(f"\nProcessing {link_name}...")
# Project this link for all frames
all_projections = []
for frame_idx, joint_pos in enumerate(joint_positions_list):
link_pos = get_link_position_from_fk(projector, joint_pos, link_idx)
link_pos_reshaped = link_pos.reshape(1, 3)
proj_2d, proj_vis = projector._project_3d_to_2d(link_pos_reshaped, K, E, img_h=img_h, img_w=img_w)
all_projections.append((proj_2d[0], proj_vis[0]))
# Get initial projection for CoTracker
init_2d, init_vis = all_projections[0]
if not init_vis:
print(f" Skipping {link_name} - not visible")
continue
# Run CoTracker
video_np = np.array(frames)
video_np = video_np.transpose(0, 3, 1, 2)
video_tensor = torch.from_numpy(video_np).float() / 255.0
video_tensor = video_tensor.unsqueeze(0).to(device)
queries = np.zeros((1, 3))
queries[0, 0] = 0
queries[0, 1] = init_2d[0]
queries[0, 2] = init_2d[1]
queries_tensor = torch.from_numpy(queries).float().unsqueeze(0).to(device)
with torch.no_grad():
pred_tracks, pred_visibility = cotracker(
video_tensor,
queries=queries_tensor,
backward_tracking=False
)
tracks = pred_tracks[0].cpu().numpy()
visibility = pred_visibility[0].cpu().numpy()
# Visualize
video_frames = []
for frame_idx, frame in enumerate(frames):
viz = frame.copy()
# Draw GT projection for this frame (blue)
gt_2d, gt_vis = all_projections[frame_idx]
if gt_vis:
gt_pt = tuple(gt_2d.astype(int))
cv2.circle(viz, gt_pt, 5, (255, 0, 0), 2) # Blue circle
# Draw tracked point (green)
if visibility[frame_idx, 0]:
track_pt = tuple(tracks[frame_idx, 0].astype(int))
cv2.circle(viz, track_pt, 3, (0, 255, 0), -1) # Green filled
# Draw trajectory
if frame_idx > 0:
for t in range(max(0, frame_idx-10), frame_idx):
if visibility[t, 0] and visibility[t+1, 0]:
pt1 = tuple(tracks[t, 0].astype(int))
pt2 = tuple(tracks[t+1, 0].astype(int))
cv2.line(viz, pt1, pt2, (0, 255, 0), 1)
# Add text
cv2.putText(viz, link_name, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
cv2.putText(viz, f"Frame {frame_idx}/{len(frames)}", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
cv2.putText(viz, f"Blue=GT, Green=Tracked", (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 0), 1)
video_frames.append(viz)
# Save video
video_name = f"{link_name.replace(' ', '_').replace('(', '').replace(')', '')}.mp4"
video_path = output_dir / video_name
media.write_video(str(video_path), video_frames, fps=10)
print(f" Saved: {video_path}")
print("\n" + "=" * 80)
print(f"Complete! Videos saved to: {output_dir}")
print("=" * 80)
if __name__ == "__main__":
main()
|