用C++和opencv写一个相机标定代码
时间: 2024-04-30 19:22:27 浏览: 92
基于opencv&c++的相机标定
5星 · 资源好评率100%
以下是使用OpenCV进行相机标定的示例代码:
```c
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
int numBoards = 10; // 拍摄10张图片
int boardWidth = 9; // 棋盘格宽度为9个方格
int boardHeight = 6; // 棋盘格高度为6个方格
float squareSize = 0.02423f; // 单个方格的物理大小
Size boardSize(boardWidth, boardHeight);
vector<vector<Point3f>> objectPoints;
vector<vector<Point2f>> imagePoints;
vector<Point2f> corners;
Mat gray, img;
VideoCapture cap(0); // 创建相机对象
if (!cap.isOpened()) // 检查相机是否打开
{
cout << "Failed to open camera." << endl;
return -1;
}
namedWindow("Camera Calibration", WINDOW_NORMAL);
while (numBoards > 0)
{
cap >> img; // 从相机读取一帧图像
cvtColor(img, gray, COLOR_BGR2GRAY);
bool found = findChessboardCorners(gray, boardSize, corners,
CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_NORMALIZE_IMAGE);
if (found)
{
drawChessboardCorners(img, boardSize, corners, found);
vector<Point3f> obj;
for (int i = 0; i < boardHeight; i++)
{
for (int j = 0; j < boardWidth; j++)
{
obj.push_back(Point3f((float)j * squareSize, (float)i * squareSize, 0));
}
}
objectPoints.push_back(obj);
imagePoints.push_back(corners);
numBoards--;
}
imshow("Camera Calibration", img);
waitKey(1);
}
destroyWindow("Camera Calibration");
Mat cameraMatrix, distCoeffs;
vector<Mat> rvecs, tvecs;
calibrateCamera(objectPoints, imagePoints, gray.size(), cameraMatrix, distCoeffs, rvecs, tvecs);
cout << "Camera matrix:" << endl << cameraMatrix << endl;
cout << "Distortion coefficients:" << endl << distCoeffs << endl;
return 0;
}
```
在此代码中,我们首先定义了一些变量,包括要拍摄的图片数量,棋盘格的大小和单个方格的物理大小。然后,我们创建了一个相机对象,并检查是否成功打开了相机。接着,我们在一个循环中捕获相机图像,并使用`findChessboardCorners`函数检测棋盘格的角点。如果检测到了棋盘格,我们将角点保存到`imagePoints`向量中,并将对应的物理坐标保存到`objectPoints`向量中。当拍摄到足够多的图片后,我们使用`calibrateCamera`函数进行相机标定,并输出相机矩阵和畸变系数。
请注意,本示例代码仅用于演示目的。在实际应用中,可能需要更多的检测和校准步骤以获得更准确的结果。
阅读全文