""" Test the Y-axis scaling fix by comparing old vs new scaling. """ import sys from pathlib import Path sys.path.append(str(Path(__file__).parent.parent)) import numpy as np import tensorflow as tf tf.config.set_visible_devices([], 'GPU') import tensorflow_datasets as tfds import datetime import re from utils.load_camera_calibration import CameraCalibrationLoader def find_closest_calibration(episode, uuid_list): 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_time = datetime.datetime.strptime( f"{date} {match_time.group(1)}:{match_time.group(2)}:{match_time.group(3)}", "%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: return None def project_manual(point_3d, K, E, img_h, img_w, original_h): """Manual projection with specified original height.""" # Transform to camera frame point_3d_hom = np.append(point_3d, 1.0) point_cam = (E @ point_3d_hom)[:3] # Project to image plane point_2d_hom = K @ point_cam point_2d = point_2d_hom[:2] / point_2d_hom[2] # Scale to target resolution original_w = 640 scale_x = img_w / original_w scale_y = img_h / original_h point_2d[0] *= scale_x point_2d[1] *= scale_y return point_2d, point_cam[2] > 0 def main(): print("=" * 80) print("Testing Y-axis scaling fix") print("=" * 80) # Load data calib_dir = '/root/workspace/code/wmrl/Dual-Dynamics-Models/DROID-main/vision/u/wenlongh/datasets/droid_v4/cameras' calib_loader = CameraCalibrationLoader(calib_dir) calib_path = Path(calib_dir) uuid_list = [f.stem.replace('_cameras', '') for f in sorted(calib_path.glob("*_cameras.json"))] droid_path = '/mnt/kevin/data/droid/droid/1.0.0' builder = tfds.builder_from_directory(droid_path) dataset = builder.as_dataset(split='train') # Find episode for episode_idx, episode in enumerate(dataset): uuid = find_closest_calibration(episode, uuid_list) if uuid and calib_loader.has_refined_extrinsics(uuid): break print(f"\nUsing episode {episode_idx}, UUID: {uuid}") # Get calibration calib = calib_loader.load_calibration(uuid) serials = [k for k in calib.keys() if k not in ['uuid', 'scene_path', 'optimization_summary']] K = np.array(calib[serials[0]]['measured_intrinsics']) E = np.array(calib[serials[0]]['refined_extrinsics']) # Get first frame step0 = next(iter(episode['steps'])) img = step0['observation']['exterior_image_1_left'].numpy() img_h, img_w = img.shape[:2] action = step0['action'].numpy() point_3d = action[:3] print(f"\nImage size: {img_w}x{img_h}") print(f"Test point (action xyz): {point_3d}") # Test OLD scaling (640x480) proj_2d_old, vis_old = project_manual(point_3d, K, E, img_h, img_w, original_h=480) print(f"\nOLD scaling (640x480):") print(f" scale_y = {img_h} / 480 = {img_h/480:.4f}") print(f" Projected 2D: [{proj_2d_old[0]:.2f}, {proj_2d_old[1]:.2f}]") # Test NEW scaling (640x360) proj_2d_new, vis_new = project_manual(point_3d, K, E, img_h, img_w, original_h=360) print(f"\nNEW scaling (640x360):") print(f" scale_y = {img_h} / 360 = {img_h/360:.4f}") print(f" Projected 2D: [{proj_2d_new[0]:.2f}, {proj_2d_new[1]:.2f}]") # Show difference diff = proj_2d_new - proj_2d_old print(f"\nDifference (NEW - OLD):") print(f" ΔX: {diff[0]:+.2f} pixels") print(f" ΔY: {diff[1]:+.2f} pixels") print(f"\nY scaling ratio: {(img_h/360) / (img_h/480):.4f} = 1.333x") print(f"Expected ΔY: {proj_2d_old[1] * (1.333 - 1):.2f} pixels") # Now test with the actual library function print("\n" + "=" * 80) print("Testing with FrankaMeshProjector:") print("=" * 80) from utils.franka_mesh_projection import FrankaMeshProjector projector = FrankaMeshProjector(use_gui=False) proj_2d_lib, vis_lib = projector._project_3d_to_2d( point_3d.reshape(1, 3), K, E, img_h=img_h, img_w=img_w ) print(f"Library projection: [{proj_2d_lib[0,0]:.2f}, {proj_2d_lib[0,1]:.2f}]") print(f"NEW manual: [{proj_2d_new[0]:.2f}, {proj_2d_new[1]:.2f}]") print(f"Match: {np.allclose(proj_2d_lib[0], proj_2d_new, atol=0.1)}") if np.allclose(proj_2d_lib[0], proj_2d_new, atol=0.1): print("\n✓ Fix is ACTIVE - library uses 640x360 scaling") elif np.allclose(proj_2d_lib[0], proj_2d_old, atol=0.1): print("\n✗ Fix is NOT ACTIVE - library still uses 640x480 scaling") else: print("\n⚠ Neither matches - something else is going on") if __name__ == "__main__": main()