代码分为几个部分,c++部分使用g++进行编译
(1)双目摄像头标定图像数据集收集保存
//image_save.cpp
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
cv::VideoCapture capl(0);
cv::VideoCapture capr(1);
int i = 0;
cv::Mat cam_left;
cv::Mat cam_right;
char filename_l[15];
char filename_r[15];
while(capl.read(cam_left) && capr.read(cam_right))
{
cv::imshow("cam_left", cam_left);
cv::imshow("cam_right", cam_right);
char c = cv::waitKey(1);
char s[40];
if(c==' ') //按空格采集图像
{
sprintf(filename_l, "left%d.jpg",i);
imwrite(filename_l, cam_left);
sprintf(filename_r, "right%d.jpg",i++);
imwrite(filename_r, cam_right);
//printf(s, "%s%d%s\n", "the ",i++,"th image");
cout << "save the "<< i <<"th image\n"<< endl;
}
if(c=='q' || c=='Q') // 按q退出
{
break;
}
}
return 0;
}
显示结果
(2)单目标定
//calibration.cpp
#include <iostream>
#include <sstream>
#include <time.h>
#include <stdio.h>
#include <fstream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
#define calibration
int main()
{
#ifdef calibration
ifstream fin("right_img.txt"); /* 标定所用图像文件的路径 */
ofstream fout("caliberation_result_right.txt"); /* 保存标定结果的文件 */
// 读取每一幅图像,从中提取出角点,然后对角点进行亚像素精确化
int image_count = 0; /* 图像数量 */
Size image_size; /* 图像的尺寸 */
Size board_size = Size(11,8); /* 标定板上每行、列的角点数 */
vector<Point2f> image_points_buf; /* 缓存每幅图像上检测到的角点 */
vector<vector<Point2f>> image_points_seq; /* 保存检测到的所有角点 */
string filename; // 图片名
vector<string> filenames;
while (getline(fin, filename))
{
++image_count;
Mat imageInput = imread(filename);
filenames.push_back(filename);
// 读入第一张图片时获取图片大小
if (image_count == 1)
{
image_size.width = imageInput.cols;
image_size.height = imageInput.rows;
}
/* 提取角点 */
if (0 == findChessboardCorners(imageInput, board_size, image_points_buf))
{
//cout << "can not find chessboard corners!\n"; // 找不到角点
cout << "**" << filename << "** can not find chessboard corners!\n";
exit(1);
}
else
{
Mat view_gray;
cvtColor(imageInput, view_gray, CV_RGB2GRAY); // 转灰度图
/* 亚像素精确化 */
// image_points_buf 初始的角点坐标向量,同时作为亚像素坐标位置的输出
// Size(5,5) 搜索窗口大小
// (-1,-1)表示没有死区
// TermCriteria 角点的迭代过程的终止条件, 可以为迭代次数和角点精度两者的组合
cornerSubPix(view_gray, image_points_buf, Size(5, 5), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1));
image_points_seq.push_back(image_points_buf); // 保存亚像素角点
/* 在图像上显示角点位置 */
drawChessboardCorners(view_gray, board_size, image_points_buf, false); // 用于在图片中标记角点
imshow("Camera Calibration", view_gray); // 显示图片
waitKey(500); //暂停0.5S
}
}
int CornerNum = board_size.width * board_size.height; // 每张图片上总的角点数
//-------------以下是摄像机标定------------------
/*棋盘三维信息*/
Size square_size = Size(60, 60); /* 实际测量得到的标定板上每个棋盘格的大小 */
vector<vector<Point3f>> object_points; /* 保存标定板上角点的三维坐标 */
/*内外参数*/
Mat cameraMatrix = Mat(3, 3, CV_32FC1, Scalar::all(0)); /* 摄像机内参数矩阵 */
vector<int> point_counts; // 每幅图像中角点的数量
Mat distCoeffs = Mat(1, 5