#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
// 读取标定板图像
vector<vector<Point3f>> object_points; // 存储标定板上的三维坐标
vector<vector<Point2f>> image_points; // 存储图像上的二维坐标
Size board_size(6, 9); // 标定板角点数
float square_size = 30.0f; // 标定板方格大小,单位mm
Mat image, gray_image;
vector<Point2f> corners;
int success_count = 0;
for (int i = 0; i < 20; i++) {
string filename = "calibration" + to_string(i) + ".jpg";
image = imread(filename);
if (image.empty()) {
cout << "Failed to read image " << filename << endl;
continue;
}
cvtColor(image, gray_image, COLOR_BGR2GRAY);
bool found = findChessboardCorners(gray_image, board_size, corners,
CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_NORMALIZE_IMAGE);
if (found) {
cornerSubPix(gray_image, corners, Size(11, 11), Size(-1, -1),
TermCriteria(TermCriteria::EPS + TermCriteria::MAX_ITER, 30, 0.1));
drawChessboardCorners(image, board_size, corners, found);
imshow("Chessboard", image);
waitKey(100);
// 生成标定板上的三维坐标
vector<Point3f> object_corner;
for (int j = 0; j < board_size.height; j++) {
for (int k = 0; k < board_size.width; k++) {
object_corner.push_back(Point3f(j * square_size, k * square_size, 0));
}
}
object_points.push_back(object_corner);
image_points.push_back(corners);
success_count++;
} else {
cout << "Failed to find chessboard corners in image " << filename << endl;
}
}
destroyAllWindows();
// 进行相机标定
Mat camera_matrix, dist_coeffs;
vector<Mat> rvecs, tvecs;
calibrateCamera(object_points, image_points, Size(gray_image.cols, gray_image.rows),
camera_matrix, dist_coeffs, rvecs, tvecs);
// 输出标定结果
cout << "Camera matrix:" << endl << camera_matrix << endl;
cout << "Distortion coefficients:" << endl << dist_coeffs << endl;
return 0;
}
基于opencv的张正友标定法代码
最新推荐文章于 2024-05-16 05:05:15 发布