opencv读取图片c++,完成棋盘格标定完整代码
时间: 2023-07-09 22:27:08 浏览: 101
下面是一个完整的 OpenCV C++ 棋盘格标定的示例代码,包括读取图片、检测棋盘格角点、计算相机内参和畸变参数等步骤:
```
#include <opencv2/opencv.hpp>
int main()
{
// 棋盘格大小
cv::Size boardSize(9, 6);
// 棋盘格角点坐标
std::vector<cv::Point3f> objPoints;
for (int i = 0; i < boardSize.height; i++) {
for (int j = 0; j < boardSize.width; j++) {
objPoints.push_back(cv::Point3f(j, i, 0));
}
}
// 图像文件列表
std::vector<std::string> fileList = {"image1.jpg", "image2.jpg", "image3.jpg"};
// 图像角点坐标
std::vector<std::vector<cv::Point2f>> imgPoints;
// 读取每张图像,检测角点
for (const auto& fileName : fileList) {
// 读取图像
cv::Mat img = cv::imread(fileName);
// 转换为灰度图像
cv::Mat grayImg;
cv::cvtColor(img, grayImg, cv::COLOR_BGR2GRAY);
// 检测棋盘格角点
std::vector<cv::Point2f> corners;
bool found = cv::findChessboardCorners(grayImg, boardSize, corners);
if (found) {
// 亚像素精细化角点坐标
cv::cornerSubPix(grayImg, corners, cv::Size(11, 11), cv::Size(-1, -1),
cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::MAX_ITER, 30, 0.1));
// 显示检测到的角点
cv::drawChessboardCorners(img, boardSize, corners, found);
cv::imshow("Chessboard Corners", img);
cv::waitKey(0);
// 将角点坐标加入列表
imgPoints.push_back(corners);
}
else {
std::cout << "Cannot find chessboard corners in image " << fileName << std::endl;
}
}
// 计算相机内参和畸变参数
cv::Mat cameraMatrix, distCoeffs;
std::vector<cv::Mat> rvecs, tvecs;
double rms = cv::calibrateCamera(objPoints, imgPoints, cv::Size(grayImg.size()), cameraMatrix, distCoeffs, rvecs, tvecs);
// 输出相机内参和畸变参数
std::cout << "Camera matrix: " << cameraMatrix << std::endl;
std::cout << "Distortion coefficients: " << distCoeffs << std::endl;
return 0;
}
```
运行此程序,会依次读取 `image1.jpg`, `image2.jpg`, `image3.jpg` 三张图片,检测棋盘格角点,并计算相机内参和畸变参数。在检测到角点时,会在图像中显示角点,并等待用户按下任意键继续。在计算完成后,会输出相机内参和畸变参数的值。
阅读全文