opencvC++的前后左右四路相机标定,标定结束之后并保存标定结果的代码
时间: 2023-08-21 08:07:50 浏览: 101
以下是OpenCV C++的前后左右四路相机标定,并保存标定结果的代码示例:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>
using namespace cv;
using namespace std;
int main()
{
// 定义存储图像和角点的向量
vector<vector<vector<Point2f>>> imagePoints(4);
vector<vector<vector<Point3f>>> objectPoints(4);
// 定义棋盘格尺寸和格点数
Size boardSize = Size(9, 6);
int boardPoints = boardSize.width * boardSize.height;
// 定义相机内参矩阵和畸变系数
vector<Mat> cameraMatrix(4), distCoeffs(4);
for (int i = 0; i < 4; i++)
{
cameraMatrix[i] = Mat::eye(3, 3, CV_64F);
distCoeffs[i] = Mat::zeros(8, 1, CV_64F);
}
// 获取图像文件名
vector<String> filenames[4];
glob("image_dir/front/*.jpg", filenames[0]);
glob("image_dir/rear/*.jpg", filenames[1]);
glob("image_dir/left/*.jpg", filenames[2]);
glob("image_dir/right/*.jpg", filenames[3]);
// 循环读取图像并提取角点
for (int i = 0; i < 4; i++)
{
for (size_t j = 0; j < filenames[i].size(); j++)
{
Mat image = imread(filenames[i][j]);
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[i].push_back(corners);
vector<Point3f> obj;
for (int k = 0; k < boardPoints; k++)
{
obj.push_back(Point3f(k / boardSize.width, k % boardSize.width, 0.0f));
}
objectPoints[i].push_back(obj);
}
}
}
// 标定相机
vector<Mat> rvecs[4], tvecs[4];
for (int i = 0; i < 4; i++)
{
calibrateCamera(objectPoints[i], imagePoints[i], Size(640, 480), cameraMatrix[i], distCoeffs[i], rvecs[i], tvecs[i]);
}
// 保存相机内参矩阵和畸变系数
FileStorage fs("calib_results.xml", FileStorage::WRITE);
for (int i = 0; i < 4; i++)
{
string name = "cameraMatrix" + to_string(i);
fs << name << cameraMatrix[i];
name = "distCoeffs" + to_string(i);
fs << name << distCoeffs[i];
}
fs.release();
return 0;
}
```
以上代码中,我们使用了一个三维向量imagePoints和一个三维向量objectPoints来存储四路相机的图像和角点。在循环读取图像并提取角点时,我们使用了四个glob()函数来获取每个相机的图像文件名。接着,我们使用一个外层循环来遍历四个相机,内层循环遍历每张图像,提取角点,并将其存储在相应的三维向量中。最后,我们使用一个外层循环来遍历四个相机,调用calibrateCamera()函数对相机进行标定,并计算出相机的内参矩阵和畸变系数。最后,我们使用FileStorage类保存标定结果为xml格式文件。
阅读全文