opencvC++的前后左右相机标定,标定结束之后并保存标定结果的代码
时间: 2023-08-21 09:07:50 浏览: 91
以下是OpenCV C++的前后左右相机标定,并保存标定结果的代码示例:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>
using namespace cv;
using namespace std;
int main()
{
// 定义存储图像和角点的向量
vector<vector<Point2f>> imagePoints;
vector<vector<Point3f>> objectPoints;
// 定义棋盘格尺寸和格点数
Size boardSize = Size(9, 6);
int boardPoints = boardSize.width * boardSize.height;
// 定义相机内参矩阵和畸变系数
Mat cameraMatrix = Mat::eye(3, 3, CV_64F);
Mat distCoeffs = Mat::zeros(8, 1, CV_64F);
// 获取图像文件名
vector<String> filenames;
glob("image_dir/*.jpg", filenames);
// 循环读取图像并提取角点
for (size_t i = 0; i < filenames.size(); i++)
{
Mat image = imread(filenames[i]);
vector<Point2f> corners;
bool found = findChessboardCorners(image, boardSize, corners);
if (found)
{
TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 30, 0.1);
cornerSubPix(image, corners, Size(11, 11), Size(-1, -1), criteria);
imagePoints.push_back(corners);
vector<Point3f> obj;
for (int j = 0; j < boardPoints; j++)
{
obj.push_back(Point3f(j / boardSize.width, j % boardSize.width, 0.0f));
}
objectPoints.push_back(obj);
}
}
// 标定相机
vector<Mat> rvecs, tvecs;
calibrateCamera(objectPoints, imagePoints, Size(640, 480), cameraMatrix, distCoeffs, rvecs, tvecs);
// 保存相机内参矩阵和畸变系数
FileStorage fs("calib_results.xml", FileStorage::WRITE);
fs << "cameraMatrix" << cameraMatrix;
fs << "distCoeffs" << distCoeffs;
fs.release();
return 0;
}
```
以上代码中,我们首先使用glob()函数获取指定目录下的所有图像文件名,然后使用循环读取每张图像并提取角点,存储在imagePoints和objectPoints向量中。接着,使用calibrateCamera()函数对相机进行标定,并计算出相机的内参矩阵和畸变系数。最后,我们使用FileStorage类保存标定结果为xml格式文件。
阅读全文