InternVLA-M1 icon indicating copy to clipboard operation
InternVLA-M1 copied to clipboard

Clarification on camera intrinsics/extrinsics used in the InternData-M1 dataset

Open godnpeter opened this issue 1 year ago • 34 comments

Hi there — thanks for releasing this excellent dataset and the accompanying work!

This is an issue already stated at the huggingface repo, but I'm just including it here also for extra visibility! https://huggingface.co/datasets/InternRobotics/InternData-M1/discussions/4

While exploring the data, I couldn’t find the camera calibration details (intrinsics and extrinsics) used during collection. I noticed that InternVLA-M1 references a “GenManip Simulation Platform: Simulation platform for generalizable pick-and-place based on Isaac Sim,” and I checked the repo at https://github.com/InternRobotics/GenManip where some camera parameters are defined for the simulation environment.

Could you clarify the following?

Are the camera parameters in the GenManip repo the same ones used to generate this dataset?

If not, could you share the camera extrinsic parameters used for data collection (and, if available, the corresponding intrinsics)?

Having these calibration details would greatly help with accurate reproduction and evaluation. Thanks in advance!

godnpeter avatar Nov 13 '25 03:11 godnpeter

Yes, the camera parameters we used are consistent with those defined in the configuration file 👉 fixed_camera_robotiq_s2r_3L_align_twoObs.yml in the GenManip repository.

Our camera setup is based on the Intel RealSense D435, and the corresponding calibration in simulation is derived from that model.

Regarding extrinsic parameters, different cameras have different reference frames:

  • camera1: Used mainly for data collection assistance and can be ignored for reconstruction.

  • realsense: Calibrated relative to the Franka robot (“forlan”) frame. The relative transform is specified under the position and orientation fields, where orientation is a quaternion in scalar-first order.

  • obs_camera and obs_camera2: Both are calibrated in the world coordinate frame (not relative to the robot). The base of the Franka arm (Link0) in this world frame has the following transform:

    Position:     [-0.41623, -0.00135, 0.99931]
    Orientation:  [1, 0, 0, 0]
    

It’s also worth noting that all coordinate frames follow the convention of X-axis pointing forward and Z-axis pointing upward.

Thanks for your interest, and please feel free to reach out with any further questions!

Axi404 avatar Nov 13 '25 05:11 Axi404

Yes, the camera parameters we used are consistent with those defined in the configuration file 👉 fixed_camera_robotiq_s2r_3L_align_twoObs.yml in the GenManip repository.

Our camera setup is based on the Intel RealSense D435, and the corresponding calibration in simulation is derived from that model.

Regarding extrinsic parameters, different cameras have different reference frames:

  • camera1: Used mainly for data collection assistance and can be ignored for reconstruction.
  • realsense: Calibrated relative to the Franka robot (“forlan”) frame. The relative transform is specified under the position and orientation fields, where orientation is a quaternion in scalar-first order.
  • obs_camera and obs_camera2: Both are calibrated in the world coordinate frame (not relative to the robot). The base of the Franka arm (Link0) in this world frame has the following transform:
    Position:     [-0.41623, -0.00135, 0.99931]
    Orientation:  [1, 0, 0, 0]
    

It’s also worth noting that all coordinate frames follow the convention of X-axis pointing forward and Z-axis pointing upward.

Thanks for your interest, and please feel free to reach out with any further questions!

Hey bro. I've got some follow-up questions. The recorded effector (position and orientation) in the dataset, - is that for the Franka eef or the gripper center? And is the effector the same coordinate system as the "Franka robot (forlan) frame"?

Vilonge avatar Nov 17 '25 12:11 Vilonge

Dear @Axi404

I also have a follow up question regarding the key "annotation.tcp_3d_trace", "annotation.base_view.tcp_2d_trace", and "annotation.base_view_2.tcp_2d_trace' .

Are these suppose to represent the full trajectory of which the arm is currently moving?

godnpeter avatar Nov 17 '25 13:11 godnpeter

Also, I've tried overlaying the tcp_2d_traces on the videos but they seem to result in strange coordinates. Can you give some guidelines in how to interpret these values?

Image

godnpeter avatar Nov 18 '25 07:11 godnpeter

Also, I've tried overlaying the tcp_2d_traces on the videos but they seem to result in strange coordinates. Can you give some guidelines in how to interpret these values?

Image

Same issue.

Vilonge avatar Nov 18 '25 07:11 Vilonge

@godnpeter @Vilonge Hi, we found that due to the project timeline, the current M1 version does not yet support TCP trace recording. We also noticed that there is a real demand for TCP data from the community.

To address this, we are preparing a post-processing script to help generate the TCP trace. This may involve several coordinate frame transformations. We expect to provide the solution within one week.

Axi404 avatar Nov 18 '25 09:11 Axi404

Dear @Axi404

Thank you for your work. Actually I've got as far as this for now!

However, as you can see in the image, I'm getting a slight mismatch of getting the gripper's exact center....

Could you please double check the yml file you've mentioned and robot's position information?

Something must be off but I'm not able to figure it out.

PS) I assumed that camera1 is the base_view and that camera2 is the base_view_2

Image Image

godnpeter avatar Nov 18 '25 09:11 godnpeter

I'll also share my current (faulty) code just in case there are others who are interested in this.

#!/usr/bin/env python3
"""
InternManip Trajectory Extraction Tool

This script processes InternManip episodes and extracts 2D trajectories from end effector positions.
It projects 3D effector positions onto 2D image coordinates using camera calibration,
and generates visualizations

Key Features:
- Extracts 3D and 2D trajectories from parquet files
- Transforms camera extrinsics from world frame to robot base frame
- Projects end effector positions to 2D using camera calibration
- Creates static visualizations and animated videos
- Exports trajectory data in JSON format

Usage:
    python generate_trajectory_internmanip.py [OPTIONS]

Examples:
    # Process first 5 episodes for debugging
    python generate_trajectory_internmanip.py --debug_n_episodes 5
    
    # Process all episodes in all chunks
    python generate_trajectory_internmanip.py
    
    # Process specific chunk and episode (e.g., chunk-000/episode_000000)
    python generate_trajectory_internmanip.py --chunk 0 --episode 0
    
    # Process all episodes in a specific chunk (e.g., all episodes in chunk-001)
    python generate_trajectory_internmanip.py --chunk 1
    
    # Process only base_view camera
    python generate_trajectory_internmanip.py --cameras base_view
    
    # Skip video generation for faster processing (only generate JSON and static images)
    python generate_trajectory_internmanip.py --skip_videos
    
    # Skip already processed episodes
    python generate_trajectory_internmanip.py --skip_existing
    
    # Custom data and video directories
    python generate_trajectory_internmanip.py --data_dir ./custom_data --video_dir ./custom_videos

Chunk and Episode Parameters:
    --chunk N     : Process only chunk N (e.g., --chunk 0 for chunk-000)
    --episode N   : Process only episode N (e.g., --episode 5 for episode_000005)
                    Must be used together with --chunk
    
    If neither is specified, all chunks and episodes are processed.
    Chunk and episode numbers are zero-indexed integers.

Output Structure:
    overlay_videos/chunk-000/episode_000000_base_view_overlay.mp4
    overlay_videos/chunk-000/episode_000000_base_view_2_overlay.mp4
    trajectory_data/chunk-000/episode_000000_base_view.json
    trajectory_data/chunk-000/episode_000000_base_view_2.json
"""

import os
import argparse
import json
import numpy as np
import pandas as pd
import pickle
import yaml
import imageio
from pathlib import Path
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from tqdm import tqdm
from scipy.spatial.transform import Rotation as R


def load_camera_config(config_file):
    """Load camera configuration from YAML file.
    
    Args:
        config_file: Path to YAML configuration file
        
    Returns:
        Dictionary containing camera configurations
    """
    with open(config_file, 'r') as f:
        config = yaml.safe_load(f)
    return config


def transform_world_to_robot_base(world_position, world_orientation_quat, robot_base_world_pos, robot_base_world_quat):
    """Transform camera extrinsics from world frame to robot base frame.
    
    Args:
        world_position: Camera position in world frame [x, y, z]
        world_orientation_quat: Camera orientation in world frame [w, x, y, z] (scalar-first)
        robot_base_world_pos: Robot base position in world frame [x, y, z]
        robot_base_world_quat: Robot base orientation in world frame [w, x, y, z] (scalar-first)
        
    Returns:
        Tuple of (position_in_base, orientation_in_base) where orientation is [roll, pitch, yaw]
    """
    # Convert quaternions to rotation matrices (scipy uses [x, y, z, w] format)
    world_orientation_quat_scipy = [world_orientation_quat[1], world_orientation_quat[2], 
                                     world_orientation_quat[3], world_orientation_quat[0]]
    robot_base_world_quat_scipy = [robot_base_world_quat[1], robot_base_world_quat[2], 
                                    robot_base_world_quat[3], robot_base_world_quat[0]]
    
    R_cam_world = R.from_quat(world_orientation_quat_scipy).as_matrix()
    R_base_world = R.from_quat(robot_base_world_quat_scipy).as_matrix()
    
    # Build homogeneous transformation matrices
    T_cam_world = np.eye(4)
    T_cam_world[:3, :3] = R_cam_world
    T_cam_world[:3, 3] = world_position
    
    T_base_world = np.eye(4)
    T_base_world[:3, :3] = R_base_world
    T_base_world[:3, 3] = robot_base_world_pos
    
    # Transform: T_cam_base = inv(T_base_world) @ T_cam_world
    T_world_base = np.linalg.inv(T_base_world)
    T_cam_base = T_world_base @ T_cam_world
    
    # Extract position and orientation
    position_in_base = T_cam_base[:3, 3]
    R_cam_base = T_cam_base[:3, :3]
    euler_angles = R.from_matrix(R_cam_base).as_euler('xyz', degrees=False)
    
    return position_in_base, euler_angles


def build_camera_matrices(camera_config, robot_base_world_pos, robot_base_world_quat):
    """Build camera intrinsics and extrinsics matrices.
    
    Args:
        camera_config: Camera configuration dictionary
        robot_base_world_pos: Robot base position in world frame
        robot_base_world_quat: Robot base orientation in world frame
        
    Returns:
        Tuple of (intrinsics_matrix, extrinsics_matrix)
        - intrinsics_matrix: 3x3 camera matrix
        - extrinsics_matrix: 4x4 camera-to-base transformation matrix
    """
    # Extract intrinsics from camera_params: [fx, fy, cx, cy, width, height]
    camera_params = camera_config.get('camera_params')
    if camera_params:
        fx, fy, cx, cy, width, height = camera_params
    else:
        # Fallback: estimate from resolution and aperture
        resolution = camera_config['resolution']
        width, height = resolution
        focal_length = camera_config['focal_length']
        h_aperture = camera_config['horizontal_aperture']
        v_aperture = camera_config['vertical_aperture']
        
        # Estimate focal length in pixels
        fx = (focal_length / h_aperture) * width
        fy = (focal_length / v_aperture) * height
        cx = width / 2
        cy = height / 2
    
    intrinsics_matrix = np.array([
        [fx, 0, cx],
        [0, fy, cy],
        [0, 0, 1]
    ])
    
    # Extract extrinsics (position and orientation in world frame)
    world_position = np.array(camera_config['position'])
    world_orientation_quat = np.array(camera_config['orientation'])  # [w, x, y, z] scalar-first
    
    # Transform to robot base frame
    position_in_base, euler_angles = transform_world_to_robot_base(
        world_position, world_orientation_quat, robot_base_world_pos, robot_base_world_quat
    )
    
    # Build extrinsics matrix (camera-to-base transformation)
    R_cam_base = R.from_euler('xyz', euler_angles).as_matrix()
    extrinsics_matrix = np.eye(4)
    extrinsics_matrix[:3, :3] = R_cam_base
    extrinsics_matrix[:3, 3] = position_in_base
    
    return intrinsics_matrix, extrinsics_matrix


def project_3d_to_2d(point_3d, cam_to_base_matrix, intrinsics_matrix):
    """Project a 3D point in robot base frame to 2D image coordinates.
    
    Isaac Sim / Omniverse coordinate convention:
    - ALL frames (world, robot, camera) use: X-forward, Y-left, Z-up
    - Camera also follows X-forward, Y-left, Z-up (NOT standard CV convention)
    - For projection: depth = X_cam, horizontal = -Y_cam, vertical = -Z_cam
    
    Args:
        point_3d: 3D point in robot base frame [x, y, z] (X-forward, Z-up)
        cam_to_base_matrix: 4x4 camera-to-base transformation matrix
        intrinsics_matrix: 3x3 camera intrinsics matrix
        
    Returns:
        Tuple of (u, v) - 2D pixel coordinates
    """
    # Convert to homogeneous coordinates
    point_3d_hom = np.array([point_3d[0], point_3d[1], point_3d[2], 1.0])
    
    # Transform from robot base to camera frame (both use X-forward, Y-left, Z-up)
    base_to_cam_matrix = np.linalg.inv(cam_to_base_matrix)
    point_cam = base_to_cam_matrix @ point_3d_hom
    
    X_cam, Y_cam, Z_cam = point_cam[:3]
    
    # Check if point is in front of camera (positive X = forward)
    if X_cam <= 0:
        return -1, -1  # Behind camera
    
    # Project using Isaac Sim convention:
    # - Depth: X_cam (forward direction)
    # - Horizontal (u): -Y_cam / X_cam (Y is left, so -Y gives right)
    # - Vertical (v): -Z_cam / X_cam (Z is up, so -Z gives down)
    # Then apply intrinsics: u = fx * horizontal + cx, v = fy * vertical + cy
    
    fx = intrinsics_matrix[0, 0]
    fy = intrinsics_matrix[1, 1]
    cx = intrinsics_matrix[0, 2]
    cy = intrinsics_matrix[1, 2]
    
    u = fx * (-Y_cam / X_cam) + cx
    v = fy * (-Z_cam / X_cam) + cy
    
    return u, v


def compute_gripper_center_positions(poses_with_orientation, gripper_offset=0.1628):
    """Compute gripper center positions from wrist positions.
    
    The poses represent the wrist position. This function adds an offset
    along the gripper's forward direction (Z-axis in EE frame) to get the center
    of the gripper fingers.
    
    Args:
        poses_with_orientation: Nx6 array of poses [x, y, z, roll, pitch, yaw]
        gripper_offset: Distance from wrist to gripper center in meters
                       (default: 0.1628m for Robotiq 2F-85)
        
    Returns:
        Nx6 array with adjusted positions (orientations remain the same)
    """
    adjusted_poses = poses_with_orientation.copy()
    
    for i in range(len(poses_with_orientation)):
        # Extract position and orientation
        position = poses_with_orientation[i, :3]
        roll, pitch, yaw = poses_with_orientation[i, 3:6]
        
        # Create rotation matrix from roll, pitch, yaw
        rot_matrix = R.from_euler("xyz", [roll, pitch, yaw]).as_matrix()
        
        # Define offset in gripper's local frame (along Z-axis)
        # The Z-axis points forward along the gripper
        local_offset = np.array([0, 0, gripper_offset])
        
        # Transform offset to base frame
        global_offset = rot_matrix @ local_offset
        
        # Add offset to wrist position
        adjusted_poses[i, :3] = position + global_offset
    
    return adjusted_poses


def try_unpickle(x):
    """Try to unpickle if possible; return decoded value."""
    if isinstance(x, (bytes, bytearray)):
        try:
            return pickle.loads(x)
        except Exception:
            return x
    return x


def load_episode_data(parquet_path):
    """Load episode data from parquet file.
    
    Args:
        parquet_path: Path to parquet file
        
    Returns:
        DataFrame containing episode data
    """
    return pd.read_parquet(parquet_path)


def extract_trajectories(data, cam_to_base_matrix, intrinsics_matrix, camera_config):
    """Extract 3D and 2D trajectories from episode data.
    
    This function computes gripper center positions (not wrist positions) using
    the Robotiq 2F-85 gripper offset of 0.1628m along the gripper's Z-axis.
    
    Args:
        data: DataFrame containing episode data
        cam_to_base_matrix: Camera-to-base transformation matrix
        intrinsics_matrix: Camera intrinsics matrix
        camera_config: Camera configuration dictionary
        
    Returns:
        Tuple of (trajectory_2d, trajectory_3d, euler_angles, gripper_states)
    """
    wrist_poses = []
    gripper_states = []
    
    for idx in range(len(data)):
        # Extract 3D position and orientation from states (wrist position)
        pos_raw = data['states.effector.position'].iloc[idx]
        ori_raw = data['states.effector.orientation'].iloc[idx]
        gripper_raw = data['states.gripper.position'].iloc[idx]
        
        pos = try_unpickle(pos_raw)
        ori = try_unpickle(ori_raw)
        gripper = try_unpickle(gripper_raw)
        
        # Combine position and orientation [x, y, z, roll, pitch, yaw]
        wrist_poses.append(np.concatenate([pos, ori]))
        
        # Gripper state (use mean of gripper positions as proxy for open/close)
        gripper_state = np.mean(np.abs(gripper))
        gripper_states.append(gripper_state)
    
    wrist_poses = np.array(wrist_poses)
    gripper_states = np.array(gripper_states)
    
    # Compute gripper center positions (adjust wrist positions)
    # Robotiq 2F-85 has 162.8mm offset from wrist flange to gripper center
    gripper_center_poses = compute_gripper_center_positions(wrist_poses, gripper_offset=0.1628)
    
    # Extract adjusted 3D positions and orientations
    trajectory_3d = gripper_center_poses[:, :3]  # [x, y, z] - now gripper center
    euler_angles = gripper_center_poses[:, 3:6]  # [roll, pitch, yaw] - unchanged
    
    # Project gripper center positions to 2D
    trajectory_2d = []
    for pos_3d in trajectory_3d:
        u, v = project_3d_to_2d(pos_3d, cam_to_base_matrix, intrinsics_matrix)
        trajectory_2d.append([u, v])
    
    return (np.array(trajectory_2d), trajectory_3d, euler_angles, gripper_states)


def detect_interaction_points(gripper_states, stability_window=3, threshold=0.001):
    """Detect gripper interaction points from gripper states.
    
    Args:
        gripper_states: Array of gripper states
        stability_window: Number of frames to check for stability
        threshold: Threshold for detecting changes
        
    Returns:
        Tuple of (grasp_points, release_points)
    """
    grasp_points = []
    release_points = []
    
    if len(gripper_states) < stability_window + 1:
        return grasp_points, release_points
    
    # Simple threshold-based detection
    # When gripper closes, value increases; when opens, value decreases
    for t in range(1, len(gripper_states)):
        delta = gripper_states[t] - gripper_states[t-1]
        
        # Detect significant changes
        if delta > threshold:
            grasp_points.append(t)
        elif delta < -threshold:
            release_points.append(t)
    
    return grasp_points, release_points


def load_images_from_video(video_path):
    """Load images from video file using imageio (supports AV1 and other codecs).
    
    Args:
        video_path: Path to video file (.mp4)
        
    Returns:
        List of images as numpy arrays (RGB format)
    """
    if not video_path.exists():
        raise FileNotFoundError(f"Video file not found: {video_path}")
    
    try:
        # Use imageio with ffmpeg backend for better codec support (including AV1)
        reader = imageio.get_reader(str(video_path), 'ffmpeg')
        images = []
        
        for frame in reader:
            # imageio already returns RGB format
            images.append(frame)
        
        reader.close()
        return images
    except Exception as e:
        print(f"    Error reading video with imageio: {e}")
        raise


def visualize_trajectory(images, traj_2d, task_instruction=None,
                        frame_idx=0, save_path=None):
    """Create a static visualization of the trajectory overlaid on an image frame.
    
    Args:
        images: List of image frames
        traj_2d: Nx2 array of 2D trajectory coordinates
        task_instruction: Optional task instruction text
        frame_idx: Frame index to display
        save_path: If provided, save image to this path
    """
    if frame_idx >= len(images):
        frame_idx = 0
    
    rgb = images[frame_idx]
    
    fig, ax = plt.subplots(figsize=(10, 6))
    ax.imshow(rgb)
    
    # Draw trajectory line
    ax.plot(traj_2d[:, 0], traj_2d[:, 1], '-', color='orange',
           linewidth=2, alpha=0.8, label='EE Trajectory')
    
    # Draw start/end markers
    ax.scatter(traj_2d[0, 0], traj_2d[0, 1], c='green', s=200, marker='D',
              edgecolors='black', linewidths=2, label='Start', zorder=11)
    ax.scatter(traj_2d[-1, 0], traj_2d[-1, 1], c='red', s=250, marker='*',
              edgecolors='black', linewidths=2, label='End', zorder=11)
    
    # Add task instruction as title
    if task_instruction:
        ax.set_title(task_instruction, fontsize=10, pad=10,
                    bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8))
    else:
        ax.set_title(f'Frame {frame_idx}/{len(images)-1}')
    
    ax.legend(loc='upper right', fontsize=8, framealpha=0.9)
    ax.axis('off')
    plt.tight_layout()
    
    if save_path:
        plt.savefig(save_path, dpi=150, bbox_inches='tight')
        print(f"  ✓ Saved to {save_path}")
        plt.close(fig)
    else:
        plt.show()


def create_video_with_trajectory(images, traj_2d, task_instruction, output_path):
    """Create an animated video with trajectory drawn progressively.
    
    Args:
        images: List of image frames
        traj_2d: Nx2 array of 2D trajectory coordinates
        task_instruction: Task instruction text
        output_path: Output path for video
        
    Returns:
        True if successful
    """
    is_mp4 = output_path.suffix == '.mp4'
    print(f"  Creating trajectory video ({'MP4' if is_mp4 else 'GIF'})...")
    
    fig, ax = plt.subplots(figsize=(8, 5))
    ax.axis('off')
    
    im = ax.imshow(images[0])
    
    # Initialize trajectory elements
    line, = ax.plot([], [], '-', color='orange', linewidth=2, alpha=0.8, label='Past')
    future_line, = ax.plot([], [], '--', color='gray', linewidth=1, alpha=0.3, label='Future')
    current_point, = ax.plot([], [], 'o', color='cyan', markersize=8, markeredgecolor='black',
                             markeredgewidth=2, label='Current', zorder=10)
    
    # Start/end markers
    start_point, = ax.plot([], [], 'D', color='green', markersize=10, markeredgecolor='black',
                          markeredgewidth=2, label='Start', zorder=11)
    end_point, = ax.plot([], [], '*', color='red', markersize=12, markeredgecolor='black',
                        markeredgewidth=2, label='End', zorder=11)
    
    title = ax.set_title(task_instruction if task_instruction else 'Frame 0', fontsize=9)
    ax.legend(loc='upper right', fontsize=7, framealpha=0.9)
    
    # Plot markers
    start_point.set_data([traj_2d[0, 0]], [traj_2d[0, 1]])
    end_point.set_data([traj_2d[-1, 0]], [traj_2d[-1, 1]])
    
    def update(frame):
        im.set_array(images[frame])
        
        if frame > 0:
            line.set_data(traj_2d[:frame+1, 0], traj_2d[:frame+1, 1])
        
        if frame < len(images) - 1:
            future_line.set_data(traj_2d[frame:, 0], traj_2d[frame:, 1])
        else:
            future_line.set_data([], [])
        
        current_point.set_data([traj_2d[frame, 0]], [traj_2d[frame, 1]])
        
        return [im, line, future_line, current_point, start_point, end_point, title]
    
    anim = animation.FuncAnimation(fig, update, frames=tqdm(range(len(images)), desc="  Rendering"),
                                   interval=33, blit=True)  # 33ms = ~30fps
    
    if is_mp4:
        # Use H.264 codec (libx264) - widely compatible, NOT AV1
        writer = animation.FFMpegWriter(fps=30, codec='libx264', bitrate=3000,
                                       extra_args=['-pix_fmt', 'yuv420p', '-preset', 'medium'])
    else:
        writer = animation.PillowWriter(fps=30, bitrate=1800)
    
    anim.save(output_path, writer=writer, dpi=100)
    plt.close(fig)
    print(f"  ✓ Saved to {output_path}")
    return True


def process_episode(parquet_path, config_file, camera_names, output_dir, 
                   video_base_dir, skip_existing=False, skip_videos=False):
    """Process a single episode and generate trajectory overlays.
    
    Args:
        parquet_path: Path to parquet file
        config_file: Path to camera configuration YAML
        camera_names: List of camera names to process
        output_dir: Output directory
        video_base_dir: Base directory containing video files
        skip_existing: Skip if output already exists
        skip_videos: Skip video generation
        
    Returns:
        True if successful
    """
    # Parse episode and chunk from filename
    # Expected format: data/chunk-000/episode_000000.parquet
    parquet_path = Path(parquet_path)
    episode_name = parquet_path.stem  # e.g., episode_000000
    chunk_name = parquet_path.parent.name  # e.g., chunk-000
    
    print(f"\n{'='*70}")
    print(f"Processing {chunk_name}/{episode_name}")
    print(f"{'='*70}")
    
    # Load data
    data = load_episode_data(parquet_path)
    print(f"  Loaded {len(data)} frames")
    
    # Load camera configuration
    camera_config = load_camera_config(config_file)
    
    # Robot base in world frame
    # https://github.com/InternRobotics/InternVLA-M1/issues/17
    robot_base_world_pos = np.array([-0.41623, -0.00135, 0.99931])
    robot_base_world_quat = np.array([1, 0, 0, 0])  # [w, x, y, z] scalar-first
    
    # Extract task instruction from annotations
    task_instruction = None
    if 'annotation.diverse_instructions' in data.columns:
        instr_raw = data['annotation.diverse_instructions'].iloc[0]
        instr = try_unpickle(instr_raw)
        if isinstance(instr, list) and len(instr) > 0:
            task_instruction = instr[0]
        elif isinstance(instr, str):
            task_instruction = instr
    
    # Camera name mapping: camera_short_name -> (config_name, video_subdir_name)
    camera_mapping = {
        'base_view': ('obs_camera', 'images.rgb.base_view'),
        'base_view_2': ('obs_camera_2', 'images.rgb.base_view_2')
    }
    
    # Process each camera
    for camera_short_name in camera_names:
        if camera_short_name not in camera_mapping:
            print(f"  ⚠️  Unknown camera: {camera_short_name}")
            continue
        
        camera_config_name, video_subdir = camera_mapping[camera_short_name]
        
        # Create output directory
        out_subdir = output_dir / chunk_name
        out_subdir.mkdir(parents=True, exist_ok=True)
        
        output_json = out_subdir / f"{episode_name}_{camera_short_name}.json"
        output_img = out_subdir / f"{episode_name}_{camera_short_name}_overlay.png"
        output_video = out_subdir / f"{episode_name}_{camera_short_name}_overlay.mp4"
        
        # Skip if exists
        if skip_existing and output_json.exists():
            print(f"  ⏭️  Skipping {camera_short_name} (already exists)")
            continue
        
        print(f"\n  Processing camera: {camera_short_name}")
        
        # Get camera configuration
        if camera_config_name not in camera_config:
            print(f"  ⚠️  Camera config not found: {camera_config_name}")
            continue
        
        cam_cfg = camera_config[camera_config_name]
        
        # Build camera matrices
        intrinsics_matrix, cam_to_base_matrix = build_camera_matrices(
            cam_cfg, robot_base_world_pos, robot_base_world_quat
        )
        
        print(f"    Intrinsics shape: {intrinsics_matrix.shape}")
        print(f"    Extrinsics shape: {cam_to_base_matrix.shape}")
        
        # Extract trajectories
        traj_2d, traj_3d, euler_angles, gripper_states = extract_trajectories(
            data, cam_to_base_matrix, intrinsics_matrix, cam_cfg
        )
        
        print(f"    Trajectory 2D shape: {traj_2d.shape}")
        print(f"    Trajectory 3D shape: {traj_3d.shape}")
        
        # Load images from video file
        video_path = video_base_dir / chunk_name / video_subdir / f"{episode_name}.mp4"
        print(f"    Loading images from video: {video_path}")
        
        if not video_path.exists():
            print(f"    ⚠️  Video file not found: {video_path}")
            continue
        
        try:
            images = load_images_from_video(video_path)
            print(f"    Loaded {len(images)} images")
        except Exception as e:
            print(f"    ⚠️  Error loading video: {e}")
            continue
        
        # Validate that images were loaded
        if len(images) == 0:
            print(f"    ⚠️  No images loaded from video (empty video file)")
            continue
        
        # Validate that trajectory and images have matching lengths
        if len(images) != len(traj_2d):
            print(f"    ⚠️  Mismatch: {len(images)} images but {len(traj_2d)} trajectory points")
            print(f"    Will use minimum length: {min(len(images), len(traj_2d))}")
            min_len = min(len(images), len(traj_2d))
            images = images[:min_len]
            traj_2d = traj_2d[:min_len]
            traj_3d = traj_3d[:min_len]
            euler_angles = euler_angles[:min_len]
            gripper_states = gripper_states[:min_len]
        
        # Get image dimensions
        img_height, img_width = images[0].shape[:2]
        
        # Normalize trajectories
        traj_2d_normalized = traj_2d / np.array([img_width, img_height])
        
        # Save trajectory data to JSON
        trajectory_data = {
            'episode_name': episode_name,
            'chunk_name': chunk_name,
            'camera': camera_short_name,
            'task_instruction': task_instruction,
            'num_timesteps': len(images),
            'image_dimensions': {'width': img_width, 'height': img_height},
            'gripper_tracking': {
                'position': 'gripper_center',
                'description': 'Tracks gripper center (not wrist position)',
                'gripper_model': 'Robotiq 2F-85',
                'offset_from_wrist_meters': 0.1628,
                'offset_direction': 'along gripper Z-axis (forward)',
            },
            'trajectory_3d_robot_base': traj_3d.tolist(),
            'trajectory_2d': traj_2d.tolist(),
            'trajectory_2d_normalized': traj_2d_normalized.tolist(),
            'euler_angles_robot_base': euler_angles.tolist(),
            'gripper_states': gripper_states.tolist(),
            'camera_intrinsics': intrinsics_matrix.tolist(),
            'camera_extrinsics': cam_to_base_matrix.tolist(),
        }
        
        with open(output_json, 'w') as f:
            json.dump(trajectory_data, f, indent=2)
        print(f"    ✓ Saved trajectory data to {output_json}")
        
        # Create static visualization
        visualize_trajectory(images, traj_2d, task_instruction,
                           frame_idx=0, save_path=output_img)
        
        # Create video (optional)
        if not skip_videos:
            create_video_with_trajectory(images, traj_2d, task_instruction, output_video)
        
        print(f"  ✅ Completed {camera_short_name}")
    
    return True


def parse_args():
    """Parse command-line arguments."""
    parser = argparse.ArgumentParser(
        description='Extract 2D trajectories from InternManip episodes',
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    
    parser.add_argument(
        '--data_dir',
        type=str,
        default='data',
        help='Data directory containing chunk folders with parquet files (default: data)'
    )
    
    parser.add_argument(
        '--video_dir',
        type=str,
        default='videos',
        help='Video directory containing chunk folders with video files (default: videos)'
    )
    
    parser.add_argument(
        '--config_file',
        type=str,
        default='fixed_camera_robotiq_s2r_3L_align_twoObs.yml',
        help='Camera configuration YAML file (default: fixed_camera_robotiq_s2r_3L_align_twoObs.yml)'
    )
    
    parser.add_argument(
        '--cameras',
        type=str,
        nargs='+',
        default=['base_view', 'base_view_2'],
        choices=['base_view', 'base_view_2'],
        help='Camera names to process (default: both cameras)'
    )
    
    parser.add_argument(
        '--chunk',
        type=int,
        default=None,
        help='Process only this specific chunk number (default: all chunks)'
    )
    
    parser.add_argument(
        '--episode',
        type=int,
        default=None,
        help='Process only this specific episode number (default: all episodes)'
    )
    
    parser.add_argument(
        '--skip_existing',
        action='store_true',
        help='Skip episodes that already have output files'
    )
    
    parser.add_argument(
        '--debug_n_episodes',
        type=int,
        default=None,
        help='Maximum number of episodes to process (for debugging)'
    )
    
    parser.add_argument(
        '--skip_videos',
        action='store_true',
        help='Skip video generation to speed up processing'
    )
    
    return parser.parse_args()


def main():
    """Main function to process episodes and extract trajectories."""
    args = parse_args()
    
    data_dir = Path(args.data_dir)
    video_dir = Path(args.video_dir)
    config_file = Path(args.config_file)
    cameras = args.cameras
    skip_existing = args.skip_existing
    skip_videos = args.skip_videos
    debug_n_episodes = args.debug_n_episodes
    
    print(f"📋 Data directory: {data_dir}")
    print(f"📋 Video directory: {video_dir}")
    print(f"📋 Config file: {config_file}")
    print(f"📋 Cameras: {', '.join(cameras)}")
    print(f"⏭️  Skip existing: {skip_existing}")
    print(f"🎬 Generate videos: {not skip_videos}")
    
    # Find all parquet files
    if args.chunk is not None and args.episode is not None:
        # Process specific episode
        chunk_str = f"chunk-{args.chunk:03d}"
        episode_str = f"episode_{args.episode:06d}"
        parquet_files = [data_dir / chunk_str / f"{episode_str}.parquet"]
    elif args.chunk is not None:
        # Process specific chunk
        chunk_str = f"chunk-{args.chunk:03d}"
        parquet_files = sorted((data_dir / chunk_str).glob("episode_*.parquet"))
    else:
        # Process all chunks
        parquet_files = sorted(data_dir.glob("chunk-*/episode_*.parquet"))
    
    if debug_n_episodes:
        parquet_files = parquet_files[:debug_n_episodes]
    
    print(f"\n🔍 Found {len(parquet_files)} episode(s) to process")
    
    # Setup output directories
    output_video_dir = Path("overlay_videos")
    output_data_dir = Path("trajectory_data")
    output_video_dir.mkdir(exist_ok=True)
    output_data_dir.mkdir(exist_ok=True)
    
    print(f"📁 Video output directory: {output_video_dir}")
    print(f"📁 Data output directory: {output_data_dir}")
    
    # Process episodes
    success_count = 0
    failure_count = 0
    
    for parquet_path in tqdm(parquet_files, desc="Processing episodes"):
        try:
            # Save to both directories
            process_episode(parquet_path, config_file, cameras, output_video_dir,
                          video_dir, skip_existing, skip_videos)
            process_episode(parquet_path, config_file, cameras, output_data_dir,
                          video_dir, skip_existing, skip_videos=True)  # Skip videos for data dir
            success_count += 1
        except Exception as e:
            print(f"\n❌ Error processing {parquet_path}: {e}")
            import traceback
            traceback.print_exc()
            failure_count += 1
            continue
    
    # Print final summary
    print("\n" + "="*70)
    print("🎉 PROCESSING COMPLETE")
    print("="*70)
    print(f"✅ Successful: {success_count}")
    print(f"❌ Failed: {failure_count}")
    print(f"📁 Output directories: {output_video_dir}, {output_data_dir}")
    print("="*70)


if __name__ == "__main__":
    main()


godnpeter avatar Nov 18 '25 09:11 godnpeter

Dear @Axi404 I do understand that preparing the code would take some time.

However, if its possible, I would be totally fine with a really rough draft of the preprocessing code. I hope to take care of this as fast as I can.

So if its okay, I would be extremely grateful if I could get a peek of how the trajectory generation code works via my email which is [email protected]

Thanks for your hard work and I'm really looking forward to hearing back from you!

godnpeter avatar Nov 18 '25 09:11 godnpeter

Dear @Axi404

Thank you for your work. Actually I've got as far as this for now!

However, as you can see in the image, I'm getting a slight mismatch of getting the gripper's exact center....

Could you please double check the yml file you've mentioned and robot's position information?

Something must be off but I'm not able to figure it out.

PS) I assumed that camera1 is the base_view and that camera2 is the base_view_2

Image Image

I am also working on this and have similarly encountered a slight misalignment in the visualization trace. Therefore, I raised the request for the URDF of the robotic arm used in the dataset on the HuggingFace Community.

Vilonge avatar Nov 18 '25 09:11 Vilonge

@Vilonge That's good to hear. I guess the camera or robot position parameters are a bit off.

As for the robotic arm, I think they are following Droid's as they are using rotobiq so that's why I set the gripper_offset as 0.1628 (=16.28cm). Do you have any thoughts?

godnpeter avatar Nov 18 '25 09:11 godnpeter

@Vilonge

I've taken the liberty and tried changing the robot position to the following and I think its a lot better. Could you also try the values below and see if they work for you?

    robot_base_world_pos = np.array([-0.41623, 0.035, 1.02])

Also I would really appreciate @Axi404 comment on these new parameters for the robot base!

https://github.com/user-attachments/assets/526a2f7f-0e03-462b-ab5f-4eb8ef6073c9

godnpeter avatar Nov 18 '25 10:11 godnpeter

Hi @godnpeter Thank you so much for your excellent work — it looks like you’ve already completed everything we needed!

Regarding the robot base placement, I believe a more accurate world position would be (-0.45768, -0.00135, 1.011). Additionally, Isaac Sim occasionally introduces a one-frame delay during step/render, so there may be a slight temporal offset. If you notice any misalignment in the TCP trace, please try applying a one-frame shift (e.g., tcp[t] = tcp[t-1] or tcp[t] = tcp[t+1]).

For trajectory generation, as described in our paper, we used our previous project GenManip. You can refer to the documentation at https://genmanip.com/. All relevant code and many assets are open-source, with more on the way. If you need help generating your own dataset, feel free to open an issue on the GenManip GitHub repository.

Thanks again for your great work!

Axi404 avatar Nov 18 '25 16:11 Axi404

Dear @Axi404

Thank you for your fast comments! I would close the issue since most problems have been solved and an official code is gonna come out in the near future!

godnpeter avatar Nov 19 '25 03:11 godnpeter

Dear @Axi404 , I'm sorry to inform you that it turns out the robot's world coordinate changes per episode.... so we actually have to have access to the robot's world position per episode...

It seems like that the robot's position changes slightly when initializing the episode...

Do you happen to have any additional info in resolving this issue?

Below is the visualization for episode 0 and 9. We can clearly see that. the robot's position is different or maybe the camera parameters differ...

Image Image

godnpeter avatar Nov 19 '25 05:11 godnpeter

@godnpeter Hi, we’re very sorry that we overlooked this detail. For the dataset, we will provide an updated version that includes the robot base information, but this requires re-uploading the data.

Unfortunately, we are not able to trace back the mapping from the GenManip data IDs to the LeRobot data IDs, so we have no choice but to re-upload the dataset. Please kindly wait a bit — we will include as much additional information as possible in the new version.

We sincerely apologize for the inconvenience caused.

Axi404 avatar Nov 19 '25 08:11 Axi404

Dear @Axi404 , I'm sorry to inform you that it turns out the robot's world coordinate changes per episode.... so we actually have to have access to the robot's world position per episode...

It seems like that the robot's position changes slightly when initializing the episode...

Do you happen to have any additional info in resolving this issue?

Below is the visualization for episode 0 and 9. We can clearly see that. the robot's position is different or maybe the camera parameters differ...

Image Image

Same issue. Since precise visual trace is critically important for me, do you have any idea for resolving this problem? Even hardcode?

Vilonge avatar Nov 19 '25 10:11 Vilonge

Dear @Axi404 , I'm sorry to inform you that it turns out the robot's world coordinate changes per episode.... so we actually have to have access to the robot's world position per episode...

It seems like that the robot's position changes slightly when initializing the episode...

Do you happen to have any additional info in resolving this issue?

Below is the visualization for episode 0 and 9. We can clearly see that. the robot's position is different or maybe the camera parameters differ...

Image Image

I observe that the projection of the gripper point onto the wrist camera is consistently accurate. This verifies that the inaccuracy in the projection offset is caused by the imprecise position of the robot base in the world coordinate, since the localization of the wrist camera does not rely on the transformation of the robot base position in the world coordinates.

Vilonge avatar Nov 19 '25 10:11 Vilonge

I observe that the projection of the gripper point onto the wrist camera is consistently accurate. This verifies that the inaccuracy in the projection offset is caused by the imprecise position of the robot base in the world coordinate, since the localization of the wrist camera does not rely on the transformation of the robot base position in the world coordinates.

Yes. In fact, we apply a 0.2x0.2 robot base position randomization to the Franka robot. Current LeRobot dataset does not record this information, it also does not record camera world pose.

If you can only use wrist camera view, current data is correct.

Axi404 avatar Nov 19 '25 13:11 Axi404

Dear @Axi404 , I'm sorry to inform you that it turns out the robot's world coordinate changes per episode.... so we actually have to have access to the robot's world position per episode... It seems like that the robot's position changes slightly when initializing the episode... Do you happen to have any additional info in resolving this issue? Below is the visualization for episode 0 and 9. We can clearly see that. the robot's position is different or maybe the camera parameters differ... Image Image

Same issue. Since precise visual trace is critically important for me, do you have any idea for resolving this problem? Even hardcode?

We hope to rush this update in one week, as fast as we can.

Axi404 avatar Nov 19 '25 13:11 Axi404