编写opencv六路相机标定的C++代码
时间: 2023-07-07 08:20:56 浏览: 112
下面是使用OpenCV进行六路相机标定的C++代码示例:
```c++
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
// 设定棋盘格尺寸,这里假设棋盘格为 20mm x 20mm
const float square_size = 20.0f;
// 设定棋盘格内角点数量
const int board_width = 9;
const int board_height = 6;
const int board_size = board_width * board_height;
// 读入图像
vector<vector<Mat>> images;
for (int i = 0; i < 6; i++)
{
vector<Mat> img_vec;
for (int j = 0; j < 10; j++)
{
stringstream ss;
ss << "./data/" << i << "_" << j << ".jpg";
Mat img = imread(ss.str(), 0);
if (img.empty())
{
cerr << "Image not found: " << ss.str() << endl;
return -1;
}
img_vec.push_back(img);
}
images.push_back(img_vec);
}
// 计算内角点坐标
vector<Point3f> object_points;
for (int i = 0; i < board_height; i++)
{
for (int j = 0; j < board_width; j++)
{
object_points.push_back(Point3f(j * square_size, i * square_size, 0));
}
}
// 搜寻内角点
vector<vector<Point2f>> image_points;
for (int i = 0; i < 6; i++)
{
vector<Point2f> img_pts;
for (int j = 0; j < 10; j++)
{
Mat img = images[i][j];
vector<Point2f> corners;
bool found = findChessboardCorners(img, Size(board_width, board_height), corners);
if (found)
{
// 提高角点精度
cornerSubPix(img, corners, Size(11, 11), Size(-1, -1),
TermCriteria(TermCriteria::EPS + TermCriteria::MAX_ITER, 30, 0.1));
img_pts.insert(img_pts.end(), corners.begin(), corners.end());
}
}
image_points.push_back(img_pts);
}
// 执行标定
vector<Mat> rvecs, tvecs;
Mat K, D;
vector<vector<Point3f>> object_points_vec(6, object_points);
calibrateCamera(object_points_vec, image_points, images[0][0].size(), K, D, rvecs, tvecs,
CV_CALIB_ZERO_TANGENT_DIST | CV_CALIB_FIX_K4 | CV_CALIB_FIX_K5);
// 输出标定结果
cout << "K: \n" << K << endl;
cout << "D: \n" << D << endl;
for (int i = 0; i < 6; i++)
{
cout << "rvec" << i << ": \n" << rvecs[i] << endl;
cout << "tvec" << i << ": \n" << tvecs[i] << endl;
}
return 0;
}
```
这段代码假设读入了六个相机的十张棋盘格图像,图像文件名为 `./data/i_j.jpg`,其中 `i` 表示相机编号,`j` 表示图像编号。标定结果将输出相机的内参矩阵 `K`、畸变系数 `D`,以及每个相机的旋转向量 `rvec` 和平移向量 `tvec`。
阅读全文