# C201 第 3 课：用 Kalibr、mrcal 或 OpenCV 运行求解器

> C201 相机标定课程的第三课：标定一个鱼眼双目对时，Kalibr、mrcal 和 OpenCV 各自需要什么、产生什么，它们文档中给出的命令，工作顺序，以及在每个工具中怎样选择相机模型。

Page: https://egocam.ai/zh-cn/university/c201/lesson-3-running-the-solver/

有了测量过的标定板和一段录制，求解器就把角点检测结果变成内参和外参。这一课比较实用指南针对双目对讲到的三个工具，即 Kalibr、mrcal 和 OpenCV，并按每个工具的文档给出的样子展示命令。实验会在你自己的采集设备上运行它们。逐个工具的比较在[标定工具对比](https://egocam.ai/zh-cn/calibration/calibration-tools-compared/)。

## 三个工具一览

| | Kalibr | mrcal | OpenCV |
|---|---|---|---|
| 输入 | 一个 ROS 1 bag | 图像，外加一张角点检测结果表 | 2D–3D 点对的数组 |
| 标定板 | Aprilgrid（推荐）、棋盘格、圆点阵列 | 推荐棋盘格配 mrgingham 检测器；其他检测器通过角点文件接入 | 棋盘格、圆点阵列和 ChArUco 检测器 |
| 相机 | 任意数量；相邻相机必须有重叠 | 任意数量，所有相机用同一个镜头模型 | 一台相机，或用 `stereoCalibrate` 标定一对 |
| 鱼眼模型 | `pinhole-equi`、`omni-radtan`、`eucm-none`、`ds-none` | `LENSMODEL_SPLINED_STEREOGRAPHIC` 等 | `cv::fisheye`（Kannala–Brandt）、`cv::omnidir`（contrib） |
| 质量输出 | 重投影误差、参数标准差、一份 PDF 报告 | 投影不确定度、交叉验证差异、残差图 | 重投影误差 |
| 许可协议 | BSD 风格，带广告条款 | Apache-2.0 | Apache-2.0 |

来源：[标定工具对比](https://egocam.ai/zh-cn/calibration/calibration-tools-compared/)、[标定双目或多相机采集设备](https://egocam.ai/zh-cn/calibration/stereo-and-multi-camera-calibration/)和 mrcal 的 [how-to-calibrate 指南](https://mrcal.secretsauce.net/how-to-calibrate.html)。

## Kalibr

Kalibr 是实用指南从头到尾完整记录的那条路，见 [Kalibr 工作流程](https://egocam.ai/zh-cn/kalibr/kalibr-workflow/)。

> **Diagram:** Kalibr's two calibrations and the files that pass between them. The camera calibration uses a recording in which the cameras stay still and the target moves; the camera–IMU calibration uses one in which the target stays still and the rig moves on every axis, and it takes camchain.yaml from the first step plus the IMU noise values in imu.yaml. Rates are the Kalibr wiki's suggestions (about 4 Hz for the first recording; 20 Hz camera and 200 Hz IMU for the second). Each tool also writes a results file and a PDF report to judge before you accept the output.

**把数据放进去**。Kalibr 只读 ROS 1 bag。除了直接录制 ROS 1 bag，[bag 格式页面](https://github.com/ethz-asl/kalibr/wiki/bag-format)还给出两种办法：用 `rosbags` 包转换 ROS 2 bag，或者用 `kalibr_bagcreater` 从图像文件生成 bag，每台相机的图像放在各自的文件夹里，并以纳秒为单位的时间戳命名（[Kalibr 工作流程，第 4 步](https://egocam.ai/zh-cn/kalibr/kalibr-workflow/)）。

**为每台相机选择模型**。`--models` 为每台相机接收一个“投影–畸变”组合，Kalibr 可以在一次运行中给每台相机拟合不同的模型。对鱼眼镜头，实用指南的[模型表](https://egocam.ai/zh-cn/lens-physics/projections-and-distortion/)指向 `pinhole-equi`（Kannala–Brandt）、`ds-none` 或 `eucm-none`，并在 180° 附近不建议用 `pinhole-equi`。

**运行它**。[多相机指南](https://github.com/ethz-asl/kalibr/wiki/multiple-camera-calibration)给出的命令是这种形式：

```bash
kalibr_calibrate_cameras --bag [filename.bag] --topics [TOPIC_0 ... TOPIC_N] --models [MODEL_0 ... MODEL_N] --target [target.yaml]
```

`--topics` 和 `--models` 的顺序决定哪台相机是 cam0、哪台是 cam1。实用指南解释过的选项中有两个：`--show-extraction` 用来观察标定板检测，`--bag-freq` 用来按设定的频率提取特征（[Kalibr 文件参考](https://egocam.ai/zh-cn/kalibr/kalibr-file-reference/)）。如果优化在最初几幅图像中发散，wiki 的建议是 "just try to restart the calibration as the initial guesses are based on a random pick of images."（意为：直接重新启动标定试试，因为初始猜测是基于随机挑选的图像。）

**输出什么**。`<bag>-camchain.yaml`（每台相机的内参、畸变和 `T_cn_cnm1`）、`<bag>-results-cam.txt` 和 `<bag>-report-cam.pdf`（[Kalibr 工作流程，第 5 步](https://egocam.ai/zh-cn/kalibr/kalibr-workflow/)）。

## mrcal

mrcal，"originally built at NASA/JPL to generate the high-accuracy calibrations demanded by long-range stereo"（意为：最初在 NASA/JPL 构建，用来生成远距离双目所要求的高精度标定）（[mrcal](https://mrcal.secretsauce.net/)），是实用指南用来评判标定的工具：它报告投影不确定度，并支持交叉验证（第 4 课）。

**模型选择**。[how-to-calibrate 指南](https://mrcal.secretsauce.net/how-to-calibrate.html)推荐对每只镜头都用它的样条模型 `LENSMODEL_SPLINED_STEREOGRAPHIC`：它 "works very well, and is able to represent real-world lenses better than the parametric models"（意为：效果很好，并且能比参数模型更好地表示真实世界的镜头）。这个模型需要一个水平视场角 `fov_x_deg`，指南说先从镜头规格书取值，再用 `mrcal-show-splined-model-correction` 检查。样条模型需要标定板的密集覆盖，因为样条只在有数据的地方受到约束（[镜头投影与畸变](https://egocam.ai/zh-cn/lens-physics/projections-and-distortion/)）。mrcal 在一次运行中对所有相机拟合同一个镜头模型；指南把这称为 "a current limitation of mrcal"（意为：mrcal 目前的一个局限）。

**运行它**。指南中的调用示例，针对一台相机：

```bash
mrcal-calibrate-cameras                                                         \
  --corners-cache corners.vnl                                                   \
  --lensmodel LENSMODEL_SPLINED_STEREOGRAPHIC_order=3_Nx=30_Ny=18_fov_x_deg=150 \
  --focal 1900                                                                  \
  --object-spacing 0.0588                                                       \
  --object-width-n 14                                                           \
  '*.JPG'
```

这些数字属于指南自己的镜头和标定板。`--object-spacing` 是测得的相邻角点之间的距离，`--object-width-n` 是标定板横向的角点数，`--focal` 是一个粗略的起始焦距，以像素为单位。对双目对，给每台相机一个带引号的 glob，例如 `'frame*-camera0.png' 'frame*-camera1.png'`：帧号相同的图像被视为在同一时刻拍摄。如果角点文件还不存在，工具会运行 mrgingham 并写出它。输出是每台相机一个 `camera-N.cameramodel` 文件。

**在工具之间转换**。mrcal 自带 `mrcal-from-kalibr` 和 `mrcal-to-kalibr`（[标定工具对比](https://egocam.ai/zh-cn/calibration/calibration-tools-compared/)）。在对鱼眼双目对依赖这个转换器之前，先看它自己的说明：它的[文档](https://github.com/dkogan/mrcal/blob/master/mrcal-from-kalibr)说它目前只支持 Kalibr 的 `pinhole` 相机配 `radtan` 畸变或无畸变。它的不确定度工具还需要这次求解的优化输入；对没有这些输入的模型，`mrcal-show-projection-uncertainty` 会停止并提示 "optimization_inputs are unavailable in this model"（意为：这个模型中没有 optimization_inputs）。所以，Kalibr 的鱼眼标定不能通过转换来用 mrcal 的不确定度图评判；要做这件事，就在 mrcal 里直接标定。

## OpenCV

OpenCV 一次标定一台相机，或者一对。它的 fisheye 模块实现了 Kannala–Brandt 模型，opencv_contrib 中的 `cv::omnidir` 实现了 Mei 的统一模型（[标定工具对比](https://egocam.ai/zh-cn/calibration/calibration-tools-compared/)）。

顺序很重要。OpenCV 自己的文档提醒，一次估计所有参数 "can diverge from the correct solution"（意为：可能偏离正确解而发散），并建议："If the intrinsic parameters can be estimated with high accuracy for each of the cameras individually (for example, using calibrateCamera ), you are recommended to do so and then pass CALIB_FIX_INTRINSIC flag to the function along with the computed intrinsic parameters"（意为：如果可以对每台相机单独高精度地估计内参（例如使用 calibrateCamera），建议这样做，然后把 CALIB_FIX_INTRINSIC 标志连同算出的内参一起传给该函数）（[OpenCV calib3d 参考文档](https://docs.opencv.org/4.x/d9/d0c/group__calib3d.html)）。它的 `stereoRectify` 只做针孔立体校正，容纳不下完整的鱼眼视野（[做立体校正，还是在射线上工作](https://egocam.ai/zh-cn/calibration/stereo-and-multi-camera-calibration/)）。

## 每个工具中相同的顺序

先内参，再双目对。OpenCV 直接这样建议；[TUM VI](https://egocam.ai/zh-cn/calibration/stereo-and-multi-camera-calibration/) 在各传感器之间遵循了同样的顺序；Kalibr 在任何 IMU 步骤之前先求解相机及其相机链。当一次鱼眼求解彻底失败时，实用指南的[双目页面](https://egocam.ai/zh-cn/calibration/stereo-and-multi-camera-calibration/)转述了 BabelCalib 的发现：在它的鱼眼和折反射基准上，Kalibr 和 OpenCV 使用 Kannala–Brandt 时都有 24% 的情况失败，而不需要初始猜测的 BabelCalib 没有失败；它每次调用标定一台相机。

> **Diagram:** Three results reported in the tools' own papers, not a head-to-head benchmark: calibration failure rates on BabelCalib's fisheye and catadioptric benchmark; test reprojection error for guided (AprilCal) and unguided (OpenCV checkerboard) capture in AprilCal's user study; and OpenVINS position error in simulation when starting from a deliberately bad calibration, with online calibration off and on. The lower two panels use logarithmic scales.

## 自测

1. 你的录制是一个 ROS 2 bag。Kalibr 需要什么？实用指南说怎样得到它？
2. 你运行 `kalibr_calibrate_cameras --topics /cam1/image_raw /cam0/image_raw ...`。输出中哪台实物相机是 cam0？
3. 你用 Kalibr 以 `ds-none` 求解了一次标定，现在想要 mrcal 的投影不确定度图。你能把它转换过去并画出这张图吗？
4. 为什么 OpenCV 建议在 `stereoCalibrate` 中使用 `CALIB_FIX_INTRINSIC`？

### 答案

1. 一个 ROS 1 bag。用 `rosbags` 包（`rosbags-convert`）转换它，或者导出图像并用 `kalibr_bagcreater` 生成 bag。
2. `/cam1/image_raw` 上的那台相机。`--topics` 和 `--models` 的顺序决定相机编号。
3. 不能。`mrcal-from-kalibr` 只支持 Kalibr 的针孔相机配 radtan 畸变或无畸变，而且不确定度工具需要只有 mrcal 求解才会保存的优化输入。要得到这张图，就在 mrcal 里标定。
4. 一次估计所有参数可能偏离正确解而发散。先标定每台相机并固定这些内参，留给双目这一步的就只有两台相机之间的变换。

## 参考来源

- 实用指南：[Kalibr 工作流程](https://egocam.ai/zh-cn/kalibr/kalibr-workflow/)、[Kalibr 文件参考](https://egocam.ai/zh-cn/kalibr/kalibr-file-reference/)、[标定工具对比](https://egocam.ai/zh-cn/calibration/calibration-tools-compared/)、[标定双目或多相机采集设备](https://egocam.ai/zh-cn/calibration/stereo-and-multi-camera-calibration/)、[镜头投影与畸变](https://egocam.ai/zh-cn/lens-physics/projections-and-distortion/)。
- Kalibr wiki，ETH Zurich ASL：[multiple-camera calibration](https://github.com/ethz-asl/kalibr/wiki/multiple-camera-calibration) 和 [bag format](https://github.com/ethz-asl/kalibr/wiki/bag-format)。
- Kogan, D. [mrcal](https://mrcal.secretsauce.net/)，它的 [how-to-calibrate 指南](https://mrcal.secretsauce.net/how-to-calibrate.html)，以及 [mrcal-from-kalibr](https://github.com/dkogan/mrcal/blob/master/mrcal-from-kalibr) 和 [mrcal-show-projection-uncertainty](https://github.com/dkogan/mrcal/blob/master/mrcal-show-projection-uncertainty) 这两个工具的源代码。
- OpenCV [calib3d 模块参考文档](https://docs.opencv.org/4.x/d9/d0c/group__calib3d.html)（`stereoCalibrate`、`stereoRectify`）。
