相机标定-opencv

2023-11-01

相机标定采用的是opencv自带的标定文件。主要有下面几个文件:
(1)camera_calibration.cpp,这个文件就是生成标定参数的文件,前期准备好后,只需要运行这个文件就可以了。
(2) default.xml PS:有的opencv版本里不叫这个名字,叫in_VID5.xml,但内容是一样的,具体的需要查看camera_calibration.cpp文件中这个位置:
在这里插入图片描述在这里插入图片描述

这个文件中需要修改的是棋盘格内角点的数目,就是棋盘格的数量减1
square_size这个参数,实测无影响
(3)VID5.xml ,这个文件中保存了需要标定的棋盘格照片位置。
在这里插入图片描述
在标定前,应该对采集的棋盘格照片做一下增强,比如直方图均衡、对比度增强增强等,但是实测增强后的效果反而不好,不知道是什么原因,如有知道的大佬还请告知。
事后分析,对比了增强前后找到的角点位置,有一定差异,怀疑增强后的角点位置没找准,增强后连噪声一并增强了,应该再做一下去噪处理,但这个没有验证。

下面贴一下,对camera_calibration.cpp中相关函数的参数介绍和用法:

#include <iostream>
#include <sstream>
#include <string>
#include <ctime>
#include <cstdio>

#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>

using namespace cv;
using namespace std;

class Settings
{
public:
    Settings() : goodInput(false) {}
    enum Pattern { NOT_EXISTING, CHESSBOARD, CIRCLES_GRID, ASYMMETRIC_CIRCLES_GRID };
    enum InputType { INVALID, CAMERA, VIDEO_FILE, IMAGE_LIST };

    void write(FileStorage& fs) const                        //Write serialization for this class
    {
        fs << "{"
                  << "BoardSize_Width"  << boardSize.width
                  << "BoardSize_Height" << boardSize.height
                  << "Square_Size"         << squareSize
                  << "Calibrate_Pattern" << patternToUse
                  << "Calibrate_NrOfFrameToUse" << nrFrames
                  << "Calibrate_FixAspectRatio" << aspectRatio
                  << "Calibrate_AssumeZeroTangentialDistortion" << calibZeroTangentDist
                  << "Calibrate_FixPrincipalPointAtTheCenter" << calibFixPrincipalPoint

                  << "Write_DetectedFeaturePoints" << writePoints
                  << "Write_extrinsicParameters"   << writeExtrinsics
                  << "Write_gridPoints" << writeGrid
                  << "Write_outputFileName"  << outputFileName

                  << "Show_UndistortedImage" << showUndistorted

                  << "Input_FlipAroundHorizontalAxis" << flipVertical
                  << "Input_Delay" << delay
                  << "Input" << input
           << "}";
    }
    void read(const FileNode& node)                          //Read serialization for this class
    {
        node["BoardSize_Width" ] >> boardSize.width;
        node["BoardSize_Height"] >> boardSize.height;
        node["Calibrate_Pattern"] >> patternToUse;
        node["Square_Size"]  >> squareSize;
        node["Calibrate_NrOfFrameToUse"] >> nrFrames;
        node["Calibrate_FixAspectRatio"] >> aspectRatio;
        node["Write_DetectedFeaturePoints"] >> writePoints;
        node["Write_extrinsicParameters"] >> writeExtrinsics;
        node["Write_gridPoints"] >> writeGrid;
        node["Write_outputFileName"] >> outputFileName;
        node["Calibrate_AssumeZeroTangentialDistortion"] >> calibZeroTangentDist;
        node["Calibrate_FixPrincipalPointAtTheCenter"] >> calibFixPrincipalPoint;
        node["Calibrate_UseFisheyeModel"] >> useFisheye;
        node["Input_FlipAroundHorizontalAxis"] >> flipVertical;
        node["Show_UndistortedImage"] >> showUndistorted;
        node["Input"] >> input;
        node["Input_Delay"] >> delay;
        node["Fix_K1"] >> fixK1;
        node["Fix_K2"] >> fixK2;
        node["Fix_K3"] >> fixK3;
        node["Fix_K4"] >> fixK4;
        node["Fix_K5"] >> fixK5;

        validate();
    }
    void validate()
    {
        goodInput = true;
        if (boardSize.width <= 0 || boardSize.height <= 0)
        {
            cerr << "Invalid Board size: " << boardSize.width << " " << boardSize.height << endl;
            goodInput = false;
        }
        if (squareSize <= 10e-6)
        {
            cerr << "Invalid square size " << squareSize << endl;
            goodInput = false;
        }
        if (nrFrames <= 0)
        {
            cerr << "Invalid number of frames " << nrFrames << endl;
            goodInput = false;
        }

        if (input.empty())      // Check for valid input
                inputType = INVALID;
        else
        {
            if (input[0] >= '0' && input[0] <= '9')
            {
                stringstream ss(input);
                ss >> cameraID;
                inputType = CAMERA;
            }
            else
            {
                if (isListOfImages(input) && readStringList(input, imageList))
                {
                    inputType = IMAGE_LIST;
                    nrFrames = (nrFrames < (int)imageList.size()) ? nrFrames : (int)imageList.size();
                }
                else
                    inputType = VIDEO_FILE;
            }
            if (inputType == CAMERA)
                inputCapture.open(cameraID);
            if (inputType == VIDEO_FILE)
                inputCapture.open(input);
            if (inputType != IMAGE_LIST && !inputCapture.isOpened())
                    inputType = INVALID;
        }
        if (inputType == INVALID)
        {
            cerr << " Input does not exist: " << input;
            goodInput = false;
        }

        flag = 0;
        if(calibFixPrincipalPoint) flag |= CALIB_FIX_PRINCIPAL_POINT;
        if(calibZeroTangentDist)   flag |= CALIB_ZERO_TANGENT_DIST;
        if(aspectRatio)            flag |= CALIB_FIX_ASPECT_RATIO;
        if(fixK1)                  flag |= CALIB_FIX_K1;
        if(fixK2)                  flag |= CALIB_FIX_K2;
        if(fixK3)                  flag |= CALIB_FIX_K3;
        if(fixK4)                  flag |= CALIB_FIX_K4;
        if(fixK5)                  flag |= CALIB_FIX_K5;

        if (useFisheye) {
            // the fisheye model has its own enum, so overwrite the flags
            flag = fisheye::CALIB_FIX_SKEW | fisheye::CALIB_RECOMPUTE_EXTRINSIC;
            if(fixK1)                   flag |= fisheye::CALIB_FIX_K1;
            if(fixK2)                   flag |= fisheye::CALIB_FIX_K2;
            if(fixK3)                   flag |= fisheye::CALIB_FIX_K3;
            if(fixK4)                   flag |= fisheye::CALIB_FIX_K4;
            if (calibFixPrincipalPoint) flag |= fisheye::CALIB_FIX_PRINCIPAL_POINT;
        }

        calibrationPattern = NOT_EXISTING;
        if (!patternToUse.compare("CHESSBOARD")) calibrationPattern = CHESSBOARD;
        if (!patternToUse.compare("CIRCLES_GRID")) calibrationPattern = CIRCLES_GRID;
        if (!patternToUse.compare("ASYMMETRIC_CIRCLES_GRID")) calibrationPattern = ASYMMETRIC_CIRCLES_GRID;
        if (calibrationPattern == NOT_EXISTING)
        {
            cerr << " Camera calibration mode does not exist: " << patternToUse << endl;
            goodInput = false;
        }
        atImageList = 0;

    }
    Mat nextImage()
    {
        Mat result;
        if( inputCapture.isOpened() )
        {
            Mat view0;
            inputCapture >> view0;
            view0.copyTo(result);
        }
        else if( atImageList < imageList.size() )
            result = imread(imageList[atImageList++], IMREAD_COLOR);

        return result;
    }

    static bool readStringList( const string& filename, vector<string>& l )
    {
        l.clear();
        FileStorage fs(filename, FileStorage::READ);
        if( !fs.isOpened() )
            return false;
        FileNode n = fs.getFirstTopLevelNode();
        if( n.type() != FileNode::SEQ )
            return false;
        FileNodeIterator it = n.begin(), it_end = n.end();
        for( ; it != it_end; ++it )
            l.push_back((string)*it);
        return true;
    }

    static bool isListOfImages( const string& filename)
    {
        string s(filename);
        // Look for file extension
        if( s.find(".xml") == string::npos && s.find(".yaml") == string::npos && s.find(".yml") == string::npos )
            return false;
        else
            return true;
    }
public:
    Size boardSize;              // The size of the board -> Number of items by width and height
    Pattern calibrationPattern;  // One of the Chessboard, circles, or asymmetric circle pattern
    float squareSize;            // The size of a square in your defined unit (point, millimeter,etc).
    int nrFrames;                // The number of frames to use from the input for calibration
    float aspectRatio;           // The aspect ratio
    int delay;                   // In case of a video input
    bool writePoints;            // Write detected feature points
    bool writeExtrinsics;        // Write extrinsic parameters
    bool writeGrid;              // Write refined 3D target grid points
    bool calibZeroTangentDist;   // Assume zero tangential distortion
    bool calibFixPrincipalPoint; // Fix the principal point at the center
    bool flipVertical;           // Flip the captured images around the horizontal axis
    string outputFileName;       // The name of the file where to write
    bool showUndistorted;        // Show undistorted images after calibration
    string input;                // The input ->
    bool useFisheye;             // use fisheye camera model for calibration
    bool fixK1;                  // fix K1 distortion coefficient
    bool fixK2;                  // fix K2 distortion coefficient
    bool fixK3;                  // fix K3 distortion coefficient
    bool fixK4;                  // fix K4 distortion coefficient
    bool fixK5;                  // fix K5 distortion coefficient

    int cameraID;
    vector<string> imageList;
    size_t atImageList;
    VideoCapture inputCapture;
    InputType inputType;
    bool goodInput;
    int flag;

private:
    string patternToUse;


};

static inline void read(const FileNode& node, Settings& x, const Settings& default_value = Settings())
{
    if(node.empty())
        x = default_value;
    else
        x.read(node);
}

enum { DETECTION = 0, CAPTURING = 1, CALIBRATED = 2 };

bool runCalibrationAndSave(Settings& s, Size imageSize, Mat&  cameraMatrix, Mat& distCoeffs,
                           vector<vector<Point2f> > imagePoints, float grid_width, bool release_object);

int main(int argc, char* argv[])    
{
    ///OpenCV中CommandLineParse类主要是命令行解析类。主要目:方便用户在命令行使用过程中减少工作量。具体使用方式如下:
    const String keys
        = "{help h usage ? |           | print this message            }"
          "{@settings      |default.xml| input setting file            }"
          "{d              |           | actual distance between top-left and top-right corners of "
          "the calibration grid }"
          "{winSize        | 11        | Half of search window for cornerSubPix }";
    //定义CommandLineParser类对象parser,并调用其构造函数对其进行初始化
    CommandLineParser parser(argc, argv, keys);
    //在此类中获取某个变量的方法如下:string pos_path = parser.get<string>("pos_path");
    parser.about("This is a camera calibration sample.\n"
                 "Usage: camera_calibration [configuration_file -- default ./default.xml]\n"
                 "Near the sample file you'll find the configuration file, which has detailed help of "
                 "how to edit it. It may be any OpenCV supported file format XML/YAML.");
    if (!parser.check()) {
        parser.printErrors();
        return 0;
    }

    if (parser.has("help")) {
        parser.printMessage();
        return 0;
    }

    //! [file_read]
    Settings s;
    //inputSettingsFile:default.xml
    const string inputSettingsFile = parser.get<string>(0);
    //OpenCV中可以使用FileStorage 对xml,yml等文本文件的读写。
    //可扩展标记语言,标准通用标记语言的子集,简称XML。是一种用于标记电子文件使其具有结构性的标记语言。YAML是一个可读性高,用来表达数据序列化的格式。
    FileStorage fs(inputSettingsFile, FileStorage::READ); // Read the settings
    if (!fs.isOpened())//FileStorage::isOpened() :判断文件是否打开
    {
        cout << "Could not open the configuration file: \"" << inputSettingsFile << "\"" << endl;
        parser.printMessage();
        return -1;
    }
    fs["Settings"] >> s;
    fs.release();                                         // close Settings file
    //! [file_read]

    //FileStorage fout("settings.yml", FileStorage::WRITE); // write config as YAML
    //fout << "Settings" << s;

    if (!s.goodInput)
    {
        cout << "Invalid input detected. Application stopping. " << endl;
        return -1;
    }

    int winSize = parser.get<int>("winSize");

    float grid_width = s.squareSize * (s.boardSize.width - 1);//grid_width=240
    bool release_object = false;
    if (parser.has("d")) {
        grid_width = parser.get<float>("d");
        release_object = true;
    }
    //明一个名为imagePoints的容器,其元素为vector的容器  Point2f(x,y)中的x代表在图像中的列,y代表图像中的行。
    //Point2f a=Point2f(2,1.5); 或者   Point2f a(2, 1.5);或者Point2f a;a.x = 2;a.y = 1.5;   错误用法:Point2f a=(2,1.5);
    vector<vector<Point2f> > imagePoints;
    Mat cameraMatrix, distCoeffs;
    Size imageSize;
    //三元运算符 Exp1 ? Exp2 : Exp3; 如果 Exp1 为真,则计算 Exp2 的值,否则计算 Exp3 的值
    int mode = s.inputType == Settings::IMAGE_LIST ? CAPTURING : DETECTION;//=1
    clock_t prevTimestamp = 0;
    const Scalar RED(0,0,255), GREEN(0,255,0);
    const char ESC_KEY = 27;

    //! [get_input]
    int num = 0;
    for(;;)//C++ 程序员偏向于使用 for(;;) 结构来表示一个无限循环
    {
        Mat view;
        bool blinkOutput = false;

        view = s.nextImage();

        //-----  如果没有更多的图像,或得到足够的,则停止校准并显示结果 -------------
        if( mode == CAPTURING && imagePoints.size() >= (size_t)s.nrFrames )
        {
          if(runCalibrationAndSave(s, imageSize,  cameraMatrix, distCoeffs, imagePoints, grid_width,
                                   release_object))
              mode = CALIBRATED;
          else
              mode = DETECTION;
        }
        if(view.empty())          // If there are no more images stop the loop
        {
            // if calibration threshold was not reached yet, calibrate now
            if( mode != CALIBRATED && !imagePoints.empty() )
                runCalibrationAndSave(s, imageSize,  cameraMatrix, distCoeffs, imagePoints, grid_width,
                                      release_object);
            break;
        }
        //! [get_input]

        imageSize = view.size();  // Format input image.
        if( s.flipVertical )    flip( view, view, 0 );

        //! [find_pattern]
        vector<Point2f> pointBuf;

        bool found;
        // | 是位运算符,规则:有1为1       CALIB_CB_ADAPTIVE_THRESH=1(01)   CALIB_CB_NORMALIZE_IMAGE=2(10)  01|10=11 =3
        int chessBoardFlags = CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_NORMALIZE_IMAGE;

        if(!s.useFisheye) {//CALIB_CB_FAST_CHECK=8
            // fast check erroneously fails with high distortions like fisheye
            chessBoardFlags |= CALIB_CB_FAST_CHECK;
        }
        /// chessBoardFlags=11  
        switch( s.calibrationPattern ) // Find feature points on the input format
        {
        case Settings::CHESSBOARD://查找棋盘内角的位置。(输入图像,棋盘行和列的内角数,检测到拐角的输出数组,操作标志)11=1+2+8 即1,2,8标志位功能全部使用
            //1:自适应阈值将图像转换为黑白 2:应用固定或自适应阈值之前,使用equalizeHist对图像伽玛进行归一化 8:对图像进行快速检查,查找棋盘角,如果没有找到,则快捷调用。这可以大大加快退化条件下的调用,当没有棋盘被观察到
            found = findChessboardCorners( view, s.boardSize, pointBuf, chessBoardFlags);
            break;
        case Settings::CIRCLES_GRID://该函数试图确定输入图像是否包含圆形网格。
            found = findCirclesGrid( view, s.boardSize, pointBuf );
            break;
        case Settings::ASYMMETRIC_CIRCLES_GRID:// CALIB_CB_ASYMMETRIC_GRID使用不对称的圆形图案。
            found = findCirclesGrid( view, s.boardSize, pointBuf, CALIB_CB_ASYMMETRIC_GRID );
            break;
        default:
            found = false;
            break;
        }
        //! [find_pattern]
        //! [pattern_found]
        if ( found)                // If done with success,
        {
              // improve the found corners' coordinate accuracy for chessboard
                if( s.calibrationPattern == Settings::CHESSBOARD)
                {
                    Mat viewGray;
                    cvtColor(view, viewGray, COLOR_BGR2GRAY);
                    //该函数迭代寻找角点或径向鞍点的亚像素精确位置(输入图像,输入角的初始坐标和为输出提供的细化坐标,搜索窗口边长的一半((11*2+1)*(11*2+1)=46)
                    //(搜索区域中间的死区面积的一半,下面的公式中没有进行求和。它有时用于避免自相关矩阵可能出现的奇异性。(-1,-1)表示没有这样的大小。),角点细化迭代过程的终止准则)
                    cornerSubPix( viewGray, pointBuf, Size(winSize,winSize),//(TermCriteria:(类型,迭代次数活元素的最大数量,期望的精度或参数变化))
                        Size(-1,-1), TermCriteria( TermCriteria::EPS+TermCriteria::COUNT, 30, 0.0001 ));
                }

                if( mode == CAPTURING &&  //对于相机,延迟时间后才能重新采样
                    (!s.inputCapture.isOpened() || clock() - prevTimestamp > s.delay*1e-3*CLOCKS_PER_SEC) )
                {
                    imagePoints.push_back(pointBuf);
                    prevTimestamp = clock();
                    blinkOutput = s.inputCapture.isOpened();
                }

                // Draw the corners.该函数绘制检测到的单个棋盘角,如果没有找到棋盘,则绘制为红色圆圈,如果找到棋盘,则绘制为与线相连的彩色角。
                //(输入图像,每个棋盘行和列的内角数(7,5),检测到的角的数组,findChessboardCorners的输出,是否找到完整单板的参数-findChessboardCorners的返回值)
                std::cout << "-----------corners:" << endl << pointBuf<<endl;
                drawChessboardCorners( view, s.boardSize, Mat(pointBuf), found );
        }
        //! [pattern_found]
        //----------------------------- Output Text ------------------------------------------------
        //! [output_text]
        string msg = (mode == CAPTURING) ? "100/100" :
                      mode == CALIBRATED ? "Calibrated" : "Press 'g' to start";
        int baseLine = 0;
        //函数cv::getTextSize计算并返回包含指定文本框的大小。
        Size textSize = getTextSize(msg, 1, 1, 1, &baseLine);//textSize=(w=71,h=10)
        Point textOrigin(view.cols - 2*textSize.width - 10, view.rows - 2*baseLine - 10);//textOrigin=(168,218)

        if( mode == CAPTURING )
        {
            if(s.showUndistorted)
                msg = cv::format( "%d/%d Undist", (int)imagePoints.size(), s.nrFrames );
            else
                msg = cv::format( "%d/%d", (int)imagePoints.size(), s.nrFrames );
        }

        putText( view, msg, textOrigin, 1, 1, mode == CALIBRATED ?  GREEN : RED);

        if( blinkOutput )
            bitwise_not(view, view);
        //! [output_text]
        //------------------------- Video capture  output  undistorted ------------------------------
        //! [output_undistorted]
        if( mode == CALIBRATED && s.showUndistorted )
        {
            Mat temp = view.clone();
            if (s.useFisheye)
            {
                Mat newCamMat;
                fisheye::estimateNewCameraMatrixForUndistortRectify(cameraMatrix, distCoeffs, imageSize,
                                                                    Matx33d::eye(), newCamMat, 1);
                cv::fisheye::undistortImage(temp, view, cameraMatrix, distCoeffs, newCamMat);
            }
            else
              undistort(temp, view, cameraMatrix, distCoeffs);
        }
        //! [output_undistorted]
        //------------------------------ Show image and check for input commands -------------------
        //! [await_input]
        num=num+1;
        std::string path = "E:/VS2022/AWORK/distortion/Corner_detection/un_enhance/"+std::to_string(num)+".png";
        cv::imwrite(path,view);
        cv::imshow("Image View", view);
        cv::waitKey(0);
        char key = (char)cv::waitKey(s.inputCapture.isOpened() ? 50 : s.delay);//key=-1

        if( key  == ESC_KEY )
            break;

        if( key == 'u' && mode == CALIBRATED )
           s.showUndistorted = !s.showUndistorted;

        if( s.inputCapture.isOpened() && key == 'g' )
        {
            mode = CAPTURING;
            imagePoints.clear();
        }
        //! [await_input]
    }

    // -----------------------Show the undistorted image for the image list ------------------------
    //! [show_results]
    if( s.inputType == Settings::IMAGE_LIST && s.showUndistorted && !cameraMatrix.empty())
    {
        Mat view, rview, map1, map2;

        if (s.useFisheye)
        {
            Mat newCamMat;
            //估计新的相机固有矩阵的不失真或整流。
            fisheye::estimateNewCameraMatrixForUndistortRectify(cameraMatrix, distCoeffs, imageSize,
                                                                Matx33d::eye(), newCamMat, 1);
            fisheye::initUndistortRectifyMap(cameraMatrix, distCoeffs, Matx33d::eye(), newCamMat, imageSize,
                                             CV_16SC2, map1, map2);
        }
        else
        {   //计算不失真和校正映射的图像转换通过重映射。如果第二个参数为空则使用零失真,如果第三或第四为空则使用单位矩阵。
            initUndistortRectifyMap(
                cameraMatrix, distCoeffs, Mat(), //getOptimalNewCameraMatrix:根据自由缩放参数返回新的相机固有矩阵。
                //第四个参数:0:当未失真图像中的所有像素有效时  1:当所有源图像像素保留在未失真图像中时  false=0,true=1;roi=0即不裁剪
                //当alpha=1时,所有像素均保留,但存在黑色边框。当alpha=0时,损失最多的像素,没有黑色边框,但会放大视场。
                getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0), imageSize,
                CV_16SC2, map1, map2);
        }

        for(size_t i = 0; i < s.imageList.size(); i++ )
        {
            view = imread(s.imageList[i], IMREAD_COLOR);
            if(view.empty())
                continue;
            cv::remap(view, rview, map1, map2, INTER_LINEAR);
            std::string path = "E:/VS2022/AWORK/distortion/correction_ori/un_enhance/" + std::to_string(i) + ".png";
            cv::imwrite(path, rview);
            cv::imshow("Image View", rview);
            char c = (char)cv::waitKey();
            if( c  == ESC_KEY || c == 'q' || c == 'Q' )
                break;
        }
    }
    //! [show_results]

    return 0;
}

//! [compute_errors]
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, bool fisheye)
{
    vector<Point2f> imagePoints2;
    size_t totalPoints = 0;
    double totalErr = 0, err;
    perViewErrors.resize(objectPoints.size());

    for(size_t i = 0; i < objectPoints.size(); ++i )
    {
        if (fisheye)
        {
            fisheye::projectPoints(objectPoints[i], imagePoints2, rvecs[i], tvecs[i], cameraMatrix,
                                   distCoeffs);
        }
        else
        {
            projectPoints(objectPoints[i], rvecs[i], tvecs[i], cameraMatrix, distCoeffs, imagePoints2);
        }
        err = norm(imagePoints[i], imagePoints2, NORM_L2);

        size_t n = objectPoints[i].size();
        perViewErrors[i] = (float) std::sqrt(err*err/n);
        totalErr        += err*err;
        totalPoints     += n;
    }

    return std::sqrt(totalErr/totalPoints);
}
//! [compute_errors]
//! [board_corners]
static void calcBoardCornerPositions(Size boardSize, float squareSize, vector<Point3f>& corners,
                                     Settings::Pattern patternType /*= Settings::CHESSBOARD*/)
{
    corners.clear();

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

    case Settings::ASYMMETRIC_CIRCLES_GRID:
        for( int i = 0; i < boardSize.height; i++ )
            for( int j = 0; j < boardSize.width; j++ )
                corners.push_back(Point3f((2*j + i % 2)*squareSize, i*squareSize, 0));
        break;
    default:
        break;
    }
}
//! [board_corners]
static bool runCalibration( Settings& s, Size& imageSize, Mat& cameraMatrix, Mat& distCoeffs,
                            vector<vector<Point2f> > imagePoints, vector<Mat>& rvecs, vector<Mat>& tvecs,
                            vector<float>& reprojErrs,  double& totalAvgErr, vector<Point3f>& newObjPoints,
                            float grid_width, bool release_object)
{
    //! [fixed_aspect]
    cameraMatrix = Mat::eye(3, 3, CV_64F);
    if( !s.useFisheye && s.flag & CALIB_FIX_ASPECT_RATIO )
        cameraMatrix.at<double>(0,0) = s.aspectRatio;
    //! [fixed_aspect]
    if (s.useFisheye) {
        distCoeffs = Mat::zeros(4, 1, CV_64F);
    } else {
        distCoeffs = Mat::zeros(8, 1, CV_64F);
    }

    vector<vector<Point3f> > objectPoints(1);
    calcBoardCornerPositions(s.boardSize, s.squareSize, objectPoints[0], s.calibrationPattern);
    objectPoints[0][s.boardSize.width - 1].x = objectPoints[0][0].x + grid_width;
    newObjPoints = objectPoints[0];

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

    //Find intrinsic and extrinsic camera parameters
    double rms;

    if (s.useFisheye) {
        Mat _rvecs, _tvecs;
        rms = fisheye::calibrate(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs, _rvecs,
                                 _tvecs, s.flag);

        rvecs.reserve(_rvecs.rows);
        tvecs.reserve(_tvecs.rows);
        for(int i = 0; i < int(objectPoints.size()); i++){
            rvecs.push_back(_rvecs.row(i));
            tvecs.push_back(_tvecs.row(i));
        }
    } else {
        int iFixedPoint = -1;
        if (release_object)
            iFixedPoint = s.boardSize.width - 1;
        rms = calibrateCameraRO(objectPoints, imagePoints, imageSize, iFixedPoint,
                                cameraMatrix, distCoeffs, rvecs, tvecs, newObjPoints,
                                s.flag | CALIB_USE_LU);
    }

    if (release_object) {
        cout << "New board corners: " << endl;
        cout << newObjPoints[0] << endl;
        cout << newObjPoints[s.boardSize.width - 1] << endl;
        cout << newObjPoints[s.boardSize.width * (s.boardSize.height - 1)] << endl;
        cout << newObjPoints.back() << endl;
    }

    cout << "Re-projection error reported by calibrateCamera: "<< rms << endl;

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

    objectPoints.clear();
    objectPoints.resize(imagePoints.size(), newObjPoints);
    totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints, rvecs, tvecs, cameraMatrix,
                                            distCoeffs, reprojErrs, s.useFisheye);
    for (int i = 0; i < int(objectPoints.size()); i++) {
        cout << "--------------------------------objectPoints["<<i<<"]=  " << objectPoints[i] << endl;
    }
    cout << "--------------------------------totalAvgErr: " << totalAvgErr << endl;
    return ok;
}

// Print camera parameters to the output file
static void saveCameraParams( Settings& s, Size& imageSize, Mat& cameraMatrix, Mat& distCoeffs,
                              const vector<Mat>& rvecs, const vector<Mat>& tvecs,
                              const vector<float>& reprojErrs, const vector<vector<Point2f> >& imagePoints,
                              double totalAvgErr, const vector<Point3f>& newObjPoints )
{
    FileStorage fs( s.outputFileName, FileStorage::WRITE );

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

    fs << "calibration_time" << buf;

    if( !rvecs.empty() || !reprojErrs.empty() )
        fs << "nr_of_frames" << (int)std::max(rvecs.size(), reprojErrs.size());
    fs << "image_width" << imageSize.width;
    fs << "image_height" << imageSize.height;
    fs << "board_width" << s.boardSize.width;
    fs << "board_height" << s.boardSize.height;
    fs << "square_size" << s.squareSize;

    if( !s.useFisheye && s.flag & CALIB_FIX_ASPECT_RATIO )
        fs << "fix_aspect_ratio" << s.aspectRatio;

    if (s.flag)
    {
        std::stringstream flagsStringStream;
        if (s.useFisheye)
        {
            flagsStringStream << "flags:"
                << (s.flag & fisheye::CALIB_FIX_SKEW ? " +fix_skew" : "")
                << (s.flag & fisheye::CALIB_FIX_K1 ? " +fix_k1" : "")
                << (s.flag & fisheye::CALIB_FIX_K2 ? " +fix_k2" : "")
                << (s.flag & fisheye::CALIB_FIX_K3 ? " +fix_k3" : "")
                << (s.flag & fisheye::CALIB_FIX_K4 ? " +fix_k4" : "")
                << (s.flag & fisheye::CALIB_RECOMPUTE_EXTRINSIC ? " +recompute_extrinsic" : "");
        }
        else
        {
            flagsStringStream << "flags:"
                << (s.flag & CALIB_USE_INTRINSIC_GUESS ? " +use_intrinsic_guess" : "")
                << (s.flag & CALIB_FIX_ASPECT_RATIO ? " +fix_aspectRatio" : "")
                << (s.flag & CALIB_FIX_PRINCIPAL_POINT ? " +fix_principal_point" : "")
                << (s.flag & CALIB_ZERO_TANGENT_DIST ? " +zero_tangent_dist" : "")
                << (s.flag & CALIB_FIX_K1 ? " +fix_k1" : "")
                << (s.flag & CALIB_FIX_K2 ? " +fix_k2" : "")
                << (s.flag & CALIB_FIX_K3 ? " +fix_k3" : "")
                << (s.flag & CALIB_FIX_K4 ? " +fix_k4" : "")
                << (s.flag & CALIB_FIX_K5 ? " +fix_k5" : "");
        }
        fs.writeComment(flagsStringStream.str());
    }

    fs << "flags" << s.flag;

    fs << "fisheye_model" << s.useFisheye;

    fs << "camera_matrix" << cameraMatrix;
    fs << "distortion_coefficients" << distCoeffs;

    fs << "avg_reprojection_error" << totalAvgErr;
    if (s.writeExtrinsics && !reprojErrs.empty())
        fs << "per_view_reprojection_errors" << Mat(reprojErrs);

    if(s.writeExtrinsics && !rvecs.empty() && !tvecs.empty() )
    {
        CV_Assert(rvecs[0].type() == tvecs[0].type());
        Mat bigmat((int)rvecs.size(), 6, CV_MAKETYPE(rvecs[0].type(), 1));
        bool needReshapeR = rvecs[0].depth() != 1 ? true : false;
        bool needReshapeT = tvecs[0].depth() != 1 ? true : false;

        for( size_t i = 0; i < rvecs.size(); i++ )
        {
            Mat r = bigmat(Range(int(i), int(i+1)), Range(0,3));
            Mat t = bigmat(Range(int(i), int(i+1)), Range(3,6));

            if(needReshapeR)
                rvecs[i].reshape(1, 1).copyTo(r);
            else
            {
                //*.t() is MatExpr (not Mat) so we can use assignment operator
                CV_Assert(rvecs[i].rows == 3 && rvecs[i].cols == 1);
                r = rvecs[i].t();
            }

            if(needReshapeT)
                tvecs[i].reshape(1, 1).copyTo(t);
            else
            {
                CV_Assert(tvecs[i].rows == 3 && tvecs[i].cols == 1);
                t = tvecs[i].t();
            }
        }
        fs.writeComment("a set of 6-tuples (rotation vector + translation vector) for each view");
        fs << "extrinsic_parameters" << bigmat;
    }

    if(s.writePoints && !imagePoints.empty() )
    {
        Mat imagePtMat((int)imagePoints.size(), (int)imagePoints[0].size(), CV_32FC2);
        for( size_t i = 0; i < imagePoints.size(); i++ )
        {
            Mat r = imagePtMat.row(int(i)).reshape(2, imagePtMat.cols);
            Mat imgpti(imagePoints[i]);
            imgpti.copyTo(r);
        }
        fs << "image_points" << imagePtMat;
    }

    if( s.writeGrid && !newObjPoints.empty() )
    {
        fs << "grid_points" << newObjPoints;
    }
}

//! [run_and_save]
bool runCalibrationAndSave(Settings& s, Size imageSize, Mat& cameraMatrix, Mat& distCoeffs,
                           vector<vector<Point2f> > imagePoints, float grid_width, bool release_object)
{
    vector<Mat> rvecs, tvecs;
    vector<float> reprojErrs;
    double totalAvgErr = 0;
    vector<Point3f> newObjPoints;

    bool ok = runCalibration(s, imageSize, cameraMatrix, distCoeffs, imagePoints, rvecs, tvecs, reprojErrs,
                             totalAvgErr, newObjPoints, grid_width, release_object);
    cout << (ok ? "Calibration succeeded" : "Calibration failed")
         << ". avg re projection error = " << totalAvgErr << endl;

    if (ok)
        saveCameraParams(s, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, reprojErrs, imagePoints,
                         totalAvgErr, newObjPoints);
    return ok;
}
//! [run_and_save]








本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

相机标定-opencv 的相关文章

  • opencv:如何将所有黑色像素转换为透明并将其保存到png文件

    如下图 我希望所有黑色像素都是透明的并将其保存为 png 文件 您可以像这样快速完成并矢量化 import cv2 import numpy as np Load image as Numpy array in BGR order na c
  • Python OpenCV视频格式在浏览器中播放

    我正在尝试从一系列图像创建视频并将其显示在浏览器中 但由于某些奇怪的原因 无论我使用什么编解码器或文件格式 我都会收到以下错误 找不到格式和 MIME 类型受支持的视频 这是我的代码 ready images import cv2 for
  • 如何在 Ubuntu 16.04 上安装适用于 Python 2.7 的 openCV 2.4.13?

    我尝试了很多在线帖子来安装 opencv 但它们不适用于 Ubuntu 16 04 有人可以给我安装 openCV 2 4 13 的步骤吗 我不久前制作了一个脚本 用于安装最新版本的 OpenCV 截至本答案的最后一次更新为 4 2 这是它
  • OpenCV 中更新窗口的 waitKey() 的替代方法

    到目前为止我见过的所有示例和书籍都建议使用 waitKey 1 来强制重新绘制 OpenCV 窗口 这看起来很奇怪而且太老套了 不必要的时候为什么还要等待 1 毫秒呢 还有其他选择吗 我尝试了 cv updateWindow 但它似乎需要
  • 如何使用 python cv2 api 将 xy 点格式化为 unactorPoints?

    我在格式化要传递给 unactorPoints 的 x y 点列表时遇到问题 opencv 2 4 1 该错误消息是 C 特定的 并抱怨点数组不是 CV 32FC2 类型 我不应该能够传入 Nx2 numpy 数组吗 import cv2
  • 将 RGB 转换为黑色或白色

    我如何在Python中获取RGB图像并将其转换为黑白图像 不是灰度 我希望每个像素要么是全黑 0 0 0 要么是全白 255 255 255 流行的 Python 图像处理库中是否有任何内置功能可以完成此任务 如果不是 最好的方法是循环遍历
  • 如何在没有 OpenCv Manager 的情况下运行 OpenCV 代码

    我正在使用 OpenCV4Android 版本 2 4 10 并在 Samsung Galayx GT I9300 上测试我的代码 我遇到的问题是 我必须从 Play 商店下载 Opencv Manager 以便我的 opencv 代码运行
  • 检测骰子的上侧

    是否可以检测骰子的上面 虽然从顶部看这将是一项简单的任务 但从许多角度来看 可以看到多个侧面 Here is an example of a dice feel free to take your own pictures 您通常想知道自己
  • 有没有办法检测图像是否模糊? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我想知道是否有一种方法可以通过分析图像数据来确定图像是否模糊 估计图像清晰度的另一种非常简单的方法是使用拉普拉斯 或 LoG 滤波器并
  • OpenCV:视频录制太快

    我有一个简单的录像机 录制来自网络摄像头的视频 theVideoWriter open filename countAsString ext CV FOURCC X V I D 30 Size 1920 1080 true while re
  • Pyinstaller“无法执行脚本 pyi_rth_pkgres”并且缺少软件包

    这是我第一次在这里发布问题 因为我的大部分问题已经被其他人回答了 我正在 python 中开发 GUI 应用程序 并尝试使用 pyinstaller 将其打包到单个文件夹和 exe 中 以便于移植 目前 我使用 Windows 10 和 a
  • `opencv.android.JavaCameraView` 和 `opencv.android.NativeCameraView` 有什么区别

    正如主题中所述 有什么区别opencv android JavaCameraView and opencv android NativeCameraView 与其他主要优点相比 有哪些优点可以提供更多选择 来自OpenCV 文档 http
  • 如何获得垂直线穿过的完整内轴线?

    我有一个图像 我想获取穿过其中轴的像素 我尝试使用骨架化 and 中轴方法来获取它们 但这两种方法都返回比相应对象短的一维线 这是带有示例图像的代码 gt gt gt import skimage filter gt gt gt impor
  • 如何将 opencv mat 图像转换为 gdi 位图

    我想将 openCV Mat 文件转换为 GDI 位图图像 我找不到任何有关如何执行此操作的信息 我认为没有直接的方法可以做到这一点 但我希望它不涉及将其写入文件并读回 http opencv users 1802565 n2 nabble
  • 对同色像素块的边界进行着色

    我有一张有 5 种不同颜色的图像 在这种情况下 随机生成 w h 40 27 img Image new RGB w h pixels img load available colors r 255 13 18 b 72 64 255 y
  • Haar训练时正样本和负样本使用多少张图片?

    我已经阅读了大量有关 Haar 训练的内容 但我不清楚应该为正样本集和负样本集使用多少图像 我看到建议使用很多图像 有些人推荐数千张 我也不清楚正负样本图像的数量是否应该相同 这是关于 Haar 训练的最佳教程 你试过这个吗 http no
  • OpenCV 机器学习算法的 CSV 格式

    OpenCV 中的机器学习算法似乎使用以 CSV 格式读取的数据 参见示例这个 cpp文件 https code ros org trac opencv browser trunk opencv samples c tree engine
  • OpenCV Python RTSP 流

    我想使用 RTSP 从 IP 摄像机流式传输视频 但我有一个问题 我已经安装了先决条件 而且我的 RTSP 链接可以在 VlC 播放器上运行 但是当我在编辑器中尝试并运行它时 它说找不到相机 这是我的代码 import cv2 import
  • 使用 OpenCV 和 Python 叠加两个图像而不丢失颜色强度

    如何叠加两个图像而不损失两个图像的颜色强度 我有图像1和图像2 2 我尝试使用 0 5 alpha 和 beta 但它给我的合并图像的颜色强度只有一半 dst cv2 addWeighted img1 0 5 img2 0 5 0 但是当我
  • Android for OpenCV - 打开跟踪文件时出错,UnsatisfiedLinkError

    我对 Android 开发和 OpenCV 都是新手 我从 Android 下载了 OpenCV 库http sourceforge net projects opencvlibrary files opencv android http

随机推荐

  • Python时间序列统计模型自回归预测网络流量

    预测过程包括预测时间序列的未来值 或者通过仅基于其过去行为 自回归 对序列进行建模 或者通过使用其他外部变量来进行建模 本文档描述了如何使用机器学习和统计模型来预测访问网站的流量 使用自 2020 年 7 月 1 日起 查看网站的每日访问历
  • 五子棋AI算法简易实现(一)

    基础篇 1 胜负判定 五子棋的胜负判定的条件是其中一方下棋以后 横线 竖线 右上斜线或者右下斜线任一方向出现五子相连 即可判定获胜 此处用递归方法即可实现 var is win false var ModuleWinnerCheck che
  • 单链表的插入操作(全)

    1 在指定位序插入数据第一步 主要执行操作 查找 先查找所要插入位置的前一个元素 具体方法 根据链表的特点 每一个节点都需要一个数据域和指针域 所以只需从头节点遍历到所要插入数据的的前一个节点即可 后面的showList函数也用的这种方法第
  • SqlServer2019—解决SQL Server 无法连接127.0.0.1的问题

    1 打开SQL Server 2019配置管理器 2 SQL Servere 网络配置 启用 Named Pipes 和 TCP IP 3 修改TCP IP协议 右键选择属性 IP地址 具体如下图所示 4 重启SQL Server服务
  • C语言输出菱形

    C语言输出菱形 菱形 include
  • 栈的顺序表示

    栈底是表头 栈顶是表尾 只能在表尾插入和删除 栈的第一个元素放在下标为0的位置 虽然top指向栈顶元素 但为了方便 指向栈顶元素之上 即下一个元素的位置 stacksize栈的大小 用来表示我们当前分配的数组 我们用数组来存储栈 能存储多少
  • 聊聊什么是架构,你理解对了吗?

    什么是架构 软件有架构 建筑也有架构 它们有什么相同点和不同点 下面咱们就介绍一下 容易混淆的几个概念 一 系统与子系统 系统 泛指由一群有关联的个体组成 根据某种规则运作 能完成个别元件不能单独完成的工作的群体 它的意思是 总体 整体 或
  • C++中的单例模式

    单例模式也称为单件模式 单子模式 可能是使用最广泛的设计模式 其意图是保证一个类仅有一个实例 并提供一个访问它的全局访问点 该实例被所有程序模块共享 有很多地方需要这样的功能模块 如系统的日志输出 GUI应用必须是单鼠标 MODEM的联接需
  • 转载 ---kafka集群消费之ConsumerRecord类

    java lang Object继承 org apache kafka clients consumer ConsumerRecord
  • 次表面散射

    技术博客 https github com Li ZhuoHang Subsurface scattering 基于屏幕空间模糊的次表面散射 SSSSS 效果展示 原模型 开启镜面表面反射 float PHBeckmann float nd
  • Qt中定义全局变量方法

    在使用qt编程时经常要使用到全局变量 全局变量该如何去定义和初始化呢 有两种方式 第一种使用extern 关键字 global h extern int a global cpp static int a 1 myfile cpp incl
  • ..\OBJ\Template.axf: Error: L6218E: Undefined symbol FSMC_NORSRAMCmd (referred from lcd.o).

    面对这个问题 假如环境配置和一般代码上不出错出现的问题的话 那就是缺了下面这两个文件 剩下的我就继续一步一步操作 进行 下去 步骤1 步骤2 用直接右击FWLIB 中第三个选项Add Existing Files 步骤3 在FWLIB中找s
  • Web服务器群集:使用Haproxy搭建Web集群

    目录 一 理论 1 Haproxy集群 2 常见的web集群调度器 3 三种web集群调度器的区别 4 下载安装 二 部署Haproxy集群 1 部署 2 重新定义Haproxy集群的日志 三 实验 1 部署Haproxy集群 四 问题 1
  • 新手linux安装vasp_史上最简单的VASP安装教程-非虚拟机

    本文是针对vasp初学者的安装教程编译器以及VASP都已编译号直接解压到系统中即可用 故不用配置其它的库文件以及环境 本教程适用于任意平台安装centos7的服务器以及pc机 若在其它linux发行版本中安装请咨询小编 一 VASP安装需要
  • SecureCRT 5.0菜单栏消失

    今天遇到一个怪问题 SecureCRT的菜单栏突然没了 郁闷了很长时间 回头想想好像是在最小化的时候选了个什么 顺着这个思路 终于发现最小化窗口 在任务栏上的最小化的程序上点右键 呵呵 看到了 Always On Top Save Sett
  • Keil IAR - Cortex M3 调试问题及解决方法(1)

    看到一篇文章 转载如下 其实不光是STM32 其它芯片甚至其它的IDE 都可参考 STM32调试过程中常见的问题及解决方法 一 在 Debug选项卡 下设置好仿真器的类型后 下载程序时却提示 No ULINK Device found 解决
  • 你不知道的javascript之运算符

    学过c php这些语言的同学在学习javascript时候可能会有一些困扰 因为javascript中的 和c或者是php中有很大的差别 因为在javascript中返回的类型并不是布尔值 他返回的而是两个操作值中之一 例如一下例子 var
  • Vue组件常用的六种通信方式

    Vue js 组件实例的作用域是相互独立的 不同组件之间的数据不能互相访问 组件有父级组件 子级组件 兄弟组件 如何选择组件之间的通信方式 针对常用的 props emit on vuex parent children attrs lis
  • 一次springboot日志不生效问题深入分析

    springboot日志不生效问题深入分析 auth by yangs at 2022 09 22 现象 在一次环境排查问题中 发现某系统日志不打印 通过各种排查 总结后引起原因为配置这块后面改动比较多 有配置移动 打包脚本优化涉及关联改动
  • 相机标定-opencv

    相机标定采用的是opencv自带的标定文件 主要有下面几个文件 1 camera calibration cpp 这个文件就是生成标定参数的文件 前期准备好后 只需要运行这个文件就可以了 2 default xml PS 有的opencv版