opencv相机标定c++代码
时间: 2025-05-12 10:40:20 浏览: 15
### OpenCV相机标定C++代码示例
以下是基于Ubuntu 18.04环境下使用OpenCV进行相机标定的C++代码示例。此代码来源于官方示例路径 `/opencv-XXX/samples/cpp/tutorial_code/calib3d/camera_calibration`[^1]。
```cpp
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/calib3d.hpp"
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;
int main(int argc, char* argv[]) {
const Size boardSize = Size(9, 6); // 棋盘格内部角点数 (列数x行数)
bool showResults = true; // 是否显示结果图像
vector<vector<Point3f>> objectPoints(1);
for (int i = 0; i < boardSize.height; ++i) {
for (int j = 0; j < boardSize.width; ++j) {
objectPoints[0].push_back(Point3f((float)(j * 25), (float)(i * 25), 0));
}
}
vector<vector<Point2f>> imagePoints;
Mat img = imread("calibration_image.png", IMREAD_GRAYSCALE);
if (!img.data) {
cout << "Error loading the image!" << endl;
return -1;
}
bool found = findChessboardCorners(img, boardSize, noArray(), CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_NORMALIZE_IMAGE | CALIB_CB_FAST_CHECK);
if (found) {
drawChessboardCorners(img, boardSize, imagePoints.back(), found);
imshow("Calibration Image with Corners Detected", img);
waitKey();
} else {
cout << "Chessboard not detected." << endl;
return -1;
}
double rms = calibrateCamera(objectPoints, imagePoints, img.size(), Mat::eye(3, 3, CV_64F),
Mat::zeros(5, 1, CV_64F), noArray(), noArray(),
CALIB_FIX_K4 | CALIB_FIX_K5);
cout << "Re-projection error reported: " << rms << endl;
FileStorage fs("camera_params.yml", FileStorage::WRITE);
if (fs.isOpened()) {
fs << "camera_matrix" << Mat::eye(3, 3, CV_64F);
fs << "distortion_coefficients" << Mat::zeros(5, 1, CV_64F);
fs.release(); // 关闭文件存储对象
} else {
cout << "Failed to save camera parameters!" << endl;
return -1;
}
return 0;
}
```
上述代码实现了棋盘格模式下的相机标定功能,具体步骤如下:
- 定义棋盘格尺寸 `boardSize` 并初始化世界坐标系中的三维点集合。
- 加载用于标定的图片并检测其中是否存在棋盘格图案。
- 如果成功找到棋盘格,则计算内外参数并通过 RMS 值评估误差。
- 将标定得到的相机矩阵和畸变系数保存到 YAML 文件中以便后续使用。
更多细节可以参考 CSDN 博客上的说明文档[^2]以及实际操作指南。
#### 注意事项
如果需要进一步扩展至 Android 环境或其他模型训练场景,请注意额外依赖库的引入方式及其兼容性问题[^3]。
阅读全文
相关推荐


















