opencv像素标定C++
时间: 2025-06-03 21:49:40 浏览: 16
### OpenCV C++ 像素标定方法
在计算机视觉领域,像素标定通常指的是通过已知的物理世界坐标系与图像平面之间的映射关系来估计相机参数的过程。以下是使用OpenCV库实现单目相机标定的一个完整示例。
#### 1. 准备工作
为了完成相机标定,需要准备一组带有棋盘格图案的图片作为输入数据集。这些图片应覆盖不同的视角和位置,以便获得更准确的结果。代码中涉及的关键函数包括`findChessboardCorners()`用于检测角点,以及`calibrateCamera()`用于计算相机内参矩阵、畸变系数和其他几何参数[^2]。
#### 2. 完整代码示例
下面是一个完整的C++程序,展示如何利用OpenCV进行单目相机标定:
```cpp
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;
int main() {
// 设置棋盘格尺寸(内部交点数)
Size boardSize(9, 6);
// 存储所有图像中的对象点和图像点
vector<vector<Point3f>> objectPointsPerImage;
vector<vector<Point2f>> imagePointsPerImage;
// 创建真实世界的三维点模型
vector<Point3f> objPts;
for (int i = 0; i < boardSize.height; ++i) {
for (int j = 0; j < boardSize.width; ++j) {
objPts.emplace_back(Point3f(float(j), float(i), 0));
}
}
// 加载图像列表并提取角点
vector<String> filenames;
glob("./images/*.jpg", filenames);
Mat imgGray, imgColor;
bool found;
for (const auto& filename : filenames) {
imgColor = imread(filename, IMREAD_COLOR);
if (imgColor.empty()) continue;
cvtColor(imgColor, imgGray, COLOR_BGR2GRAY);
// 查找棋盘格角点
found = findChessboardCorners(imgGray, boardSize, imagePointsPerImage.back(),
CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_NORMALIZE_IMAGE | CALIB_CB_FAST_CHECK);
if (!found) continue;
cornerSubPix(imgGray, imagePointsPerImage.back(), Size(11, 11), Size(-1, -1),
TermCriteria(TermCriteria::EPS + TermCriteria::MAX_ITER, 30, 0.1));
drawChessboardCorners(imgColor, boardSize, imagePointsPerImage.back(), true);
imshow("Found Corners", imgColor);
waitKey(500);
objectPointsPerImage.push_back(objPts);
}
// 如果找到足够的有效图像,则继续标定过程
if (objectPointsPerImage.size() >= 10) {
Mat cameraMatrix, distCoeffs;
vector<Mat> rvecs, tvecs;
// 执行相机标定
double rms = calibrateCamera(objectPointsPerImage, imagePointsPerImage,
imgGray.size(), cameraMatrix, distCoeffs,
rvecs, tvecs, 0, TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON));
cout << "Re-projection error: " << rms << endl;
cout << "Camera matrix:\n" << cameraMatrix << endl;
cout << "Distortion coefficients:\n" << distCoeffs << endl;
} else {
cerr << "Not enough valid images to perform calibration." << endl;
}
return 0;
}
```
此代码实现了以下几个功能:
- 使用`glob()`加载指定目录下的所有图像文件。
- 调用`findChessboardCorners()`查找棋盘格角点,并调用`cornerSubPix()`进一步优化其精度[^2]。
- 利用`calibrateCamera()`估算相机内参矩阵、畸变系数以及其他必要的几何参数[^2]。
#### 3. 结果分析
最终输出结果包括重投影误差 RMS 值、相机内参矩阵 `cameraMatrix` 和畸变系数 `distCoeffs`。其中,RMS 是衡量标定质量的重要指标之一——越低表示拟合效果越好[^2]。
---
###
阅读全文
相关推荐


















