读OpenCV自带的标定例程“calibration.cpp”感想

    为了更好地了解OpenCV的相机标定功能和使用已经标定的数据进行相机的畸变校正,我把OpenCV的例程“calibration.cpp”从头到尾重新读了一遍,并进行了一些基本的注释,来增加这个代码的可读性。

    OpenCV自带了很多例程,但由于是注释是英文编写,且注释很少,导致初学者学习很不容易。

    为了使用“标定”这个功能,我查阅了很多CSDN博客和百度等,终于按照一些前辈的方法把这个标定功能跑起来并得到了结果。然而,并不是很懂这个功能里面的具体方法,也就是对这个功能还处于“黑箱”的认识状态。好歹OpenCV也是个“open”开源的东西,不读一读学习一下似乎有点浪费。因此我也就沉下心来,耐心读了一下,并做了力所能及的注释。

    通过这篇博文,希望能对之前读这个例程的过程进行一个简单的总结。

                                                                          1. 使用命令行输入main()函数的参数

    刚看到这样一个500多行的程序时,我作为一个小白,是有一点忌惮的,感觉摸不到头脑。里面出现了大段不认识的符号(不认识,不是因为太难,而是因为我的知识面太窄。。。),尤其是一开始发现这个程序跟以前在C++教程里见到的开头进行参数声明的函数完全不同,直接把源文件“calibration.cpp”放进Visual Studio新建的C++project里面也不能直接运行出结果。后来才明白,这个源文件,是需要生成一个“exe”文件,再放入CMD命令行界面,再补充一些必须参数执行的。

    因为,“标定”这一功能的实现,可以有多种实现方式,也可以有多种数据来源。比如,本程序,就提供了“棋盘标定板”、“圆点标定板”和“非对称圆点标定板”三种标定板的模式供选择。而且,标定板中的特征点的数目、图片的尺寸等各种参数(这里就不具体一一列举了)都可以根据具体的情况进行选择,保证各种场景下的标定任务都可以通过这个标定程序来完成。

    为了实现一个可订制参数如此多的功能,直接让用户进入源程序去更改参数似乎非常复杂,而且容易造成混乱。因此,该例程就使用了“先呼出CMD命令行界面,再让用户自己输入自定义标定框架”的方式来实现功能的初始化。

    首先,设置一个带参数的main函数,再声明各个参数变量,调用命令行界面的输入系统,让用户根据提前准备好的帮助文档(使用字符串常量显示在屏幕上)输入参数。

int main( int argc, char** argv )
 cv::CommandLineParser parser(argc, argv,                           //进入命令行界面,要求输入一些基本参数,例如-w -h等。
 "{help ||}{w||}{h||}{pt|chessboard|}{n|10|}{d|1000|}{s|1|}{o|out_camera_data.yml|}"
 "{op||}{oe||}{zt||}{a|1|}{p||}{v||}{V||}{su||}"
 "{@input_data|0|}");

    我们可以记住这个方法,在以后编写类似的“需要用户输入多个参数”的功能时,借鉴这个呼出命令行,给main函数直接输入参数的方法。

                                                                           2. 分清主函数和子函数

    本例程的主函数大约是从第300行到570行左右,而前面的300行都是主函数中用到的一些子函数,其中一些子函数还调用了其余的子函数。分清子各个函数的功能,并在主函数中一一找出他们的位置,能帮助我们更快地理清整个例程的思路。下面我就把我注释过的例程放在下面。(程序较长,也可以直接跳过程序看后文)

#include "opencv2/core.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"

#include <cctype>
#include <stdio.h>
#include <string.h>
#include <time.h>

using namespace cv;
using namespace std;

   ///****************************************************** 1. 一些帮助文字************************************//

const char * usage =
" \nexample command line for calibration from a live feed.\n"
"   calibration  -w=4 -h=5 -s=0.025 -o=camera.yml -op -oe\n"
" \n"
" example command line for calibration from a list of stored images:\n"
"   imagelist_creator image_list.xml *.png\n"
"   calibration -w=4 -h=5 -s=0.025 -o=camera.yml -op -oe image_list.xml\n"
" where image_list.xml is the standard OpenCV XML/YAML\n"
" use imagelist_creator to create the xml or yaml list\n"
" file consisting of the list of strings, e.g.:\n"
" \n"
"<?xml version=\"1.0\"?>\n"
"<opencv_storage>\n"
"<images>\n"
"view000.png\n"
"view001.png\n"
"<!-- view002.png -->\n"
"view003.png\n"
"view010.png\n"
"one_extra_view.jpg\n"
"</images>\n"
"</opencv_storage>\n";




const char* liveCaptureHelp =
    "When the live video from camera is used as input, the following hot-keys may be used:\n"
        "  <ESC>, 'q' - quit the program\n"
        "  'g' - start capturing images\n"
        "  'u' - switch undistortion on/off\n";

static void help()
{
    printf( "This is a camera calibration sample.\n"
        "Usage: calibration\n"
        "     -w=<board_width>         # the number of inner corners per one of board dimension\n"
        "     -h=<board_height>        # the number of inner corners per another board dimension\n"
        "     [-pt=<pattern>]          # the type of pattern: chessboard or circles' grid\n"
        "     [-n=<number_of_frames>]  # the number of frames to use for calibration\n"
        "                              # (if not specified, it will be set to the number\n"
        "                              #  of board views actually available)\n"
        "     [-d=<delay>]             # a minimum delay in ms between subsequent attempts to capture a next view\n"
        "                              # (used only for video capturing)\n"
        "     [-s=<squareSize>]       # square size in some user-defined units (1 by default)\n"
        "     [-o=<out_camera_params>] # the output filename for intrinsic [and extrinsic] parameters\n"
        "     [-op]                    # write detected feature points\n"
        "     [-oe]                    # write extrinsic parameters\n"
        "     [-zt]                    # assume zero tangential distortion\n"
        "     [-a=<aspectRatio>]      # fix aspect ratio (fx/fy)\n"
        "     [-p]                     # fix the principal point at the center\n"
        "     [-v]                     # flip the captured images around the horizontal axis\n"
        "     [-V]                     # use a video file, and not an image list, uses\n"
        "                              # [input_data] string for the video file name\n"
        "     [-su]                    # show undistorted images after calibration\n"
        "     [input_data]             # input data, one of the following:\n"
        "                              #  - text file with a list of the images of the board\n"
        "                              #    the text file can be generated with imagelist_creator\n"
        "                              #  - name of video file with a video of the board\n"
        "                              # if input_data not specified, a live view from the camera is used\n"
        "\n" );
    printf("\n%s",usage);
    printf( "\n%s", liveCaptureHelp );
}

enum { DETECTION = 0, CAPTURING = 1, CALIBRATED = 2 };   //检测?获取?标定?
enum Pattern { CHESSBOARD, CIRCLES_GRID, ASYMMETRIC_CIRCLES_GRID };    ///棋盘的类型有三种


//**********************************************************************2. 计算投影偏差******************************************************/

static double computeReprojectionErrors(   
        const vector<vector<Point3f> >& objectPoints,
        const vector<vector<Point2f> >& imagePoints,
        const vector<Mat>& rvecs, const vector<Mat>& tvecs,
        const Mat& cameraMatrix, const Mat& distCoeffs,
        vector<float>& perViewErrors )
{
    vector<Point2f> imagePoints2;
    int i, totalPoints = 0;
    double totalErr = 0, err;
    perViewErrors.resize(objectPoints.size());

    for( i = 0; i < (int)objectPoints.size(); i++ )
    {
        projectPoints(Mat(objectPoints[i]), rvecs[i], tvecs[i],
                      cameraMatrix, distCoeffs, imagePoints2);
        err = norm(Mat(imagePoints[i]), Mat(imagePoints2), NORM_L2);
        int n = (int)objectPoints[i].size();
        perViewErrors[i] = (float)std::sqrt(err*err/n);
        totalErr += err*err;
        totalPoints += n;
    }

    return std::sqrt(totalErr/totalPoints);
}




 //**********************************************************************3. 计算棋盘角点******************************************************/

static void calcChessboardCorners(Size boardSize, float squareSize, vector<Point3f>& corners, Pattern patternType = CHESSBOARD)   
{
    corners.resize(0);

    switch(patternType)
    {
      case CHESSBOARD:
      case CIRCLES_GRID:
        for( int i = 0; i < boardSize.height; i++ )
            for( int j = 0; j < boardSize.width; j++ )
                corners.push_back(Point3f(float(j*squareSize),
                                          float(i*squareSize), 0));
        break;

      case ASYMMETRIC_CIRCLES_GRID:
        for( int i = 0; i < boardSize.height; i++ )
            for( int j = 0; j < boardSize.width; j++ )
                corners.push_back(Point3f(float((2*j + i % 2)*squareSize),
                                          float(i*squareSize), 0));
        break;

      default:
        CV_Error(Error::StsBadArg, "Unknown pattern type\n");
    }
}

//**********************************************************************4. 运行标定******************************************************/


static bool runCalibration( vector<vector<Point2f> > imagePoints,          ///////标定函数的返回值为布尔类型。
                    Size imageSize, Size boardSize, Pattern patternType,
                    float squareSize, float aspectRatio,
                    int flags, Mat& cameraMatrix, Mat& distCoeffs,
                    vector<Mat>& rvecs, vector<Mat>& tvecs,
                    vector<float>& reprojErrs,
                    double& totalAvgErr)
{
    cameraMatrix = Mat::eye(3, 3, CV_64F);
    if( flags & CALIB_FIX_ASPECT_RATIO )
        cameraMatrix.at<double>(0,0) = aspectRatio;

    distCoeffs = Mat::zeros(8, 1, CV_64F);

    vector<vector<Point3f> > objectPoints(1);
    calcChessboardCorners(boardSize, squareSize, objectPoints[0], patternType);

    objectPoints.resize(imagePoints.size(),objectPoints[0]);

    double rms = calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix,   ///调用了calibrateCamera函数,该函数是一个OpenCV自带的函数。
                    distCoeffs, rvecs, tvecs, flags|CALIB_FIX_K4|CALIB_FIX_K5);
                    ///*|CALIB_FIX_K3*/|CALIB_FIX_K4|CALIB_FIX_K5);
    printf("RMS error reported by calibrateCamera: %g\n", rms);

    bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs);

    totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints,   ////此处调用了computeReprojectionErrors函数,是第2个步骤的函数。
                rvecs, tvecs, cameraMatrix, distCoeffs, reprojErrs);

    return ok;
}



//**********************************************************************5. 保存相机参数******************************************************/

static void saveCameraParams( const string& filename,   
                       Size imageSize, Size boardSize,
                       float squareSize, float aspectRatio, int flags,
                       const Mat& cameraMatrix, const Mat& distCoeffs,
                       const vector<Mat>& rvecs, const vector<Mat>& tvecs,
                       const vector<float>& reprojErrs,
                       const vector<vector<Point2f> >& imagePoints,
                       double totalAvgErr )
{
    FileStorage fs( filename, FileStorage::WRITE );     ////fs是一个类变量,类是“FileStorage”。通过constructor,将初始化设定为“写”类型。

    time_t tt;
    time( &tt );
    struct tm *t2 = localtime( &tt );
    char buf[1024];
    strftime( buf, sizeof(buf)-1, "%c", t2 );

    fs << "calibration_time" << buf;    ///把电脑的系统时间记录下来存入文件

    if( !rvecs.empty() || !reprojErrs.empty() )
        fs << "nframes" << (int)std::max(rvecs.size(), reprojErrs.size());   ///把图片数量存入文件
    fs << "image_width" << imageSize.width;   ///图片宽度
    fs << "image_height" << imageSize.height;   ///图片高度
    fs << "board_width" << boardSize.width;   ///板宽
    fs << "board_height" << boardSize.height;   ///板高
    fs << "square_size" << squareSize;   ///方形尺寸

    if( flags & CALIB_FIX_ASPECT_RATIO )
        fs << "aspectRatio" << aspectRatio;  ///x与y方向焦距比例

    if( flags != 0 )
    {
        sprintf( buf, "flags: %s%s%s%s",
            flags & CALIB_USE_INTRINSIC_GUESS ? "+use_intrinsic_guess" : "",
            flags & CALIB_FIX_ASPECT_RATIO ? "+fix_aspectRatio" : "",
            flags & CALIB_FIX_PRINCIPAL_POINT ? "+fix_principal_point" : "",
            flags & CALIB_ZERO_TANGENT_DIST ? "+zero_tangent_dist" : "" );
        //cvWriteComment( *fs, buf, 0 );
    }

    fs << "flags" << flags;     ///文件输出

    fs << "camera_matrix" << cameraMatrix;     ///文件输出
    fs << "distortion_coefficients" << distCoeffs;      ///文件输出

    fs << "avg_reprojection_error" << totalAvgErr;      ///文件输出
    if( !reprojErrs.empty() )
        fs << "per_view_reprojection_errors" << Mat(reprojErrs);       ///文件输出

    if( !rvecs.empty() && !tvecs.empty() )
    {
        CV_Assert(rvecs[0].type() == tvecs[0].type());
        Mat bigmat((int)rvecs.size(), 6, rvecs[0].type());
        for( int i = 0; i < (int)rvecs.size(); i++ )
        {
            Mat r = bigmat(Range(i, i+1), Range(0,3));
            Mat t = bigmat(Range(i, i+1), Range(3,6));

            CV_Assert(rvecs[i].rows == 3 && rvecs[i].cols == 1);
            CV_Assert(tvecs[i].rows == 3 && tvecs[i].cols == 1);
            //*.t() is MatExpr (not Mat) so we can use assignment operator
            r = rvecs[i].t();
            t = tvecs[i].t();
        }
        //cvWriteComment( *fs, "a set of 6-tuples (rotation vector + translation vector) for each view", 0 );
        fs << "extrinsic_parameters" << bigmat;      ///文件输出
    }

    if( !imagePoints.empty() )
    {
        Mat imagePtMat((int)imagePoints.size(), (int)imagePoints[0].size(), CV_32FC2);
        for( int i = 0; i < (int)imagePoints.size(); i++ )
        {
            Mat r = imagePtMat.row(i).reshape(2, imagePtMat.cols);
            Mat imgpti(imagePoints[i]);
            imgpti.copyTo(r);
        }
        fs << "image_points" << imagePtMat;       ///文件输出
    }
}

//**********************************************************************6. 从图像列表里读图像文件******************************************************/


static bool readStringList( const string& filename, vector<string>& l )   ///从图像列表里读图像文件,返回值仅为真假。另外初始化字符串向量。
{
    l.resize(0);
    FileStorage fs(filename, FileStorage::READ);  ///建立一个类型是“文件存储(FileStorage)”的object,,名为fs,并初始化其读取功能。
    if( !fs.isOpened() )  //如果图像文件未打开,返回“false”
        return false;
    FileNode n = fs.getFirstTopLevelNode();  ///建立图像节点object,名为n,并将其初始化为第一行最左侧节点。
    if( n.type() != FileNode::SEQ )   ///如果图像节点类型不是SEQ(sequence),返回“false”
        return false;
    FileNodeIterator it = n.begin(), it_end = n.end();  ///建立图像节点迭代object,分别有一个开始和一个结束。
    for( ; it != it_end; ++it )
        l.push_back((string)*it);   ///push back字符串,相当于从文件中逐行取出图像文件的名称。
    return true;
}

//**********************************************************************7. 运行和保存******************************************************/


static bool runAndSave(const string& outputFilename,
                const vector<vector<Point2f> >& imagePoints,
                Size imageSize, Size boardSize, Pattern patternType, float squareSize,
                float aspectRatio, int flags, Mat& cameraMatrix,
                Mat& distCoeffs, bool writeExtrinsics, bool writePoints )
{
    vector<Mat> rvecs, tvecs;
    vector<float> reprojErrs;
    double totalAvgErr = 0;

    bool ok = runCalibration(imagePoints, imageSize, boardSize, patternType, squareSize,   ///运行标定   runCalibration是第四个步骤的函数。详情见上面第“4”步骤。
                   aspectRatio, flags, cameraMatrix, distCoeffs,
                   rvecs, tvecs, reprojErrs, totalAvgErr);
    printf("%s. avg reprojection error = %.2f\n",
           ok ? "Calibration succeeded" : "Calibration failed",
           totalAvgErr);

    if( ok )
        saveCameraParams( outputFilename, imageSize,              ///如果标定成功,保存相机参数。   saveCameraParams即是第五步的函数。详情见上面第“5”步骤。
                         boardSize, squareSize, aspectRatio,
                         flags, cameraMatrix, distCoeffs,
                         writeExtrinsics ? rvecs : vector<Mat>(),
                         writeExtrinsics ? tvecs : vector<Mat>(),
                         writeExtrinsics ? reprojErrs : vector<float>(),
                         writePoints ? imagePoints : vector<vector<Point2f> >(),
                         totalAvgErr );
    return ok;
}

//**********************************************************************以下为主函数******************************************************/


int main( int argc, char** argv )
{
	/**********************1.基本变量的声明**************************/

    Size boardSize, imageSize;  //Size变量:标定板尺寸、图像尺寸
    float squareSize, aspectRatio;   //浮点变量:方形尺寸、xy焦距比例
    Mat cameraMatrix, distCoeffs;   //图像变量:相机矩阵、畸变系数矩阵
    string outputFilename;  //输出文件的名称
    string inputFilename = "";   //输入文件的名称

    int i, nframes;
    bool writeExtrinsics, writePoints;  //布尔变量,是否写外参、是否写特征点
    bool undistortImage = false;   //是否是无畸变图像,默认值为“图像有畸变”
    int flags = 0;
    VideoCapture capture;
    bool flipVertical;   //是否做垂直方向翻转
    bool showUndistorted;  //是否展示校正后的图像
    bool videofile;  //是否是录像文件
    int delay;  //对于实时图像,延迟设为多长
    clock_t prevTimestamp = 0;  //初始化时间戳
    int mode = DETECTION;  //模式首先设置为“检测”
    int cameraId = 0;  //相机ID暂且设为0
    vector<vector<Point2f> > imagePoints;   //初始化图像点的二维指针向量?
    vector<string> imageList; //初始化字符串向量:图像列表
    Pattern pattern = CHESSBOARD;  //默认标定板是棋盘板(后期也可以通过cmd改为圆点板)

	/**********************2.进入命令行界面,要求用户输入标定的基本参数**************************/


    cv::CommandLineParser parser(argc, argv,                           //进入命令行界面,要求输入一些基本参数,例如-w -h等。
        "{help ||}{w||}{h||}{pt|chessboard|}{n|10|}{d|1000|}{s|1|}{o|out_camera_data.yml|}"
        "{op||}{oe||}{zt||}{a|1|}{p||}{v||}{V||}{su||}"
        "{@input_data|0|}");

	/**********************3.将用户输入的基本参数赋值给已经声明好的变量**************************/

    if (parser.has("help"))   //如果输入内容中有“帮助”字样,则显示帮助文档。在程序最前面。
    {
        help();
        return 0;
    }
    boardSize.width = parser.get<int>( "w" );   //将输入的-w值输入板子宽度
    boardSize.height = parser.get<int>( "h" );   //将输入的h值输入板子高度
    if ( parser.has("pt") )  //如果有“标定板类别”的输入,则进入类别输入判断,分别为:圆点阵列、不对称圆点阵列、棋盘阵列。如果不是以上三种,则输出“类型出错,必须使用棋盘或圆点阵列”。
    {
        string val = parser.get<string>("pt");
        if( val == "circles" )
            pattern = CIRCLES_GRID;
        else if( val == "acircles" )
            pattern = ASYMMETRIC_CIRCLES_GRID;
        else if( val == "chessboard" )
            pattern = CHESSBOARD;
        else
            return fprintf( stderr, "Invalid pattern type: must be chessboard or circles\n" ), -1;
    }
    squareSize = parser.get<float>("s");  //将输入的-s数据设为标定的“方形尺寸”
    nframes = parser.get<int>("n");  //输入标定图片的帧数
    aspectRatio = parser.get<float>("a");  //输入xy方向的焦距的比例
    delay = parser.get<int>("d");  //若使用实时图像,则其延迟设定为delay
    writePoints = parser.has("op");   //是否写特征点
    writeExtrinsics = parser.has("oe");   //是否写外参
    if (parser.has("a"))
        flags |= CALIB_FIX_ASPECT_RATIO;
    if ( parser.has("zt") )
        flags |= CALIB_ZERO_TANGENT_DIST;
    if ( parser.has("p") )
        flags |= CALIB_FIX_PRINCIPAL_POINT;
    flipVertical = parser.has("v");
    videofile = parser.has("V");
    if ( parser.has("o") )
        outputFilename = parser.get<string>("o");
    showUndistorted = parser.has("su");  //是否显示已经校正的图像
    if ( isdigit(parser.get<string>("@input_data")[0]) ) //根据输入数据的类型,抽取需要校正的图像:有实时图像的情况,和,只有图片列表的情况。
        cameraId = parser.get<int>("@input_data");
    else
        inputFilename = parser.get<string>("@input_data"); 
    if (!parser.check())
    {
        help();
        parser.printErrors();
        return -1;
    }
    if ( squareSize <= 0 )
        return fprintf( stderr, "Invalid board square width\n" ), -1;
    if ( nframes <= 3 )
        return printf("Invalid number of images\n" ), -1;
    if ( aspectRatio <= 0 )
        return printf( "Invalid aspect ratio\n" ), -1;
    if ( delay <= 0 )
        return printf( "Invalid delay\n" ), -1;
    if ( boardSize.width <= 0 )
        return fprintf( stderr, "Invalid board width\n" ), -1;
    if ( boardSize.height <= 0 )
        return fprintf( stderr, "Invalid board height\n" ), -1;


    if( !inputFilename.empty() )  //如果图像列表为空,则打开相机获取图像
    {
        if( !videofile && readStringList(inputFilename, imageList) )
            mode = CAPTURING;
        else
            capture.open(inputFilename);
    }
    else
        capture.open(cameraId);

    if( !capture.isOpened() && imageList.empty() ) //如果相机无法打开且图像列表为空,则报告“无法初始化相机”
        return fprintf( stderr, "Could not initialize video (%d) capture\n",cameraId ), -2;

    if( !imageList.empty() )   //如果图像列表非空,则获取图像列表的长度(size),作为标定图像的数量。
        nframes = (int)imageList.size();

    if( capture.isOpened() )   //如果相机打开,则显示实时相机帮助文档。
        printf( "%s", liveCaptureHelp );

    namedWindow( "Image View", 1 );  //打开一个窗口

    for(i = 0;;i++)  //此处未说明i变量的范围和for循环停止的条件。
    {
        Mat view, viewGray;  //声明图像view和viewGray
        bool blink = false;  //闪烁设为false

        if( capture.isOpened() )  //若相机打开了,则抓取图片并复制给图片变量view
        {
            Mat view0;
            capture >> view0;
            view0.copyTo(view);
        }
        else if( i < (int)imageList.size() )  //若相机没有打开,则从图片列表中按照索引号i来读取图片给图片变量view
            view = imread(imageList[i], 1);

        if(view.empty())   //如果图片变量view为空,则准备结束。
        {
            if( imagePoints.size() > 0 )  //图像点尺寸大于零,说明已经读取了所有的图像,可以执行运行和保存。
                runAndSave(outputFilename, imagePoints, imageSize,
                           boardSize, pattern, squareSize, aspectRatio,
                           flags, cameraMatrix, distCoeffs,
                           writeExtrinsics, writePoints);
            break;
        }

        imageSize = view.size();  //声明图像尺寸变量

        if( flipVertical )        //如果需要垂直方向翻转,则翻转
            flip( view, view, 0 );

        vector<Point2f> pointbuf;  //建立图像点缓存buffer
        cvtColor(view, viewGray, COLOR_BGR2GRAY);  //转换颜色,将图片变量view转化成灰阶图片存入图片viewGray当中

        bool found;
        switch( pattern )   //根据三种不同的标定板类别,分别进行特征点抓取,并将是否抓取到返回给found这个布尔变量。    其中抓取特征点的函数是三个比较复杂的opencv自带函数。
        {
            case CHESSBOARD:
                found = findChessboardCorners( view, boardSize, pointbuf,
                    CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_FAST_CHECK | CALIB_CB_NORMALIZE_IMAGE);
                break;
            case CIRCLES_GRID:
                found = findCirclesGrid( view, boardSize, pointbuf );
                break;
            case ASYMMETRIC_CIRCLES_GRID:
                found = findCirclesGrid( view, boardSize, pointbuf, CALIB_CB_ASYMMETRIC_GRID );
                break;
            default:
                return fprintf( stderr, "Unknown pattern type\n" ), -1;
        }

       // improve the found corners' coordinate accuracy
        if( pattern == CHESSBOARD && found) cornerSubPix( viewGray, pointbuf, Size(11,11),  //如果是棋盘类型的标定板,则继续使用“角点亚像素”改善精度。
            Size(-1,-1), TermCriteria( TermCriteria::EPS+TermCriteria::COUNT, 30, 0.1 ));

        if( mode == CAPTURING && found &&   //此部分工作在mode==CAPTURE的情况下。
           (!capture.isOpened() || clock() - prevTimestamp > delay*1e-3*CLOCKS_PER_SEC) )
        {
            imagePoints.push_back(pointbuf);
            prevTimestamp = clock();
            blink = capture.isOpened();
        }

        if(found)     //如果抓取特征点成功,则画出棋盘的角点。
            drawChessboardCorners( view, boardSize, Mat(pointbuf), found );

        string msg = mode == CAPTURING ? "100/100" :   //分两种情况:1.CAPTURE模式下,msg设为100/100。2.CALIBRATED模式下则给出“已经标定”或者“按下'g'开始”
            mode == CALIBRATED ? "Calibrated" : "Press 'g' to start";
        int baseLine = 0;  //设“基准线”=0
        Size textSize = getTextSize(msg, 1, 1, 1, &baseLine);
        Point textOrigin(view.cols - 2*textSize.width - 10, view.rows - 2*baseLine - 10);//给出文本的起点(textOrigin)指针

        if( mode == CAPTURING )  //CAPTURE模式下工作的内容
        {
            if(undistortImage)
                msg = format( "%d/%d Undist", (int)imagePoints.size(), nframes );
            else
                msg = format( "%d/%d", (int)imagePoints.size(), nframes );
        }

        putText( view, msg, textOrigin, 1, 1,  //在图像中放入文本文字(类似一个分数的图像序号,10/17这样,每成功抓取一幅图片的特征点,分子加1)
                 mode != CALIBRATED ? Scalar(0,0,255) : Scalar(0,255,0));

        if( blink )
            bitwise_not(view, view);

        if( mode == CALIBRATED && undistortImage )  //在CALIBRATED模式下且,显示已经校正的图像,则执行校正,函数为undistort(xx,xx,xx,xx)  该函数很重要!!!!
        {
            Mat temp = view.clone();  //克隆原图像view至暂存图像temp
            undistort(temp, view, cameraMatrix, distCoeffs);  //校正图像,并存放在view当中
        }

        imshow("Image View", view);   //显示已经校正过的图像。
        char key = (char)waitKey(capture.isOpened() ? 50 : 500);

        if( key == 27 )
            break;

        if( key == 'u' && mode == CALIBRATED )  //该部分可能用于校正畸变的反过程
            undistortImage = !undistortImage;

        if( capture.isOpened() && key == 'g' )
        {
            mode = CAPTURING;
            imagePoints.clear();
        }

        if( mode == CAPTURING && imagePoints.size() >= (unsigned)nframes )  //如果标定点的size大于标定图片的个数,即,已经标定结束了所有图片的标定,则进行模式改变:
        {
            if( runAndSave(outputFilename, imagePoints, imageSize,   //根据“运行与保存”这个函数的返回值,确定模式进入“CALIBRATED”或者“DETECTION”。
                       boardSize, pattern, squareSize, aspectRatio,
                       flags, cameraMatrix, distCoeffs,
                       writeExtrinsics, writePoints))
                mode = CALIBRATED;
            else
                mode = DETECTION;
            if( !capture.isOpened() )  //如果相机也没有打开,即,使用的是图片列表提供图片的标定方法,则跳出for循环。反之,如果是工作在相机实时采集图像的模式下,则可以重新返回,并进行下一次循环。
                break;
        }
    }

    if( !capture.isOpened() && showUndistorted )  //如果不工作在相机模式下,且需要显示已经校正过的图像,则执行以下内容。
    {
        Mat view, rview, map1, map2;
        initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(),  // 构建校正表格。initUndistortRectifyMap()这个函数很重要,它可以构建校正图像的查表,形成查表后,配合另一个remap()函数使用,可以提高校正图像的速度。
                                getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0),
                                imageSize, CV_16SC2, map1, map2);

        for( i = 0; i < (int)imageList.size(); i++ ) //循环读入图像列表中的所有图像,执行校正。
        {
            view = imread(imageList[i], 1); //读入图像到view变量
            if(view.empty())
                continue;
            //undistort( view, rview, cameraMatrix, distCoeffs, cameraMatrix );
            remap(view, rview, map1, map2, INTER_LINEAR);  //对view变量进行查表,查表为从map1->map2的映射关系,使用线性插值,输出图像为rview图像变量。
            imshow("Image View", rview);  //将校正得到的rview图像变量显示出来
            char c = (char)waitKey();  //等待按键,按键后对下一幅图进行校正和显示。 如果直接按键“Q或ESC”则直接退出。
            if( c == 27 || c == 'q' || c == 'Q' )
                break;
        }
    }

    return 0;
}

    我把子函数分成了7个,分别是:

1.一些帮助文字

2.计算投影偏差

3.计算棋盘角点

4.运行标定

5.保存相机参数

6.从图像列表里读取图像文件

7.运行和保存

    其中,“4.运行标定”还调用过“2.计算投影偏差”;“7.运行和保存”还调用过“4.运行标定”和“5.保存相机参数”。

    这样分析一下,就能够感受到这些子函数的层次感。

    即使不看主函数,大概也能猜到,整个例程的思路应该是:先读取图像,再运算标定算法,再保存标定结果。

    事实上,主函数也是按照这个顺序进行的,只不过,由于“标定”这个功能中有太多可以用户自定义的可选的参数,因此主函数中也为了实现各种方法而使用了很多分支,但整体思路仍然是“读取图像->运行标定->保存标定结果”。

    关于主函数,我主要总结以下几个要点。

1. 主函数提供了“相机实时获取图片并进行标定”和“通过图片列表文件读取已经拍摄的标定图片进行标定”两种方案,并在各个步骤中同时照顾两种方案的实现。主要通过“capture.isOpened()”这个函数来确定是否有可用相机。

2.主函数中使用了一个没有结束标志的for循环。这个循环只有在读取不到更多图片(图片列表文件模式)或相机停止工作时推出循环。退出循环时,imagePoints这个向量中已经装满了各个图片收集到的点,然后通过“7.运行和保存”实现标定。

3.标定并得到标定数据后,根据用户的设定,可以选择对之前输入的标定图片进行校正并输出,这样就可以看到我们的标定效果是不是足够好。

4.值得一提的是,本例程对校正功能进行了一定的优化。即,校正并不通过直接的校正函数undistort()来完成,而是通过校正函数生成一个查找表initUndistortRectifyMap(),再把需要校正的图放进查找表进行映射remap()。因为,查表的速度要快于校正的计算,对于大量的图片或者实时性要求高的场景来说,查表的计算量更划算一些。

undistort( view, rview, cameraMatrix, distCoeffs, cameraMatrix );
initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(),  // 构建校正表格。initUndistortRectifyMap()这个函数很重要,它可以构建校正图像的查表,形成查表后,配合另一个remap()函数使用,可以提高校正图像的速度。
                                getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0),
                                imageSize, CV_16SC2, map1, map2);
remap(view, rview, map1, map2, INTER_LINEAR);  //对view变量进行查表,查表为从map1->map2的映射关系,使用线性插值,输出图像为rview图像变量。
imshow("Image View", rview);  //将校正得到的rview图像变量显示出来
    以上就是该例程的一些简单的读后感和总结。更详细的内容,后面我会再找时间补充。



猜你喜欢

转载自blog.csdn.net/yibeiyese/article/details/80686194