# C201 实验：标定你的鱼眼双目采集设备

> C201 相机标定课程的动手实验：用 Kalibr 标定你自己的鱼眼双目对的内参和外参，用一次重复标定和已知几何检查它，并可选地用 mrcal 的投影不确定度和交叉验证来评判它。每条命令都与工具文档给出的一致，带检查点，以及某一步失败时该怎么办。

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

这个实验标定你的采集设备上的相机：每台相机的内参，以及双目对两台相机之间的变换。相机到 IMU 的标定属于课程 C202；[Kalibr 工作流程](https://egocam.ai/zh-cn/kalibr/kalibr-workflow/)的第 6 到第 9 步讲它。

主线是 Kalibr，实用指南从头到尾完整记录了它。B 部分是可选的 mrcal 路线，供想要投影不确定度和交叉验证的团队使用。下面每条命令都是从工具自己的文档中复制的，或者按文档记载的形式换上你自己的文件名；每一步都链接了来源。方括号标出需要你填写的值。

先学完[第 1 到第 4 课](https://egocam.ai/zh-cn/university/c201/)，并把[检查清单](https://egocam.ai/zh-cn/university/c201/checklist/)放在手边。

## A 部分：Kalibr

### 第 1 步：安装配置 Kalibr

Kalibr 需要 ROS 1。Kalibr wiki 的[安装页面](https://github.com/ethz-asl/kalibr/wiki/installation)为没有 ROS 1 的系统提供了一个 Docker 镜像。构建它：

```bash
git clone https://github.com/ethz-asl/kalibr.git
cd kalibr
docker build -t kalibr -f Dockerfile_ros1_20_04 . # change this to whatever ubuntu version you want
```

然后启动容器，把你的数据文件夹挂载到 `/data`：

```bash
FOLDER=/path/to/your/data/on/host
xhost +local:root
docker run -it -e "DISPLAY" -e "QT_X11_NO_MITSHM=1" \
    -v "/tmp/.X11-unix:/tmp/.X11-unix:rw" \
    -v "$FOLDER:/data" kalibr
```

在容器内，用 `source devel/setup.bash` 加载 ROS 环境。安装页面的示例随后以 `rosrun kalibr <tool>` 的形式运行每个工具；wiki 的其他页面只写工具名本身。下面的命令保持它们所出自页面的形式。

**你应当看到**容器内的一个 shell 提示符，以及 `/data` 下你的数据文件夹中的文件。

**如果失败**：每个工具也可以用 `--h` 列出它的选项（[Kalibr 文件参考](https://egocam.ai/zh-cn/kalibr/kalibr-file-reference/)）。如果图或报告窗口打不开，上面的 `DISPLAY` 和 X11 那几行就是把显示传进容器的东西。

### 第 2 步：锁定相机

把内参所依赖的一切都固定在最终工作状态（[第 1 课](https://egocam.ai/zh-cn/university/c201/lesson-1-what-calibration-estimates/)、[Kalibr 工作流程，第 1 步](https://egocam.ai/zh-cn/kalibr/kalibr-workflow/)）：

- 分辨率、裁切和像素合并（binning）模式；
- 对焦，自动对焦关闭；如果可以，用机械方式锁住手动对焦环；
- 光学防抖和电子防抖关闭；
- 在良好的光线下使用短而固定的曝光，这样角点保持清晰，又没有额外的增益噪声（[为什么需要明亮、均匀的光](https://egocam.ai/zh-cn/calibration/targets-and-calibration-sequences/)）。

如果镜头有手动对焦环，并且相机发布实时的 ROS 图像话题，Kalibr 的[相机对焦工具](https://github.com/ethz-asl/kalibr/wiki/camera-focus)有助于每次都把它调成一样：

```bash
kalibr_camera_focus --topic [IMAGE_TOPIC]
```

**你应当看到**带有对焦度量的实时图像。wiki 的说明：把相机对准一个细节丰富的场景，例如西门子星或棋盘格，"and adjust the focus while trying to minimize the calculated focus measure."（意为：然后调节对焦，同时设法使计算出的对焦度量最小。）

**写下来**：分辨率、对焦、曝光和每台相机的序列号。它们是标定的一部分。

### 第 3 步：制作并测量标定板

用 wiki 的[标定板脚本](https://github.com/ethz-asl/kalibr/wiki/calibration-targets)生成一个 Aprilgrid：

```bash
rosrun kalibr kalibr_create_target_pdf --type apriltag --nx [NUM_COLS] --ny [NUM_ROWS] --tsize [TAG_WIDTH_M] --tspace [TAG_SPACING_PERCENT]
```

尽管 wiki 的占位符里写着 `PERCENT`，`--tspace` 是一个像 0.3 这样的小数，不是 30；`--tsize` 以米为单位（[kalibr_create_target_pdf](https://egocam.ai/zh-cn/kalibr/kalibr-file-reference/)）。按你的镜头来定标定板的大小：在相同距离上，更大的标定板更好，mrcal 的[编排研究](https://mrcal.secretsauce.net/tour-choreography.html)发现 "we care about the size of the chessboard relative to its distance from the camera"（意为：我们关心的是棋盘格的尺寸相对于它到相机的距离）（[标定板页面](https://egocam.ai/zh-cn/calibration/targets-and-calibration-sequences/)）。

然后：

1. **把它打印出来，平整地粘**在一块刚性板上。
2. **留出白色边框**，至少一个网格单元宽。
3. **测量它**。跨一个标签的黑色外边缘测量 `tagSize`，并测量两个相邻标签之间的间隙。跨多个标签测量再做除法可以减小误差（[测量打印出来的标定板](https://egocam.ai/zh-cn/kalibr/kalibr-file-reference/)）。
4. **写 `target.yaml`**，填入测得的数字，按 wiki 的格式：

```yaml
target_type: 'aprilgrid' #gridtype
tagCols: [NUM_COLS]      #number of apriltags
tagRows: [NUM_ROWS]      #number of apriltags
tagSize: [MEASURED_M]    #size of apriltag, edge to edge [m]
tagSpacing: [GAP/TAGSIZE] #ratio of space between tags to tagSize
```

**你应当看到** `tagSpacing` 在 0 和 1 之间，`tagSize` 带小数点。

**如果失败**：长度要写成带小数点的形式，例如 `0.06`；单独一个 `1` 会被读成整数，通不过 Kalibr 的检查。`tagSpacing` 是一个比值：把间隙以米为单位写进去，会把每个角点都放到错误的位置（[target.yaml](https://egocam.ai/zh-cn/kalibr/kalibr-file-reference/)）。

> **Diagram:** On an Aprilgrid, tagSize is the width of one tag across its black border, in metres. tagSpacing is not a length: it is the gap between tags divided by tagSize. The small black squares fill the gaps at the tag corners.

### 第 4 步：录制相机序列

采集设备不动，标定板移动。Kalibr 的[多相机指南](https://github.com/ethz-asl/kalibr/wiki/multiple-camera-calibration)建议把相机帧率降到 "to around 4 Hz while capturing the calibration data"（意为：采集标定数据时降到约 4 Hz），并说这 "reduces redundant information in the dataset"（意为：减少数据集中的冗余信息）。把房间里其他所有 AprilTag 都遮住：一个无关的标签可能带有与网格中某个标签相同的 ID（[第 2 课](https://egocam.ai/zh-cn/university/c201/lesson-2-targets-and-recording/)）。

开始之前先计划好运动（[第 2 课](https://egocam.ai/zh-cn/university/c201/lesson-2-targets-and-recording/)）：

- **每台相机各自的近距离视图**，尽量占满它的图像，并向前、向后、向左、向右倾斜。
- **两台相机图像的四角和边缘**。让标定板伸出画面边缘：Aprilgrid 在只看到一部分时仍然能给出角点。
- **共同视野帧**，标定板同时被两台相机看到，距离刚好够远即可。
- **缓慢、平稳的运动**，这样角点保持清晰。

**你应当看到**，在实时画面上，标定板在整段录制中到达了两幅图像的每个部分。

**如果失败**：如果你看不到实时画面，就比你认为需要的多录一些，并在报告中检查覆盖（第 7 步）。在 AprilCal 研究中，按书面说明操作的新手漏掉了图像的四角（[标定板页面](https://egocam.ai/zh-cn/calibration/targets-and-calibration-sequences/)）。

### 第 5 步：把数据放进 ROS 1 bag

Kalibr 只读 ROS 1 bag。用适合你的录制工具的那一种办法（[Kalibr 工作流程，第 4 步](https://egocam.ai/zh-cn/kalibr/kalibr-workflow/)）：

- **ROS 2 bag**：用 `rosbags` 包转换它，如 wiki 的 [ROS 2 指南](https://github.com/ethz-asl/kalibr/wiki/ROS2-Calibration-Using-Kalibr)所示。wiki 写版本要求时没有加引号；shell 会把不带引号的 `>` 读成重定向，所以这里加了引号：

```bash
pip3 install "rosbags>=0.9.12" # might need -U
rosbags-convert <ros2_bag_folder> --dst calib_01.bag --exclude-topic <non_img_and_imu_topics>
```

- **图像文件**：把每台相机的图像放进各自的文件夹 `cam0/` 和 `cam1/`，每个文件以纳秒为单位的时间戳命名，例如 `1385030208726607500.png`，然后用 [bagcreater](https://github.com/ethz-asl/kalibr/wiki/bag-format) 生成 bag：

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

生成的话题是 `/cam0/image_raw` 和 `/cam1/image_raw`。Kalibr 使用你放进去的时间戳；它不会修正它们。

**检查点**：在容器内，`rosbag info` 给出一个 bag 的摘要，包括它的话题、消息数量和频率（[ROS rosbag 命令行](https://wiki.ros.org/rosbag/Commandline)）：

```bash
rosbag info [calib.bag]
```

**你应当看到**每台相机一个图像话题，消息数量相近。

### 第 6 步：标定相机

为每台相机选择一个模型（[第 3 课](https://egocam.ai/zh-cn/university/c201/lesson-3-running-the-solver/)）：不到 180° 的鱼眼镜头用 `pinhole-equi`（Kannala–Brandt），或者用 `ds-none` 或 `eucm-none`，后两者也适合接近或超过 180° 的镜头。使用你的处理流程要用的模型。然后按[安装页面](https://github.com/ethz-asl/kalibr/wiki/installation)在容器内使用的形式运行：

```bash
rosrun kalibr kalibr_calibrate_cameras \
    --bag /data/[calib.bag] --target /data/target.yaml \
    --models [MODEL_0] [MODEL_1] \
    --topics /cam0/image_raw /cam1/image_raw
```

`--topics` 和 `--models` 的顺序决定哪台相机是 cam0。

**你应当看到**，它结束时有三个文件：`<bag>-camchain.yaml`、`<bag>-results-cam.txt` 和 `<bag>-report-cam.pdf`（[Kalibr 文件参考](https://egocam.ai/zh-cn/kalibr/kalibr-file-reference/)）。

**如果失败**：

| 症状 | 参考来源说该怎么办 |
|---|---|
| "Cameras are not connected through mutual observations"（意为：相机没有通过共同观测连接起来） | 多录一些标定板同时出现在两台相机中的帧；检查相机是否同步；该提示信息建议 "Maybe adjust the approx. sync. tolerance"（意为：或许可以调整近似同步容差）（`--approx-sync`，默认 0.02 s） |
| 优化在最初几幅图像中发散 | "just try to restart the calibration as the initial guesses are based on a random pick of images"（意为：直接重新启动标定试试，因为初始猜测是基于随机挑选的图像） |
| 标定板从未或很少被检测到 | 加上 `--show-extraction` 观察检测；检查 `target.yaml`、白色边框、视野中的其他 AprilTag 和模糊 |
| 用上的帧很少 | 一帧里的标签数要多于网格较长一边的标签数才算数：在 6 × 6 的网格上至少 7 个 |
| "Omni with equidistant model not yet supported!"（意为：Omni 配 equidistant 模型尚不支持！） | 使用 `omni-radtan` 或其他模型 |

来源：[Kalibr 工作流程，常见失败](https://egocam.ai/zh-cn/kalibr/kalibr-workflow/)和 [Kalibr 文件参考](https://egocam.ai/zh-cn/kalibr/kalibr-file-reference/)。

### 第 7 步：读懂结果

打开 `<bag>-results-cam.txt` 和 `<bag>-report-cam.pdf`，按[第 4 课](https://egocam.ai/zh-cn/university/c201/lesson-4-reading-the-result/)逐项检查：

1. 结果文件末尾的**标定板块**包含你测得的尺寸。
2. 每台相机的**重投影误差**：均值在 x 和 y 方向都接近零，两台相机的离散程度相近。
3. **参数标准差**（"+-" 值）：没有哪个相对于它的值偏大。
4. 每台相机重投影误差页上的**角点图**：检测结果到达全部四条边和四个角。
5. **极角误差页**：误差一直到最宽的角度都保持平坦。
6. **Obs. graph（观测图）页**：两台相机通过共同观测相连。
7. **基线**：cam1 的 `T_cn_cnm1` 中的平移量与你用卡尺测得的镜头间距相符。

各页和各行的说明在 [Kalibr 文件参考](https://egocam.ai/zh-cn/kalibr/kalibr-file-reference/)。

**如果某项检查不通过**：误差向边缘上升，或者那里没有角点，就带上边缘覆盖重新录制，或者换一个鱼眼模型试试。基线与其他每个平移量偏差相同的百分比，就重新测量标定板。一次只改一样东西，然后重新求解。

### 第 8 步：再标定一次并比较

在同样的设置下录制第二个独立的序列，并用同样的方法标定它。根据我们与业内人士的交流，在两次良好的录制之间变动很大的值，说明哪一次都没有把它确定好（[Kalibr 工作流程，第 9 步](https://egocam.ai/zh-cn/kalibr/kalibr-workflow/)）。以像素比较两次标定，不是逐个参数比较：高阶畸变系数可以大幅摆动，而投影几乎完全相同（[评判一次标定，检查 4](https://egocam.ai/zh-cn/calibration/judging-a-calibration/)）。[提示词页面](https://egocam.ai/zh-cn/university/c201/prompts/)有一条提示词可以写出这个比较脚本。

如果你的相机发布实时的 ROS 话题，`kalibr_camera_validator` 会在实时图像上显示重投影误差，包括每台相机的和相机之间的（[标定验证工具](https://github.com/ethz-asl/kalibr/wiki/calibration-validator)）：

```bash
kalibr_camera_validator --cam camchain.yaml --target target.yaml
```

### 第 9 步：对照已知几何检查

- **直线**：对一帧图像边界附近有直边的场景做去畸变；它们出来必须是直的（[评判一次标定，检查 5](https://egocam.ai/zh-cn/calibration/judging-a-calibration/)）。
- **已知标定板上的深度**：如果你运行双目深度，把它与由一台相机求解出的标定板位姿比较。错误的标定给出的深度图看起来清晰，但在尺度和形状上有变形（[检查 6](https://egocam.ai/zh-cn/calibration/judging-a-calibration/)）。

### 第 10 步：签字验收并存档

过一遍[检查清单](https://egocam.ai/zh-cn/university/c201/checklist/)的签字验收部分。然后把标定和数据存放在一起：有版本管理，并与设备的序列号绑定，这样处理流程永远不会用别的设备的数字去处理素材（[相机标定](https://egocam.ai/zh-cn/calibration/camera-calibration/)）。把 `target.yaml`、结果文件和报告和它放在一起保存。

## B 部分（可选）：用 mrcal 评判内参

mrcal 报告投影不确定度，并支持交叉验证，[第 4 课](https://egocam.ai/zh-cn/university/c201/lesson-4-reading-the-result/)称这些检查是最有力的。Kalibr 的鱼眼结果不能为此导入 mrcal：`mrcal-from-kalibr` 只支持 Kalibr 的针孔相机配 radtan 畸变或无畸变（[它的文档](https://github.com/dkogan/mrcal/blob/master/mrcal-from-kalibr)）。所以 B 部分是在 mrcal 中单独做的一次标定，有它自己的标定板和录制。这里的一切都来自 mrcal 的 [how-to-calibrate 指南](https://mrcal.secretsauce.net/how-to-calibrate.html)和[安装页面](https://mrcal.secretsauce.net/install.html)。

### B1：安装

在 Debian 12 或 Ubuntu 22.04 及更高版本上，安装页面给出：

```bash
apt install mrcal libmrcal-dev python3-mrcal
```

棋盘格角点检测器 mrgingham 是一个单独的软件包：`apt install mrgingham`。

### B2：标定板和录制

mrcal 推荐棋盘格配 mrgingham 检测器；mrgingham 的文档提供了一份 14 × 14 棋盘格的 PDF。把它打印出来，平整地装好，并测量角点间距。mrgingham 只报告完整的标定板，所以在往图像边缘够的时候要看着实时画面。

图像必须在各相机之间同步。把它们命名为 `frameFFF-cameraCCC.png`：`FFF` 相同的图像被视为在同一时刻拍摄，`CCC` 标识相机。录制两轮独立的标定板运动（dance），分别放进两个文件夹，用于 B4 中的交叉验证。

### B3：标定

用指南的公式估计一个起始焦距：f ≈ 成像器宽度（像素）÷ (4 · tan(水平视场角 ÷ 4))。然后在每一轮运动的文件夹里，用你的值运行指南的命令，每台相机一个 glob：

```bash
mrcal-calibrate-cameras                                                         \
  --corners-cache corners.vnl                                                   \
  --lensmodel LENSMODEL_SPLINED_STEREOGRAPHIC_order=3_Nx=30_Ny=18_fov_x_deg=[FOV] \
  --focal [FOCAL_PX]                                                            \
  --object-spacing [MEASURED_SPACING_M]                                         \
  --object-width-n 14                                                           \
  'frame*-camera0.png' 'frame*-camera1.png'
```

**你应当看到**写出了 `camera-0.cameramodel` 和 `camera-1.cameramodel`。如果 `corners.vnl` 不存在，工具会先运行 mrgingham 并写出它。

**如果失败**：指南说明，没有可用的共同视野时外参是没有定义的，求解器会抱怨 Hessian "not positive definite"（意为：非正定）。多录一些两台相机共同看到的视图。

### B4：不确定度和交叉验证

对每台相机，画出投影不确定度图：

```bash
mrcal-show-projection-uncertainty camera-0.cameramodel
```

在不确定度差的地方，指南的建议是 "you need more chessboard observations in that area."（意为：你需要在那个区域有更多的棋盘格观测。）然后比较两轮运动得到的同一台相机的模型：

```bash
mrcal-show-projection-diff [dance1]/camera-0.cameramodel [dance2]/camera-0.cameramodel
```

**你应当看到**差异大约是两个不确定度之和。远大于此就指向模型误差（[mrcal 交叉验证](https://mrcal.secretsauce.net/tour-cross-validation.html)）。要找出原因，就像指南演示的那样，查看拟合得最差的观测：

```bash
mrcal-show-residuals-board-observation \
  --from-worst                         \
  --vectorscale 100                    \
  camera-0.cameramodel                 \
  0-5
```

指南用它根据残差的图样来识别检测器误差、卷帘快门、同步误差和未建模的标定板形状。

## 参考来源

- Kalibr wiki，ETH Zurich ASL：[installation](https://github.com/ethz-asl/kalibr/wiki/installation)、[calibration targets](https://github.com/ethz-asl/kalibr/wiki/calibration-targets)、[multiple-camera calibration](https://github.com/ethz-asl/kalibr/wiki/multiple-camera-calibration)、[bag format](https://github.com/ethz-asl/kalibr/wiki/bag-format)、[ROS 2 calibration](https://github.com/ethz-asl/kalibr/wiki/ROS2-Calibration-Using-Kalibr)、[camera focus](https://github.com/ethz-asl/kalibr/wiki/camera-focus)、[calibration validator](https://github.com/ethz-asl/kalibr/wiki/calibration-validator)。
- Kalibr 源代码，[github.com/ethz-asl/kalibr](https://github.com/ethz-asl/kalibr)（commit `1f60227`）：`kalibr_calibrate_cameras` 和 `kalibr_create_target_pdf` 的选项。
- ROS wiki：[rosbag command line](https://wiki.ros.org/rosbag/Commandline)。
- Kogan, D. mrcal：[how to calibrate](https://mrcal.secretsauce.net/how-to-calibrate.html)、[install](https://mrcal.secretsauce.net/install.html)、[cross-validation](https://mrcal.secretsauce.net/tour-cross-validation.html)，以及 [mrcal-from-kalibr](https://github.com/dkogan/mrcal/blob/master/mrcal-from-kalibr) 的源代码。
- 实用指南：[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/targets-and-calibration-sequences/)、[评判一次标定](https://egocam.ai/zh-cn/calibration/judging-a-calibration/)、[相机标定](https://egocam.ai/zh-cn/calibration/camera-calibration/)。
