# C202 实验：测量你的 IMU 并把它标定到相机

> C202 IMU 课程的动手实验：录制一段静态 IMU 日志并用 allan_variance_ros 计算它的 Allan 偏差，写出 Kalibr 的 imu.yaml，然后录制一个相机–IMU 数据集并运行 kalibr_calibrate_imu_camera，评判残差和变换，读出并检查时间偏移。每条命令都与工具的文档或源代码给出的一致，并带有检查点以及某一步失败时该怎么办。

Page: https://egocam.ai/zh-cn/university/c202/lab/

本实验测量你的采集设备上的 IMU，并把它与相机联系起来。A 部分录制静止不动的 IMU，并把日志变成 Kalibr 的 `imu.yaml`。B 部分录制采集设备在标定板前的运动，并运行 Kalibr 的相机–IMU 标定，它给出 IMU 与相机之间的变换以及它们时钟之间的时间偏移。

下面的每条命令要么是从工具自己的文档中照抄的，要么是按其文档给出的形式换上你自己的文件名；每一步都链接了来源。凡是根据工具源代码陈述的行为，都注明了文件和 commit。方括号标出需要你填写的值。

先学完[第 1 到第 4 课](https://egocam.ai/zh-cn/university/c202/)，为你的相机做完 [C201 实验](https://egocam.ai/zh-cn/university/c201/lab/)，并把[检查清单](https://egocam.ai/zh-cn/university/c202/checklist/)放在手边。

## A 部分：IMU 自身

A 部分的录制要花几个小时。先启动它，在它运行期间做 B 部分的准备工作。

### A1：编译 allan_variance_ros

[allan_variance_ros 的 README](https://github.com/ori-drs/allan_variance_ros) 说该工具 "is designed for Ubuntu 20.04"（意为：是为 Ubuntu 20.04 设计的），并为其他系统提供了一个 devcontainer。把这个仓库放进一个 ROS 1 catkin 工作空间的 `src` 文件夹，例如 `~/catkin_ws/src/allan_variance_ros`，然后在工作空间文件夹中执行：

```bash
catkin build allan_variance_ros
source devel/setup.bash
```

**你应该看到**这个软件包编译完成，没有错误。README 给出的另一条路线，针对不是 Ubuntu 20.04 的系统，是它的 devcontainer（仓库中的 `.devcontainer/README.md`）。

### A2：准备采集设备

- **把 IMU 配置得与今后录制时完全一样**：相同的输出速率和相同的滤波器设置。把它们记下来。第 4 课说明滤波器会改变时间偏移；噪声同样只属于一种配置。
- **让它预热**。据我们所知，最好在采集设备达到工作温度之后再开始记录日志，因为仍在稳定下来的零偏会表现为一种趋势，而不是噪声（[温度与静态曲线图的局限](https://egocam.ai/zh-cn/calibration/imu-noise-and-allan-variance/)）。
- **把它放在一个有阻尼的表面上**，在整个录制期间不会有东西碰到或撞到它。README 说："Place your IMU on some damped surface and record your IMU data to a rosbag."（意为：把你的 IMU 放在某个有阻尼的表面上，并把 IMU 数据录制到一个 rosbag 里。）任何传到 IMU 的振动都会出现在 Allan 曲线图里，就像它是传感器噪声一样。

### A3：录制静态日志

按 README 第一步所说，在一个终端里启动 `roscore`，并启动 IMU 驱动程序。然后只录制 IMU 话题，采用 [ROS rosbag 命令行](https://wiki.ros.org/rosbag/Commandline)页面给出的形式（`-O` 给 bag 命名，`--duration` 让它停止）：

```bash
rosbag record --duration=[HOURS]h -O imu_static.bag [IMU_TOPIC]
```

录多长：README 说 "You must record at least 3 hours of data. The longer the sequence, the more accurate the results."（意为：你必须录制至少 3 小时的数据。序列越长，结果越准确。）Kalibr wiki 建议一段 "~15-24 hour dataset recording of the IMU being stationary"（意为：IMU 保持静止的约 15 到 24 小时的数据集录制）（[IMU noise model](https://github.com/ethz-asl/kalibr/wiki/IMU-Noise-Model)）。第 2 课的表格说明了原因：随机游走来自长 τ 一端，3 小时的日志在那里是不确定的。

**检查点**：`rosbag info imu_static.bag` 给出 bag 的时长和消息数（[rosbag 命令行](https://wiki.ros.org/rosbag/Commandline)）。

**你应该看到**时长至少是你计划的长度，IMU 话题接近其标称采样率，消息数接近 IMU 采样率乘以时长。消息数明显少于这个值说明有采样丢失；重新录制。

### A4：把消息按时间戳排序

README 建议做这一步：

```bash
rosrun allan_variance_ros cookbag.py --input original_rosbag --output cooked_rosbag
```

换成你的文件名，就是 `--input imu_static.bag --output imu_static_cooked.bag`。该脚本按每条消息的 header 时间戳重写它（`scripts/cookbag.py`，commit `1d54b60`）。Allan 计算对连续的采样求平均，所以它们必须按采样的先后顺序排列（[温度与静态曲线图的局限](https://egocam.ai/zh-cn/calibration/imu-noise-and-allan-variance/)）。

### A5：计算 Allan 偏差

按仓库中示例（`config/*.yaml`）的格式写一个配置文件：

```yaml
imu_topic: "[IMU_TOPIC]"
imu_rate: [IMU_RATE_HZ]
measure_rate: [IMU_RATE_HZ] # Rate to which imu data is subsampled
sequence_time: [RECORD_LENGTH_S]
```

源代码如何使用这些键（`src/AllanVarianceComputor.cpp`，commit `1d54b60`）：

- **`measure_rate`** 设定降采样步长为 `imu_rate / measure_rate`。有些示例配置做了降采样（400 到 100 Hz）；`config/sim.yaml` 没有。据我们所知，让 `measure_rate` 等于 `imu_rate` 可以避开 Kalibr 噪声模型中关于降采样的那条注意事项（[第 2 课](https://egocam.ai/zh-cn/university/c202/lesson-2-measuring-imu-noise/)）。
- **`sequence_time`** 限定读取日志的多少秒：在它之后的采样被跳过。把它设为你的记录长度。
- **陀螺仪单位**。源代码把陀螺仪的值按弧度每秒读入，ROS IMU 消息里就是这样存的，并把它们换算成度用于输出（换算处的一条注释是这样说的）。

把处理过的 bag **单独**放在一个文件夹里：该工具列出文件夹中的 `.bag` 文件，并且只处理其中的第一个（`src/allan_variance.cpp`）。然后按 README 给出的方式运行：

```bash
rosrun allan_variance_ros allan_variance [path_to_folder_containing_bag] [path_to_config_file]
```

**你应该看到**读取日志时的进度信息，以及写入 bag 所在文件夹的 `allan_variance.csv`。源代码计算的平均时间从 0.1 s 到约 1,000 s。

### A6：读曲线图和数字

运行分析，并传入配置文件，使话题和采样率写进输出文件：

```bash
rosrun allan_variance_ros analysis.py --data allan_variance.csv --config [path_to_config_file]
```

README 说按空格键可以转到下一张图。该脚本按轴打印白噪声（速度随机游走或角度随机游走）、零偏不稳定性和随机游走，保存 `acceleration.png` 和 `gyro.png`，并写出 `imu.yaml`（`--output` 可改文件名）。

对照[第 2 课](https://egocam.ai/zh-cn/university/c202/lesson-2-measuring-imu-noise/)逐项检查：

1. **形状**。短 τ 处是下降的 −½ 段，然后是平坦的底部，再是上升段。最开头斜率为 −1 是量化噪声；右端趋向 +1 的斜率是一种趋势，例如预热（[失效情形](https://egocam.ai/zh-cn/calibration/imu-noise-and-allan-variance/)）。
2. **拟合的直线**。在 `analysis.py`（commit `1d54b60`）中，−½ 直线是对 10 s 以下的 τ 拟合的，+½ 直线是对整条曲线拟合的，而不只是上升的那一支。用眼睛检查每条直线是否与它所代表的那部分曲线相符。
3. **各轴**。比较每个传感器的三个轴。如果有一个不一致，把它记下来。
4. **写进文件的是哪个轴**。自 commit `7a3a461`（2022 年 10 月，提交说明为 `Use worst axis instead of average and support overlapping bins`）起，`analysis.py` 写入 `imu.yaml` 的是三个轴的值中最大的那个，而不是它们的均值（`np.amax`）。README 中的示例 `imu.yaml` 与三轴均值吻合，所以它早于这次改动。把打印出来的各轴值与文件对照着读。
5. **规格书**。换算规格书上的噪声指标并做比较（[由规格书得到这些值](https://egocam.ai/zh-cn/kalibr/kalibr-file-reference/)）。实测值可能往任一方向偏离（[可穿戴采集设备上的 IMU](https://egocam.ai/zh-cn/hardware/imu-sensors/)）。

> **Diagram:** An Allan deviation plot from hours of a stationary IMU. White noise is read on the falling line at τ = 1 s (Kalibr's noise density) and rate random walk on the rising line at τ = 3 s (Kalibr's random walk). The flat minimum is what Woodman and allan_variance_ros report as bias instability; by the IEEE 952 derivation the coefficient B is that minimum divided by 0.664.

### A7：写出给 Kalibr 用的 imu.yaml

从生成的文件出发，对照 [YAML formats](https://github.com/ethz-asl/kalibr/wiki/Yaml-formats) 页面检查每个键：

```yaml
#Accelerometers
accelerometer_noise_density: [VALUE]   #Noise density (continuous-time)
accelerometer_random_walk:   [VALUE]   #Bias random walk

#Gyroscopes
gyroscope_noise_density:     [VALUE]   #Noise density (continuous-time)
gyroscope_random_walk:       [VALUE]   #Bias random walk

rostopic:                    [IMU_TOPIC]      #the IMU ROS topic
update_rate:                 [IMU_RATE_HZ]    #Hz (for discretization of the values above)
```

- **单位**：陀螺仪的值以弧度为单位，不是度。
- **`update_rate`** 是 IMU 在 B 部分的 bag 中真实运行的采样率，`rostopic` 是它在那里的话题。
- **放大**。定一个倍数。Kalibr wiki 说："for lowest-cost sensors, increasing the noise model parameters by a factor of 10x or more may be necessary"（意为：对最低成本的传感器，可能需要把噪声模型参数增大到 10 倍或更多）（[放大噪声值](https://egocam.ai/zh-cn/kalibr/kalibr-file-reference/)）。把原始文件存为 `imu_allan.yaml`，把放大后的存为 `imu.yaml`，并把倍数记下来。B5 步会告诉你它是否合适。

## B 部分：IMU 相对相机

### B1：备齐输入

- [C201 实验](https://egocam.ai/zh-cn/university/c201/lab/)得到的 `[calib]-camchain.yaml` 和 `target.yaml`，对应同样的相机，分辨率和对焦也相同。
- A7 得到的 `imu.yaml`。
- Kalibr，按 [C201 实验第 1 步](https://egocam.ai/zh-cn/university/c201/lab/)搭建，你的数据文件夹挂载在 `/data`。

### B2：锁定设置

- **曝光短而且固定**，光线良好、均匀。[相机–IMU 指南](https://github.com/ethz-asl/kalibr/wiki/camera-imu-calibration)要求 "keep the motion blur low"（意为：保持运动模糊小），采用 "low shutter times"（意为：短快门时间）和 "good illumination"（意为：良好的照明）。固定的曝光还能让时间偏移在录制期间保持不变（第 4 课）。
- **IMU 处于生产配置**，与 A2 中相同。
- **速率**。该指南报告说 "Good results have been obtained by using a camera rate of 20 Hz and an IMU rate of 200 Hz."（意为：使用 20 Hz 的相机帧率和 200 Hz 的 IMU 采样率取得了良好的结果。）使用你的采集设备真实的 IMU 采样率；它必须与 `update_rate` 一致。

### B3：录制相机–IMU 数据集

把标定板固定在墙上或桌上；它绝不能动。把图像话题和 IMU 话题一起录制：

```bash
rosbag record -O imu_cam.bag [CAM0_TOPIC] [CAM1_TOPIC] [IMU_TOPIC]
```

如果你的录制程序写出的是文件，就用 `kalibr_bagcreater` 由 `cam0/`、`cam1/` 和一个 `imu0.csv` 生成 bag，该 CSV 的表头为 `timestamp,omega_x,omega_y,omega_z,alpha_x,alpha_y,alpha_z`，单位是 "timestamps=[ns], omega=[rad/s], alpha=[m/s^2]"（意为：时间戳为 [ns]，omega 为 [rad/s]，alpha 为 [m/s^2]）（[bag format](https://github.com/ethz-asl/kalibr/wiki/bag-format)）：

```bash
kalibr_bagcreater --folder dataset-dir/. --output-bag awsome.bag
```

运动方式（[第 3 课](https://egocam.ai/zh-cn/university/c202/lesson-3-kalibr-camera-imu/)）：

- 开始时采集设备静止，然后轻轻拿起："avoid shocks, especially at the beginning/end when you pick up the sensor"（意为：避免冲击，尤其是在开头和结尾拿起传感器的时候）。原因见 [Kalibr 工作流程，第 7 步](https://egocam.ai/zh-cn/kalibr/kalibr-workflow/)。
- 让标定板始终在相机的视野内。Kalibr 仅有的视觉测量就是标定板的角点，所以没有标定板的一帧不能把任何东西与相机联系起来。
- 绕每个轴旋转，并沿每个轴平移："try to excite all IMU axes (rotation and translation)"（意为：尽量激励 IMU 的所有轴（旋转和平移））。不只是左右摇摆。
- 动作轻快但平滑。作为量级参考，Furgale 及其同事的录制 "about 90 seconds"（意为：约 90 秒），并且 "an average absolute angular velocity of about 55° s−1"（意为：平均绝对角速度约为 55 °/s）。
- 结束时轻轻放下采集设备。

**检查点**：`rosbag info imu_cam.bag`。

**你应该看到**每个图像话题和 IMU 话题，以及接近 IMU 采样率乘以时长的 IMU 消息数。

### B4：运行标定

在容器内，按该指南示例的形式：

```bash
rosrun kalibr kalibr_calibrate_imu_camera \
	--target /data/target.yaml \
	--imu /data/imu.yaml \
	--imu-models calibrated \
	--cam /data/[calib]-camchain.yaml \
	--bag /data/imu_cam.bag
```

如果 IMU 的比例和失准没有修正过，就用 `--imu-models scale-misalignment`。对于带两个 IMU 的采集设备，把两个文件和两个模型都给出，参考 IMU 在前：`--imu /data/imu0.yaml /data/imu1.yaml --imu-models calibrated calibrated`（[Multi-IMU and IMU intrinsic calibration](https://github.com/ethz-asl/kalibr/wiki/Multi-IMU-and-IMU-intrinsic-calibration)）。

**你应该看到**运行结束时有四个文件：`imu_cam-camchain-imucam.yaml`、`imu_cam-imu.yaml`、`imu_cam-results-imucam.txt` 和 `imu_cam-report-imucam.pdf`（[文件一览](https://egocam.ai/zh-cn/kalibr/kalibr-file-reference/)）。

### B5：评判结果

打开报告和结果文件，对照[第 3 课](https://egocam.ai/zh-cn/university/c202/lesson-3-kalibr-camera-imu/)逐项检查：

1. **IMU 时序**。测量速率页是在预期速率处的一条平线。"Inspect the IMU time dt plot carefully in the PDF report!"（意为：仔细检查 PDF 报告中的 IMU 时间 dt 图！）（[RealSense 教程](https://github.com/ethz-asl/kalibr/wiki/Calibrating-Intel-RealSense-Cameras)）。如果它显示出成簇和间隙，就停下来：先修好时间戳，再做别的。
2. **IMU 残差**在 ±3σ 虚线之内，加速度计和陀螺仪都是。
3. **零偏**在其 ±3σ 边界之内。
4. **重投影**误差在 3σ 圆之内，并且与相机标定时相当。
5. 结果文件中的**归一化残差**：把它们与你假定的噪声比较。

**如果某项检查不通过**：残差远在线外，说明噪声值太小或者数据不好：加大放大倍数，或者检查时间戳。零偏越出其边界，说明 "your trajectory was too dynamic, or your noise values are not good"（意为：你的轨迹太剧烈，或者你的噪声值不好）。每次只改一样东西，然后重新求解。

### B6：检查变换

在结果文件中，`T_ci` 把 IMU 坐标变到相机坐标，所以它的平移量是 IMU 在该相机坐标系中的位置，单位为米（[Kalibr 如何命名变换](https://egocam.ai/zh-cn/kalibr/kalibr-file-reference/)）。把它与卡尺测量值或机械图纸比较："Sanity check your final rotation and translation with hand-measured values."（意为：用手工测量的值对最终的旋转和平移做合理性检查。）旋转部分应当与 IMU 的安装方式相符；如果它与相机正交安装，各元素接近 0 或 ±1。

> **Diagram:** How Kalibr names its transforms. T_a_b takes a point given in frame b and returns it in frame a. Each camera block in camchain-imucam.yaml stores T_cam_imu (IMU to that camera), and every camera after cam0 stores T_cn_cnm1 (the previous camera to this one, so cam1 holds T_c1_c0).

### B7：读出时间偏移

在结果文件中找到 `timeshift cam0 to imu0: [s] (t_imu = t_cam + shift)` 这一行，在 `camchain-imucam.yaml` 中找到 `timeshift_cam_imu`（[第 4 课](https://egocam.ai/zh-cn/university/c202/lesson-4-time-offset-and-multiple-imus/)）。

1. **读出符号**。负：相机的时间戳相对 IMU 的偏晚。正：IMU 的偏晚。
2. **把它与你的时间戳的产生方式对照**。帧带的是曝光的开始、中间还是结束时刻？IMU 有没有滤波器延迟？[成因表](https://egocam.ai/zh-cn/calibration/camera-imu-time-offset/)给出了每一种的实测大小。
3. **同一个时钟上的相机应当一致**。在一起触发的双目对上，两台相机的偏移应当接近；wiki 的示例中是 −8.121e-05 s 和 −8.681e-05 s。
4. **它的边界**。`--timeoffset-padding` 选项限定偏移可以离开 Kalibr 基于相关的初始猜测多远。多 IMU 页面说 "trouble finding an appropriate value likely hints to issues in the dataset"（意为：难以找到合适的值，很可能暗示数据集有问题）：在把它放宽之前，先看看时间戳。

### B8：再标定一次并比较

在相同设置下录制第二个相机–IMU 数据集，并用同样的方式标定。比较两个变换和两个时间偏移。根据我们与业内人士的交流，在两段良好的录制之间变动很大的值，哪一段都没有把它确定好（[Kalibr 工作流程，第 9 步](https://egocam.ai/zh-cn/kalibr/kalibr-workflow/)）。作为量级参考，Furgale 及其同事的偏移估计在各数据集之间保持 "within a domain of ±0.2 ms"（意为：在 ±0.2 ms 的范围内）（[用 Kalibr 离线估计](https://egocam.ai/zh-cn/calibration/camera-imu-time-offset/)）。

**可选，曝光斜率**。如果你的帧可能是在曝光开始或结束时打时间戳的，就在几个固定的曝光时间下分别标定，并拟合偏移对曝光的关系。斜率接近 +0.5 说明是曝光开始时的时间戳，接近 −0.5 是曝光结束时，接近 0 是曝光中点。[提示词页面](https://egocam.ai/zh-cn/university/c202/prompts/)有一条用来写这个拟合的提示词。

### B9：签字确认并保存

过一遍[检查清单](https://egocam.ai/zh-cn/university/c202/checklist/)的签字确认一节。把 `imu_allan.yaml`、`imu.yaml`、放大倍数、`camchain-imucam.yaml`、结果文件和报告随数据一起保存，做版本管理，并与这台设备的序列号和 IMU 配置绑定。当你运行一个在线估计偏移的跟踪器时，用 Kalibr 的值作为它的起始值，并先把它的符号约定与 Kalibr 的核对一遍（[相机–IMU 时间偏移，检查清单](https://egocam.ai/zh-cn/calibration/camera-imu-time-offset/)）。

## 某一步失败时

| 现象 | 来源说该怎么做 |
|---|---|
| IMU 时间戳成簇，如 wiki 示例中的 "a burst of IMU are send at a rate of 1ms with gaps of 6ms between"（意为：一簇 IMU 数据以 1 ms 的间隔发出，簇与簇之间有 6 ms 的间隙） | "You will need to rectify the timestamp problems."（意为：你需要纠正时间戳问题。）（[camera–IMU calibration](https://github.com/ethz-asl/kalibr/wiki/camera-imu-calibration)） |
| IMU 残差远在 ±3σ 之外 | 放大噪声值；检查时间戳 |
| 时间偏移无法在其边界内稳定下来 | wiki："trouble finding an appropriate value likely hints to issues in the dataset"（意为：难以找到合适的值，很可能暗示数据集有问题） |
| 标定板位姿在运动中翻转 | "The use of an Aprilgrid is recommended to avoid this problem entirely."（意为：建议使用 Aprilgrid 来完全避免这个问题。） |
| bag 被拒绝 | 是 ROS 2 bag：用 `rosbags-convert` 把它转换成 ROS 1（[Kalibr 工作流程，第 4 步](https://egocam.ai/zh-cn/kalibr/kalibr-workflow/)） |
| Allan 曲线图在右端向斜率 +1 上升 | 一种趋势，例如预热：把它剪掉，或者在稳定的温度下重新录制 |
| `allan_variance` 处理了错误的日志 | 文件夹里有不止一个 `.bag`：该工具只处理一个 |

多 IMU 页面总结了最大的风险："The most common failure mode of kalibr appears to be incorrect timestamps provided by the user."（意为：kalibr 最常见的失败情形看来是用户提供的时间戳不正确。）

## 参考来源

- Buchanan, R. [allan_variance_ros](https://github.com/ori-drs/allan_variance_ros), Oxford Robotics Institute：README、`config/*.yaml`、`scripts/analysis.py`、`scripts/cookbag.py`、`src/allan_variance.cpp` 和 `src/AllanVarianceComputor.cpp`（commit `1d54b60`，2025 年 1 月），以及 `scripts/analysis.py` 的历史（commit `7a3a461`）。
- Kalibr wiki，ETH Zurich ASL：[camera–IMU calibration](https://github.com/ethz-asl/kalibr/wiki/camera-imu-calibration)、[Multi-IMU and IMU intrinsic calibration](https://github.com/ethz-asl/kalibr/wiki/Multi-IMU-and-IMU-intrinsic-calibration)、[IMU noise model](https://github.com/ethz-asl/kalibr/wiki/IMU-Noise-Model)、[YAML formats](https://github.com/ethz-asl/kalibr/wiki/Yaml-formats)、[bag format](https://github.com/ethz-asl/kalibr/wiki/bag-format)、[Calibrating Intel RealSense cameras](https://github.com/ethz-asl/kalibr/wiki/Calibrating-Intel-RealSense-Cameras)。
- Kalibr 源代码，[github.com/ethz-asl/kalibr](https://github.com/ethz-asl/kalibr)（commit `1f60227`）：[kalibr_calibrate_imu_camera](https://github.com/ethz-asl/kalibr/blob/master/aslam_offline_calibration/kalibr/python/kalibr_calibrate_imu_camera)、[IccSensors.py](https://github.com/ethz-asl/kalibr/blob/master/aslam_offline_calibration/kalibr/python/kalibr_imu_camera_calibration/IccSensors.py)、[IccUtil.py](https://github.com/ethz-asl/kalibr/blob/master/aslam_offline_calibration/kalibr/python/kalibr_imu_camera_calibration/IccUtil.py)。
- ROS wiki：[rosbag command line](https://wiki.ros.org/rosbag/Commandline)。
- Furgale, P., Rehder, J. and Siegwart, R. (2013). [Unified temporal and spatial calibration for multi-sensor systems](https://doi.org/10.1109/IROS.2013.6696514). *IEEE/RSJ IROS*.
- 实用指南：[IMU 噪声模型与 Allan 方差](https://egocam.ai/zh-cn/calibration/imu-noise-and-allan-variance/)、[Kalibr 工作流程](https://egocam.ai/zh-cn/kalibr/kalibr-workflow/)、[Kalibr 文件参考](https://egocam.ai/zh-cn/kalibr/kalibr-file-reference/)、[相机–IMU 时间偏移](https://egocam.ai/zh-cn/calibration/camera-imu-time-offset/)、[可穿戴采集设备上的 IMU](https://egocam.ai/zh-cn/hardware/imu-sensors/)。
