windows单目相机标定代码opencv2.4 c++
时间: 2023-08-02 08:01:56 浏览: 212
在使用Windows操作系统下进行单目相机标定,可以使用OpenCV 2.4 C库提供的函数来实现。下面是一个简单的代码示例:
```c
#include <opencv2/opencv.hpp>
int main()
{
// 读取相机参数
cv::Mat cameraMatrix = cv::Mat::eye(3, 3, CV_64F); // 相机内参矩阵
cv::Mat distCoeffs = cv::Mat::zeros(5, 1, CV_64F); // 畸变系数向量
// 读取标定板图像
std::vector<cv::Mat> calibrationImages;
cv::Size boardSize(7, 6); // 标定板角点数
cv::Size imageSize; // 图像尺寸
// 依次读取标定图像并提取角点
for (int i = 1; i <= 20; ++i)
{
cv::Mat image;
image = cv::imread("calibration_images/" + std::to_string(i) + ".jpg", CV_LOAD_IMAGE_GRAYSCALE);
if (image.empty())
{
std::cout << "Failed to load calibration image: " << i << std::endl;
continue;
}
calibrationImages.push_back(image);
// 寻找角点
std::vector<cv::Point2f> corners;
bool found = cv::findChessboardCorners(image, boardSize, corners);
if (found)
{
cv::cornerSubPix(image, corners, cv::Size(11, 11), cv::Size(-1, -1),
cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 30, 0.1));
// 绘制角点
cv::drawChessboardCorners(image, boardSize, corners, found);
cv::imshow("Calibration image", image);
cv::waitKey(0);
}
else
{
std::cout << "Failed to find corners in image: " << i << std::endl;
}
imageSize = image.size();
}
// 进行相机标定
std::vector<std::vector<cv::Point2f>> imagePoints;
std::vector<std::vector<cv::Point3f>> objectPoints;
objectPoints.resize(calibrationImages.size(), std::vector<cv::Point3f>(0));
for (int i = 0; i < calibrationImages.size(); ++i)
{
for (int j = 0; j < boardSize.height; ++j)
{
for (int k = 0; k < boardSize.width; ++k)
{
objectPoints[i].push_back(cv::Point3f(j, k, 0));
}
}
imagePoints.push_back(std::vector<cv::Point2f>(0));
bool found = cv::findChessboardCorners(calibrationImages[i], boardSize, imagePoints[i]);
if (found)
{
cv::cornerSubPix(calibrationImages[i], imagePoints[i], cv::Size(11, 11), cv::Size(-1, -1),
cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 30, 0.1));
}
else
{
std::cout << "Failed to find corners in image: " << i + 1 << std::endl;
}
}
// 进行相机标定
cv::calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs);
// 输出标定结果
std::cout << "Camera matrix: " << std::endl << cameraMatrix << std::endl;
std::cout << "Distortion coefficients: " << std::endl << distCoeffs << std::endl;
return 0;
}
```
上述代码首先读取了一组标定板图像,然后通过`cv::findChessboardCorners`函数寻找标定板上的角点,并使用`cv::cornerSubPix`函数进行亚像素级角点精确化处理。接着,使用所得到的图像角点和已知的物体角点创建相机标定所需的输入数据。最后,调用`cv::calibrateCamera`函数进行相机标定,得到相机的内参矩阵和畸变系数向量。最后,输出标定结果。
请注意,上述代码只是一个简单的示例,并且假设输入图像序列已经按照一定的顺序命名并存储在`calibration_images`文件夹中。在实际应用中,您可能需要根据具体的情况进行适当的修改和调整。
阅读全文