opencv4.6.0版本的用c++四个摄像头标定和去畸变,并保存标定参数以及使用畸变图像的代码
时间: 2024-03-08 18:50:34 浏览: 77
下面是使用C++进行四个摄像头标定和去畸变的示例代码。该代码使用OpenCV 4.6.0版本,可以标定四个摄像头,并保存标定参数以及使用畸变图像。
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;
int main()
{
vector<string> img_names{"img1.jpg", "img2.jpg", "img3.jpg", "img4.jpg"};
Size board_size{9, 6};
vector<vector<Point2f>> corners_all;
vector<Mat> rvecs_all, tvecs_all;
vector<Mat> cameraMatrix_all, distCoeffs_all;
vector<vector<Point3f>> object_points;
// 初始化棋盘格三维点坐标
vector<Point3f> object_points_one;
for (int i = 0; i < board_size.height; ++i) {
for (int j = 0; j < board_size.width; ++j) {
object_points_one.emplace_back(j, i, 0);
}
}
for (int i = 0; i < img_names.size(); ++i) {
Mat img = imread(img_names[i]);
vector<Point2f> corners;
// 寻找角点
bool found = findChessboardCorners(img, board_size, corners, CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE + CALIB_CB_FAST_CHECK);
if (found) {
Mat gray_img;
cvtColor(img, gray_img, COLOR_BGR2GRAY);
// 亚像素精确化
cornerSubPix(gray_img, corners, Size(5, 5), Size(-1, -1), TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 30, 0.1));
drawChessboardCorners(img, board_size, corners, found);
corners_all.emplace_back(corners);
object_points.emplace_back(object_points_one);
}
imshow("img", img);
waitKey();
}
// 标定
calibrateCameraRO(object_points, corners_all, Size(640, 480), 0, 0, rvecs_all, tvecs_all, CALIB_USE_INTRINSIC_GUESS | CALIB_FIX_K4 | CALIB_FIX_K5);
// 保存标定参数
for (int i = 0; i < img_names.size(); ++i) {
Mat cameraMatrix, distCoeffs;
FileStorage fs(img_names[i] + ".xml", FileStorage::WRITE);
fs << "camera_matrix" << rvecs_all[i];
fs << "distortion_coefficients" << tvecs_all[i];
fs.release();
cameraMatrix_all.push_back(cameraMatrix);
distCoeffs_all.push_back(distCoeffs);
}
// 去畸变并显示
for (int i = 0; i < img_names.size(); ++i) {
Mat img = imread(img_names[i]);
Mat cameraMatrix, distCoeffs;
FileStorage fs(img_names[i] + ".xml", FileStorage::READ);
fs["camera_matrix"] >> cameraMatrix;
fs["distortion_coefficients"] >> distCoeffs;
fs.release();
Mat img_undistorted;
undistort(img, img_undistorted, cameraMatrix, distCoeffs);
imshow("img_undistorted", img_undistorted);
waitKey();
}
return 0;
}
```
这段代码中,我们首先定义了待标定的图像文件名、棋盘格大小、角点坐标、相机内参、畸变系数等变量。然后,我们通过循环遍历所有图像,寻找角点并进行亚像素精确化。接着,我们使用 `calibrateCameraRO` 函数进行标定,该函数可以同时标定多个摄像头。最后,我们保存了每个摄像头的标定参数,并使用 `undistort` 函数将畸变图像进行去畸变并显示。
希望这段代码对您有所帮助。如果您有任何问题,请随时提出。
阅读全文