基于opencv的多路相机的相机标定C++代码
时间: 2023-10-11 12:10:40 浏览: 120
以下是基于OpenCV的多路相机的相机标定的C++代码示例:
```cpp
#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
// 标定参数
int chessboardWidth = 9; // 棋盘格宽度
int chessboardHeight = 6; // 棋盘格高度
float chessboardSize = 0.02f; // 棋盘格尺寸,单位:米
Size chessboardSizeImg(chessboardWidth, chessboardHeight); // 棋盘格大小
vector<vector<Point3f>> objectPoints; // 三维点
vector<vector<Point2f>> imagePoints1, imagePoints2; // 左右相机的二维点
vector<Point3f> objectPointsBuffer;
vector<Point2f> corners1, corners2;
Mat img1, img2, gray1, gray2;
string imgPath1 = "left.png"; // 左相机图片路径
string imgPath2 = "right.png"; // 右相机图片路径
// 设置棋盘格的三维坐标
for (int i = 0; i < chessboardHeight; i++)
{
for (int j = 0; j < chessboardWidth; j++)
{
objectPointsBuffer.emplace_back(Point3f(j * chessboardSize, i * chessboardSize, 0));
}
}
// 读取图片
img1 = imread(imgPath1);
img2 = imread(imgPath2);
// 转为灰度图
cvtColor(img1, gray1, COLOR_BGR2GRAY);
cvtColor(img2, gray2, COLOR_BGR2GRAY);
// 查找棋盘格角点
bool found1 = findChessboardCorners(gray1, chessboardSizeImg, corners1, CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE + CALIB_CB_FAST_CHECK);
bool found2 = findChessboardCorners(gray2, chessboardSizeImg, corners2, CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE + CALIB_CB_FAST_CHECK);
// 如果两个相机都找到了棋盘格角点,则保存角点
if (found1 && found2)
{
objectPoints.emplace_back(objectPointsBuffer);
imagePoints1.emplace_back(corners1);
imagePoints2.emplace_back(corners2);
}
// 进行相机标定
Mat cameraMatrix1, cameraMatrix2, distCoeffs1, distCoeffs2, R, T, E, F;
stereoCalibrate(objectPoints, imagePoints1, imagePoints2, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, img1.size(), R, T, E, F);
// 打印结果
cout << "Camera Matrix 1: " << cameraMatrix1 << endl;
cout << "Distortion Coefficients 1: " << distCoeffs1 << endl;
cout << "Camera Matrix 2: " << cameraMatrix2 << endl;
cout << "Distortion Coefficients 2: " << distCoeffs2 << endl;
cout << "Rotation Matrix: " << R << endl;
cout << "Translation Vector: " << T << endl;
return 0;
}
```
注意,上述代码仅包含了相机标定的部分,实际开发中还需要考虑如何读取多个相机的图像数据、如何进行图像校正等问题。
阅读全文