# C401 Lab: From a Recording to a LeRobot Dataset

> The hands-on lab of the C401 processing course: run the open Basalt visual-inertial system (or ORB-SLAM3 or OpenVINS) on a public TUM VI fisheye stereo sequence and score it, run it on your own head-worn recording in the EuRoC folder layout, then export frames and poses to a LeRobotDataset v3.0 and read it back. Every command is as the tools' documentation or source gives it, with licences stated.

Page: https://egocam.ai/university/c401/lab/

This lab takes one recording from images and IMU samples on a disk to a trajectory, and from a trajectory to a training dataset. Part A runs an open visual-inertial system on a public fisheye stereo sequence with ground truth, so you can see what a good run looks like. Part B runs the same system on your own head-worn recording. Part C exports frames and poses to LeRobotDataset v3.0 and reads them back.

The main path is [Basalt](https://gitlab.com/VladyslavUsenko/basalt), because it is permissively licensed, ships binaries, handles fisheye stereo with the double sphere model and reads a plain folder layout. ORB-SLAM3 and OpenVINS are given as alternatives. Every command below is copied from the tool's own documentation, or follows the documented form with your own file names; the source is linked at each step. Square brackets mark values you fill in.

Work through [Lessons 1 to 4](https://egocam.ai/university/c401/) first, and keep the [checklist](https://egocam.ai/university/c401/checklist/) next to you.

## Licences before you start

| Component | Licence | Source |
|---|---|---|
| Basalt | BSD 3-clause ("Note also the different licenses of thirdparty code") | [Basalt README](https://gitlab.com/VladyslavUsenko/basalt) |
| ORB-SLAM3 | GPL-3.0 | [UZ-SLAMLab/ORB_SLAM3](https://github.com/UZ-SLAMLab/ORB_SLAM3) |
| OpenVINS | GPL-3.0 | [rpng/open_vins](https://github.com/rpng/open_vins) |
| lerobot | Apache-2.0 | [huggingface/lerobot](https://github.com/huggingface/lerobot) |
| TUM VI data | CC BY 4.0; its source code BSD-2-Clause | [TUM VI dataset page](https://vision.in.tum.de/data/datasets/visual-inertial-dataset) |

GPL-3.0 is copyleft: if the pipeline will ship in a closed product, check its obligations before you build on ORB-SLAM3 or OpenVINS ([SLAM and VIO Systems Compared](https://egocam.ai/processing/slam-vio-systems-compared/#choosing-by-constraint)). None of the components in this lab is non-commercial, but the hand and body models you may add later often are ([Lesson 2](https://egocam.ai/university/c401/lesson-2-hands-and-body/#licences-check-the-model-and-the-code)).

## Part A: a public sequence with ground truth

TUM VI is a visual-inertial benchmark recorded with a handheld rig, not a head-worn one, with 195° fisheye stereo cameras and an IMU. Its page states that "the cameras and IMU sensors are time-synchronized in hardware". The `room` sequences are fully covered by motion capture ([VIO Benchmarks and Ground Truth](https://egocam.ai/processing/vio-benchmarks-and-ground-truth/#euroc-and-tum-vi-the-standard-odometry-references)), so the whole trajectory can be scored. This part uses `room1`.

### Step A1: Install Basalt

The [Basalt README](https://gitlab.com/VladyslavUsenko/basalt) gives a binary install for Ubuntu 22.04 and later (amd64):

```bash
curl -LsSf https://gitlab.com/VladyslavUsenko/basalt/-/raw/master/scripts/install.sh | sh
```

"The installer places binaries in `~/.local/bin`, libraries in `~/.local/lib`, and data files in `~/.local/etc/basalt`." ([README, raw](https://gitlab.com/VladyslavUsenko/basalt/-/raw/master/README.md)) The data files include the calibration and configuration for TUM VI. The README also gives a source build with CMake presets.

**You should see** `basalt_vio` on your path, and `tumvi_512_ds_calib.json` and `tumvi_512_config.json` under `~/.local/etc/basalt/`.

### Step A2: Download the sequence

Basalt's [VIO and mapping guide](https://gitlab.com/VladyslavUsenko/basalt/-/blob/master/doc/VioMapping.md) downloads `magistrale1` from TUM VI's EuRoC-format export. Use the same export with `room1`:

```bash
mkdir tumvi_data
cd tumvi_data
wget http://vision.in.tum.de/tumvi/exported/euroc/512_16/dataset-room1_512_16.tar
tar -xvf dataset-room1_512_16.tar
```

**You should see** a folder `dataset-room1_512_16/mav0/` with `cam0/`, `cam1/`, `imu0/` and a ground-truth folder. If the download URL has moved, the [TUM VI dataset page](https://vision.in.tum.de/data/datasets/visual-inertial-dataset) lists the current links.

### Step A3: Run the visual-inertial odometry

The guide's command, with the `room1` folder, the GUI off, and the two options that save results. `--save-trajectory` takes `tum`, `euroc` or `kitti`, and `--result-path` writes the RMS ATE against the dataset's ground truth ([`src/vio.cpp`](https://gitlab.com/VladyslavUsenko/basalt/-/blob/master/src/vio.cpp)):

```bash
basalt_vio --dataset-path dataset-room1_512_16/ \
  --cam-calib ~/.local/etc/basalt/tumvi_512_ds_calib.json \
  --dataset-type euroc \
  --config-path ~/.local/etc/basalt/tumvi_512_config.json \
  --marg-data tumvi_marg_data \
  --show-gui 0 \
  --save-trajectory euroc \
  --result-path room1_result.json
```

**You should see** `trajectory.csv` in the working folder, one line per pose in the form `#timestamp [ns],p_RS_R_x [m],p_RS_R_y [m],p_RS_R_z [m],q_RS_w [],q_RS_x [],q_RS_y [],q_RS_z []`, and `room1_result.json` with `rms_ate`, `num_frames` and `exec_time_ns`. In Basalt's code the saved pose is `T_w_i`: the IMU body in the world frame, not the camera.

**Checkpoint.** Run it again with `--show-gui 1` and press `align_se3`: the guide says it "aligns the GT trajectory with the current estimate using an SE(3) transformation and prints the transformation and the root-mean-squared absolute trajectory error (RMS ATE)" ([VioMapping.md, raw](https://gitlab.com/VladyslavUsenko/basalt/-/raw/master/doc/VioMapping.md)). Write the number down with the sequence and the system's version. Compare it only with numbers measured the same way ([Lesson 1](https://egocam.ai/university/c401/lesson-1-camera-poses/#scoring-a-trajectory)).

**If it fails:** a missing file error usually means the calibration or config path is wrong for your install; the guide notes its paths are for an installed package, and a source build keeps the files in the repository's `data` folder. The guide also warns: "It appears that only the datasets in ASL Dataset Format (`euroc` dataset type in our notation) contain ground truth that is time-aligned to the IMU and camera images." ([VioMapping.md, raw](https://gitlab.com/VladyslavUsenko/basalt/-/raw/master/doc/VioMapping.md)) Score against the EuRoC-format export, not a bag.

### Alternative A: ORB-SLAM3 (GPL-3.0)

Build it as the [ORB-SLAM3 README](https://github.com/UZ-SLAMLab/ORB_SLAM3) gives, after installing its dependencies (Pangolin, OpenCV, Eigen):

```bash
git clone https://github.com/UZ-SLAMLab/ORB_SLAM3.git ORB_SLAM3
cd ORB_SLAM3
chmod +x build.sh
./build.sh
```

`build.sh` also unpacks the vocabulary `Vocabulary/ORBvoc.txt`. The README's TUM VI section refers to a `tum_vi_examples` script that is not in the repository at commit `4452a3c`; the stereo-inertial example's own usage line is ([`stereo_inertial_tum_vi.cc`](https://github.com/UZ-SLAMLab/ORB_SLAM3/blob/master/Examples/Stereo-Inertial/stereo_inertial_tum_vi.cc)):

```text
Usage: ./stereo_inertial_tum_vi path_to_vocabulary path_to_settings path_to_image_folder_1 path_to_image_folder_2 path_to_times_file path_to_imu_data (trajectory_file_name)
```

The repository ships the settings, timestamps and IMU files for each TUM VI sequence, so for `room1`:

```bash
./Examples/Stereo-Inertial/stereo_inertial_tum_vi Vocabulary/ORBvoc.txt \
  Examples/Stereo-Inertial/TUM-VI.yaml \
  [DATA]/dataset-room1_512_16/mav0/cam0/data \
  [DATA]/dataset-room1_512_16/mav0/cam1/data \
  Examples/Stereo-Inertial/TUM_TimeStamps/dataset-room1_512.txt \
  Examples/Stereo-Inertial/TUM_IMU/dataset-room1_512.txt \
  room1
```

**You should see** `f_room1.txt` (all frames) and `kf_room1.txt` (keyframes). In the source, each line is a timestamp in nanoseconds, then `tx ty tz qx qy qz qw`; with an IMU the pose is the IMU body in the world, and only the largest map in the Atlas is saved ([`System.cc`](https://github.com/UZ-SLAMLab/ORB_SLAM3/blob/master/src/System.cc)). `TUM-VI.yaml` uses the `KannalaBrandt8` camera model and is not rectified, as the README describes for fisheye stereo.

### Alternative A: OpenVINS (GPL-3.0)

OpenVINS's documented path uses ROS. Its [installation guide](https://docs.openvins.com/gs-installing.html) covers ROS 1 and ROS 2, and its [tutorial](https://docs.openvins.com/gs-tutorial.html) runs a bag in ROS 1 with:

```bash
roscore # term 0
source devel/setup.bash # term 1
roslaunch ov_msckf subscribe.launch config:=euroc_mav
```

and plays the bag in another terminal. The repository ships a `tum_vi` configuration, and its `serial.launch` reads a bag directly and saves the estimate when `dosave` is set; its arguments are `config`, `dataset`, `bag`, `dosave` and `path_est` ([serial.launch](https://github.com/rpng/open_vins/blob/master/ov_msckf/launch/serial.launch)). OpenVINS takes its calibration as `kalibr_imucam_chain.yaml` and `kalibr_imu_chain.yaml`, which "should be the same as Kalibr's", so a Kalibr calibration from course C201 carries over. Score a run with its evaluation tool, as the [error evaluation page](https://docs.openvins.com/eval-error.html) shows:

```bash
rosrun ov_eval error_singlerun <align_mode> <file_gt.txt> <file_est.txt>
```

## Part B: your own head-worn recording

### Step B1: Put the recording in the EuRoC folder layout

Basalt's `euroc` reader expects, under your dataset folder ([`dataset_io_euroc.h`](https://gitlab.com/VladyslavUsenko/basalt/-/blob/master/include/basalt/io/dataset_io_euroc.h)):

- `mav0/cam0/data.csv`: one line per frame, a timestamp in nanoseconds, a comma, then the image file name;
- `mav0/cam0/data/` and `mav0/cam1/data/`: the images. The reader looks up the second camera's image **by the first camera's file name**, so the two cameras must share timestamps, which is what a hardware-synchronised pair gives;
- `mav0/imu0/data.csv`: one line per IMU sample, a timestamp in nanoseconds, then gyroscope x, y, z and accelerometer x, y, z, comma-separated;
- optionally, ground truth in `mav0/state_groundtruth_estimate0/`, `mav0/gt/` or `mav0/mocap0/`.

Lines starting with `#` are skipped. Write your converter from your recording container (MCAP, VRS, a camera's own files) into this layout, and keep the camera and IMU timestamps on the same clock ([Why Synchronisation Matters](https://egocam.ai/sync/why-sync-matters/)).

**Checkpoint:** the first and last timestamps of `cam0/data.csv` fall inside the IMU's time range, and every file name in `cam0/data.csv` exists in both `cam0/data/` and `cam1/data/`.

Why these two checks: visual-inertial tracking integrates the IMU between frames ([Why Synchronisation Matters](https://egocam.ai/sync/why-sync-matters/)), so a frame outside the IMU's time range has no inertial measurement to link it to its neighbours. And a stereo pair is only a stereo measurement if both images were taken at the same instant: in the field guide's example of a head turning at 100°/s, seen by a 1280-pixel camera with a 90° field of view, a 10 ms gap between the two exposures shifts the image by about 11 px, which goes straight into the stereo depth ([a turning head](https://egocam.ai/sync/why-sync-matters/#worked-example-a-turning-head)).

### Step B2: Calibration and configuration

`basalt_vio` needs a camera-IMU calibration in Basalt's JSON format and a configuration file. Basalt's [calibration guide](https://gitlab.com/VladyslavUsenko/basalt/-/blob/master/doc/Calibration.md) shows `basalt_calibrate` (cameras, with `--cam-types ds ds` for double sphere) and `basalt_calibrate_imu` (camera plus IMU) on public calibration recordings. The IMU noise values in its commands belong to those datasets' sensors: use your own, measured as course C202 teaches ([C202 Lesson 2: measuring IMU noise](https://egocam.ai/university/c202/lesson-2-measuring-imu-noise/); [IMU Calibration](https://egocam.ai/calibration/imu-calibration/)). The estimator uses those values to decide how much to trust the IMU against the cameras; values that are too small make it "trust your IMU measurements too much", as Kalibr's [IMU noise model](https://github.com/ethz-asl/kalibr/wiki/IMU-Noise-Model) warns. Start the configuration from the shipped TUM VI file and change one setting at a time.

### Step B3: Run and look

Run the same command as step A3 with your folder and files. Without ground truth, `--result-path` has nothing to score against; use the checks the field guide gives for the field ([Lesson 1](https://egocam.ai/university/c401/lesson-1-camera-poses/#scoring-a-trajectory)):

- **Marker revisit.** Start and end the recording at the same marked spot; the distance between the first and last pose is the end-of-session drift.
- **Hard moments.** Note where the run struggles: fast head turns, hands filling the view, the first seconds. These are the failure modes in [Running SLAM on Wearable Footage](https://egocam.ai/processing/slam-on-wearable-footage/#why-head-worn-footage-breaks-standard-slam).

## Part C: export to LeRobotDataset v3.0 and read it back

This part writes one episode: the left camera's frames and the IMU body pose from Basalt's `trajectory.csv`. It stores no action, because human capture has no robot action; building actions from hands and poses is course C402 ([Lesson 4](https://egocam.ai/university/c401/lesson-4-training-formats/#human-data-as-states-and-actions)).

### Step C1: Install lerobot

From the [installation guide](https://huggingface.co/docs/lerobot/installation), in a Python 3.12 environment:

```bash
conda create -y -n lerobot python=3.12
conda activate lerobot
conda install ffmpeg -c conda-forge
pip install 'lerobot[dataset]'
```

The guide notes that TorchCodec, the default video decoder, requires `ffmpeg`. The `dataset` extra matters: a plain `pip install lerobot` "installs only the core ML dependencies", and the guide's extras table lists `dataset` for "Loading & creating datasets". Without it, `from lerobot.datasets import LeRobotDataset` stops with an ImportError that names the extra. This lab was written against lerobot 0.7.0, and the scripts in steps C2 and C3 were tested with it on a small synthetic sequence in the EuRoC layout.

### Step C2: Write the episode

The script uses only the documented writing API: `LeRobotDataset.create(repo_id, fps, features, root=...)`, `add_frame()` with a `task` key, `save_episode()` and `finalize()` ([LeRobotDataset v3.0 docs](https://huggingface.co/docs/lerobot/lerobot-dataset-v3), [lerobot_dataset.py](https://github.com/huggingface/lerobot/blob/v0.7.0/src/lerobot/datasets/lerobot_dataset.py)). The feature format follows lerobot's own DROID port ([port_droid.py](https://github.com/huggingface/lerobot/blob/v0.7.0/examples/port_datasets/port_droid.py)). Choices that are this lab's, not lerobot's, are marked in the comments.

```python

from pathlib import Path

from PIL import Image
from lerobot.datasets import LeRobotDataset

seq = Path(sys.argv[1])            # e.g. dataset-room1_512_16
traj = Path(sys.argv[2])           # Basalt trajectory.csv (--save-trajectory euroc)
out = Path(sys.argv[3])            # a new, empty folder for the dataset

# Camera frames: timestamp [ns], file name
frames = []
for line in (seq / "mav0/cam0/data.csv").read_text().splitlines():
    if line.startswith("#") or not line.strip():
        continue
    t, name = [x.strip() for x in line.split(",")[:2]]
    frames.append((int(t), name))

# Basalt poses: timestamp [ns], position, quaternion w, x, y, z (T_w_i)
poses = {}
for line in traj.read_text().splitlines():
    if line.startswith("#") or not line.strip():
        continue
    t, *v = line.split(",")
    poses[int(t)] = [float(x) for x in v]   # int, not float: keep every nanosecond

# This lab's choice: keep only frames that have a pose, and report gaps.
kept = [(t, n) for t, n in frames if t in poses]
print(f'{len(frames)} frames, {len(kept)} with a pose')
dt = np.diff([t for t, _ in kept]) / 1e9
fps = round(1.0 / np.median(dt))
print(f'fps {fps}, largest gap {dt.max():.3f} s')

first = np.array(Image.open(seq / "mav0/cam0/data" / kept[0][1]))
h, w = first.shape[:2]

features = {
    "observation.images.cam0": {
        "dtype": "video", "shape": (h, w, 3),
        "names": ["height", "width", "channels"],
    },
    # This lab's choice: IMU body pose in Basalt's world frame,
    # position in metres, quaternion in x, y, z, w order.
    "observation.state": {
        "dtype": "float32", "shape": (7,),
        "names": {"axes": ["x", "y", "z", "qx", "qy", "qz", "qw"]},
    },
}

ds = LeRobotDataset.create(repo_id="local/c401_lab", fps=fps,
                           features=features, root=out)
try:
    for t, name in kept:
        img = np.array(Image.open(seq / "mav0/cam0/data" / name))
        if img.dtype == np.uint16:      # this lab's choice: 16-bit to 8-bit
            img = (img >> 8).astype(np.uint8)
        if img.ndim == 2:               # greyscale to three channels
            img = np.stack([img] * 3, axis=-1)
        px, py, pz, qw, qx, qy, qz = poses[t]
        ds.add_frame({
            "observation.images.cam0": img,
            "observation.state": np.array([px, py, pz, qx, qy, qz, qw],
                                          dtype=np.float32),
            "task": 'TUM VI room1, handheld, IMU pose from Basalt',
        })
    ds.save_episode()
finally:
    ds.finalize()
```

Run it with your three paths. lerobot sets each frame's timestamp to its index divided by `fps` ([Lesson 4](https://egocam.ai/university/c401/lesson-4-training-formats/#lerobotdataset-v30)), so the script prints the largest gap between kept frames: if it is much larger than `1/fps`, frames are missing and the stored timestamps will drift from the real ones. End the episode at the gap instead.

**You should see** under your output folder `meta/info.json`, `meta/stats.json`, `meta/tasks.parquet`, `meta/episodes/`, `data/chunk-000/file-000.parquet` and `videos/observation.images.cam0/chunk-000/file-000.mp4`, the v3.0 layout in [Lesson 4](https://egocam.ai/university/c401/lesson-4-training-formats/).

> **Diagram:** Why LeRobotDataset v3.0 changed the layout. In v2.1 every episode has its own Parquet file and one MP4 per camera, so the file count grows with episodes times cameras. In v3.0 many episodes are concatenated into each Parquet shard and each camera's MP4 shard, and a row in meta/episodes records each episode's length, task and offsets, which locate it as a row range in the data and a time range in the video. Shard sizes are lerobot's defaults. Sources: the LeRobotDataset v3.0 docs and lerobot's datasets/utils.py (v0.3.3 for v2.1, main for v3.0).

### Step C3: Read it back

Load the dataset as the [v3.0 docs](https://huggingface.co/docs/lerobot/lerobot-dataset-v3) show, with your local folder as `root`:

```python
from lerobot.datasets import LeRobotDataset

ds = LeRobotDataset("local/c401_lab", root="[OUTPUT_FOLDER]")
print(ds.num_episodes, ds.num_frames, ds.fps)
sample = ds[100]
print(sample["observation.state"], sample["observation.images.cam0"].shape)
```

**You should see** one episode, the number of kept frames, your fps, a seven-value state and an image tensor of shape `[C, H, W]`.

**Checkpoint:** compare `sample["observation.state"]` with the 101st kept pose (index 100): same numbers, with the quaternion reordered from Basalt's `w, x, y, z` to the `x, y, z, w` you declared.

### Step C4: Write down what the numbers mean

LeRobot's `meta/info.json` has no field for calibration or coordinate frames ([Lesson 4](https://egocam.ai/university/c401/lesson-4-training-formats/#lerobotdataset-v30)). Put the Basalt calibration file under `meta/`, and write on the dataset card: which frame the pose is in (here the IMU body, `T_w_i`), the units, the quaternion order, the system and version that produced it, the sequence's licence, and how frames without a pose were handled. Course C402 builds actions on top of exactly these facts.

The frame matters as soon as hands are added. Hand joints are measured in the camera frame, so they move into the world with the camera's pose, `T_world_cam = T_world_imu · T_imu_cam`, using the camera-IMU transform from your calibration. Treating Basalt's IMU pose as if it were the camera's would shift and rotate every hand point by the offset between the IMU and the camera.

## Sources

- Basalt, Usenko et al.: [README](https://gitlab.com/VladyslavUsenko/basalt), [VIO and mapping guide](https://gitlab.com/VladyslavUsenko/basalt/-/blob/master/doc/VioMapping.md), [calibration guide](https://gitlab.com/VladyslavUsenko/basalt/-/blob/master/doc/Calibration.md), and the [`src/vio.cpp`](https://gitlab.com/VladyslavUsenko/basalt/-/blob/master/src/vio.cpp) and [`dataset_io_euroc.h`](https://gitlab.com/VladyslavUsenko/basalt/-/blob/master/include/basalt/io/dataset_io_euroc.h) sources (master, commit `0f3b2b52`).
- ORB-SLAM3, UZ-SLAMLab: [README](https://github.com/UZ-SLAMLab/ORB_SLAM3), [`stereo_inertial_tum_vi.cc`](https://github.com/UZ-SLAMLab/ORB_SLAM3/blob/master/Examples/Stereo-Inertial/stereo_inertial_tum_vi.cc) and [`System.cc`](https://github.com/UZ-SLAMLab/ORB_SLAM3/blob/master/src/System.cc) (commit `4452a3c`).
- OpenVINS, RPNG: [installation](https://docs.openvins.com/gs-installing.html), [tutorial](https://docs.openvins.com/gs-tutorial.html), [error evaluation](https://docs.openvins.com/eval-error.html) and [serial.launch](https://github.com/rpng/open_vins/blob/master/ov_msckf/launch/serial.launch) (commit `6948812`).
- Hugging Face lerobot (v0.7.0): [installation](https://huggingface.co/docs/lerobot/installation), [LeRobotDataset v3.0](https://huggingface.co/docs/lerobot/lerobot-dataset-v3), [lerobot_dataset.py](https://github.com/huggingface/lerobot/blob/v0.7.0/src/lerobot/datasets/lerobot_dataset.py), [port_droid.py](https://github.com/huggingface/lerobot/blob/v0.7.0/examples/port_datasets/port_droid.py).
- Kalibr wiki, ETH Zurich ASL: [IMU noise model](https://github.com/ethz-asl/kalibr/wiki/IMU-Noise-Model).
- TUM VI: [dataset page](https://vision.in.tum.de/data/datasets/visual-inertial-dataset); Schubert, D. et al. (2018). [The TUM VI benchmark for evaluating visual-inertial odometry](https://arxiv.org/abs/1804.06120). *IEEE/RSJ IROS*.
- Field guide: [SLAM and VIO Systems Compared](https://egocam.ai/processing/slam-vio-systems-compared/), [VIO Benchmarks and Ground Truth](https://egocam.ai/processing/vio-benchmarks-and-ground-truth/), [Running SLAM on Wearable Footage](https://egocam.ai/processing/slam-on-wearable-footage/), [Training Formats](https://egocam.ai/processing/training-formats-lerobot-rlds/), [Why Synchronisation Matters](https://egocam.ai/sync/why-sync-matters/), [IMU Calibration](https://egocam.ai/calibration/imu-calibration/).
