1. 程式人生 > >執行OpenCV3.4.1的雙目相機標定例程註釋,OpenCV3.4.1+VS2017安裝配置

執行OpenCV3.4.1的雙目相機標定例程註釋,OpenCV3.4.1+VS2017安裝配置

新版本總是在迭代升級,目前opencv最新版本為3.4.1VS已經到了2017版本,由於opencv每個版本對應的VS都需要有不同的配置,這裡也是鼓搗了好幾天才完成配置,並且跑完這個雙目標定的例程,期間踩了不少坑,下面貼出來分享給小夥伴,同時還有程式註釋

opencv安裝:https://opencv.org/releases.html


VS2017安裝:https://www.visualstudio.com/zh-hans/thank-you-downloading-visual-studio/?sku=Professional&rel=15

這裡記得安裝一些必要元件!!建議全程線上,因為後邊可能需要獲取一些計算機許可權,360等軟體會禁止許可權,導致最後各種配置不成功!

接下來就是配置opencv了:

  1.  配置環境變數:D:\work_soft\opencv\build\x64\vc15\bin
                這裡VC15對應VS2017,

    2.在VS2017配置屬性管理器Debug x64:

     VC++目錄: 
        (Include Directories)
        包含目錄(標頭檔案)D:\work_soft\opencv\build\include
                                      D:\work_soft\opencv\build\include\opencv

                                      D:\work_soft\opencv\build\include\opencv2


        (Library Directories)

        庫目錄(庫檔案)   D:\work_soft\opencv\build\x64\vc15\lib

這裡下邊需要繼承響應的庫檔案,否則會提示缺少msvcprt.lib等庫檔案,很麻煩


    聯結器-輸入:
        (Linker-Input-Additional Dependencies)

        附加依賴項 opencv_world341d.lib


好了,到了這裡就配置結束了,接下來嘗試下執行第一個標定例程;

 D:\work_soft\opencv是我的opencv安裝位置

  1. 找到官方的例程    D:\work_soft\opencv\sources\samples\cpp\stereocalib.cpp
  2. 找到官方的圖片和.xml   D:\work_soft\opencv\sources\samples\data
  3. 新建工程,並且把第二部得到的圖片和.xml放到新建的工程中
  4. 選擇x64和debug環境

  5. 更改一行程式碼cv::CommandLineParser parser(argc, argv, "{w|9|}{h|6|}{s|1.0|}{nr||}{help||}{@input|stereo_calib.xml|}");

這裡的@input|stereo_calib.xml|指的是你存入stereo_calib.xml的地址,之前是放在和stereocalib.cpp同目錄下。

以下是程式碼註釋

/* This is sample from the OpenCV book. The copyright notice is below */


/* *************** License:**************************
   Oct. 3, 2008
   Right to use this code in any way you want without warranty, support or any guarantee of it working.


   BOOK: It would be nice if you cited it:
   Learning OpenCV: Computer Vision with the OpenCV Library
     by Gary Bradski and Adrian Kaehler
     Published by O'Reilly Media, October 3, 2008


   AVAILABLE AT:
     http://www.amazon.com/Learning-OpenCV-Computer-Vision-Library/dp/0596516134
     Or: http://oreilly.com/catalog/9780596516130/
     ISBN-10: 0596516134 or: ISBN-13: 978-0596516130


   OPENCV WEBSITES:
     Homepage:      http://opencv.org
     Online docs:   http://docs.opencv.org
     Q&A forum:     http://answers.opencv.org
     Issue tracker: http://code.opencv.org
     GitHub:        https://github.com/opencv/opencv/
   ************************************************** */


#include "opencv2/calib3d.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"


#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>


using namespace cv;//包含相應的Opencv名稱空間
using namespace std;


static int print_help()
{
    cout <<
            " Given a list of chessboard images, the number of corners (nx, ny)\n"
            " on the chessboards, and a flag: useCalibrated for \n"
            "   calibrated (0) or\n"
            "   uncalibrated \n"
            "     (1: use cvStereoCalibrate(), 2: compute fundamental\n"
            "         matrix separately) stereo. \n"
            " Calibrate the cameras and display the\n"
            " rectified results along with the computed disparity images.   \n" << endl;
    cout << "Usage:\n ./stereo_calib -w=<board_width default=9> -h=<board_height default=6> -s=<square_size default=1.0> <image list XML/YML file default=../data/stereo_calib.xml>\n" << endl;
    return 0;
}


/************相機標定程式***************/
static void
StereoCalib(const vector<string>& imagelist, Size boardSize, float squareSize, bool displayCorners = false, bool useCalibrated=true, bool showRectified=true)
{
    if( imagelist.size() % 2 != 0 )//判斷圖片是否成對
    {
        cout << "Error: the image list contains odd (non-even) number of elements\n";
        return;
    }


    const int maxScale = 2;//設定尋找角點的影象尺寸,若scale未找到,則將影象放大尋找角點
    // ARRAY AND VECTOR STORAGE:


    vector<vector<Point2f> > imagePoints[2];//分別為左右影象的角點
    vector<vector<Point3f> > objectPoints;//物體
    Size imageSize;//??


    int i, j, k, nimages = (int)imagelist.size()/2;//nimages為左或右影象的個數


    imagePoints[0].resize(nimages);
    imagePoints[1].resize(nimages);
    vector<string> goodImageList;


    for( i = j = 0; i < nimages; i++ )//依次尋找13對圖片
    {
        for( k = 0; k < 2; k++ )//依次尋找左右圖片
        {
            const string& filename = imagelist[i*2+k];
            Mat img = imread(filename, 0);//載入灰度圖 0代表灰度圖
            if(img.empty())
                break;
            if( imageSize == Size() )//判斷影象尺寸是否達到預先設定的要求
                imageSize = img.size();
            else if( img.size() != imageSize )
            {
                cout << "The image " << filename << " has the size different from the first image size. Skipping the pair\n";
                break;
            }
            bool found = false;
//設定影象矩陣的引用(指標),此時指向左右檢視的矩陣首地址 
            vector<Point2f>& corners = imagePoints[k][j];//賦值角點個數及位置
            for( int scale = 1; scale <= maxScale; scale++ )
            {
                Mat timg;
                if( scale == 1 )
                    timg = img;
                else
                    resize(img, timg, Size(), scale, scale, INTER_LINEAR_EXACT);
                found = findChessboardCorners(timg, boardSize, corners,//找角點函式,得到內角點座標
                    CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_NORMALIZE_IMAGE);


//drawChessboardCorners(timg, boardSize, corners, found);//畫出角點,自己除錯時使用,但會降低精度,正式執行時應該註釋掉


                if( found )
                {
                    if( scale > 1 )
                    {
                        Mat cornersMat(corners);
                        cornersMat *= 1./scale;
                    }
                    break;
                }
            }
            if( displayCorners )
            {
                cout << filename << endl;
                Mat cimg, cimg1;
                cvtColor(img, cimg, COLOR_GRAY2BGR);
                drawChessboardCorners(cimg, boardSize, corners, found);
                double sf = 640./MAX(img.rows, img.cols);
                resize(cimg, cimg1, Size(), sf, sf, INTER_LINEAR_EXACT);
                imshow("corners", cimg1);
                char c = (char)waitKey(500);
                if( c == 27 || c == 'q' || c == 'Q' ) //Allow ESC to quit
                    exit(-1);
            }
            else
                putchar('.');
            if( !found )
                break;
            cornerSubPix(img, corners, Size(11,11), Size(-1,-1),
                         TermCriteria(TermCriteria::COUNT+TermCriteria::EPS,
                                      30, 0.01));
        }
        if( k == 2 )
        {
            goodImageList.push_back(imagelist[i*2]);
            goodImageList.push_back(imagelist[i*2+1]);
            j++;
        }
    }
    cout << j << " pairs have been successfully detected.\n";//命令列列印檢測到的圖片
    nimages = j;//nimages為左右影象個數
    if( nimages < 2 )
    {
        cout << "Error: too little pairs to run the calibration\n";
        return;
    }


    imagePoints[0].resize(nimages);//左相機 角點位置
    imagePoints[1].resize(nimages);//右相機 角點位置
    objectPoints.resize(nimages);


    for( i = 0; i < nimages; i++ )
    {
        for( j = 0; j < boardSize.height; j++ )
            for( k = 0; k < boardSize.width; k++ )
                objectPoints[i].push_back(Point3f(k*squareSize, j*squareSize, 0));
    }


    cout << "Running stereo calibration ...\n";


    Mat cameraMatrix[2], distCoeffs[2];//相機引數  畸變矩陣
    cameraMatrix[0] = initCameraMatrix2D(objectPoints,imagePoints[0],imageSize,0);
    cameraMatrix[1] = initCameraMatrix2D(objectPoints,imagePoints[1],imageSize,0);
    Mat R, T, E, F;//R旋轉矩陣 T平移矩陣 E本徵矩陣 F輸出基本矩陣
//最關鍵的地方,求解校正後的相機引數
    double rms = stereoCalibrate(objectPoints, imagePoints[0], imagePoints[1],
                    cameraMatrix[0], distCoeffs[0],
                    cameraMatrix[1], distCoeffs[1],
                    imageSize, R, T, E, F,
                    CALIB_FIX_ASPECT_RATIO +
                    CALIB_ZERO_TANGENT_DIST +
                    CALIB_USE_INTRINSIC_GUESS +
                    CALIB_SAME_FOCAL_LENGTH +
                    CALIB_RATIONAL_MODEL +
                    CALIB_FIX_K3 + CALIB_FIX_K4 + CALIB_FIX_K5,
                    TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 100, 1e-5) );
    cout << "done with RMS error=" << rms << endl;


// CALIBRATION QUALITY CHECK
// because the output fundamental matrix implicitly
// includes all the output information,
// we can check the quality of calibration using the
// epipolar geometry constraint: m2^t*F*m1=0
    double err = 0;//計算投影標定誤差
    int npoints = 0;
    vector<Vec3f> lines[2];//極線
    for( i = 0; i < nimages; i++ )//水平校正
    {
        int npt = (int)imagePoints[0][i].size();
        Mat imgpt[2];
        for( k = 0; k < 2; k++ )
        {
            imgpt[k] = Mat(imagePoints[k][i]);
            undistortPoints(imgpt[k], imgpt[k], cameraMatrix[k], distCoeffs[k], Mat(), cameraMatrix[k]);
            computeCorrespondEpilines(imgpt[k], k+1, F, lines[k]);
        }
        for( j = 0; j < npt; j++ )
        {
            double errij = fabs(imagePoints[0][i][j].x*lines[1][j][0] +
                                imagePoints[0][i][j].y*lines[1][j][1] + lines[1][j][2]) +
                           fabs(imagePoints[1][i][j].x*lines[0][j][0] +
                                imagePoints[1][i][j].y*lines[0][j][1] + lines[0][j][2]);
            err += errij;
        }
        npoints += npt;
    }
    cout << "average epipolar err = " <<  err/npoints << endl;


    // save intrinsic parameters
    FileStorage fs("intrinsics.yml", FileStorage::WRITE);//儲存內參
    if( fs.isOpened() )
    {
        fs << "M1" << cameraMatrix[0] << "D1" << distCoeffs[0] <<
            "M2" << cameraMatrix[1] << "D2" << distCoeffs[1];
        fs.release();
    }
    else
        cout << "Error: can not save the intrinsic parameters\n";


//外引數  
// R--右相機相對左相機的旋轉矩陣  
// T--右相機相對左相機的平移矩陣  
// R1,R2--左右相機校準變換(旋轉)矩陣  3×3  
// P1,P2--左右相機在校準後坐標系中的投影矩陣 3×4  
// Q--視差-深度對映矩陣,我利用它來計算單個目標點的三維座標


    Mat R1, R2, P1, P2, Q;
    Rect validRoi[2];//影象校正之後,會對影象進行裁剪,這裡的validROI就是指裁剪之後的區域
//進行立體校正
    stereoRectify(cameraMatrix[0], distCoeffs[0],
                  cameraMatrix[1], distCoeffs[1],
                  imageSize, R, T, R1, R2, P1, P2, Q,
                  CALIB_ZERO_DISPARITY, 1, imageSize, &validRoi[0], &validRoi[1]);

/*
* R T 左相機到右相機的旋轉平移矩陣  R 3*3      T  3*1  T中第一個Tx為 基線長度
立體校正的時候需要兩幅影象共面並且行對準 以使得立體匹配更加的可靠
使得兩幅影象共面的方法就是把兩個攝像頭的影象投影到一個公共成像面上,這樣每幅影象從本影象平面投影到公共影象平面都需要一個旋轉矩陣R
stereoRectify 這個函式計算的就是從影象平面投影都公共成像平面的旋轉矩陣Rl,Rr。 Rl,Rr即為左右相機平面行對準的校正旋轉矩陣。
左相機經過Rl旋轉,右相機經過Rr旋轉之後,兩幅影象就已經共面並且行對準了。
其中Pl,Pr為兩個相機的投影矩陣,其作用是將3D點的座標轉換到影象的2D點的座標:P*[X Y Z 1]' =[x y w]
Q矩陣為重投影矩陣,即矩陣Q可以把2維平面(影象平面)上的點投影到3維空間的點:Q*[x y d 1] = [X Y Z W]。其中d為左右兩幅影象的視差
*/


    fs.open("extrinsics.yml", FileStorage::WRITE);
    if( fs.isOpened() )
    {
        fs << "R" << R << "T" << T << "R1" << R1 << "R2" << R2 << "P1" << P1 << "P2" << P2 << "Q" << Q;
        fs.release();
    }
    else
        cout << "Error: can not save the extrinsic parameters\n";
//opencv可以辨認相機的物理位置
    // OpenCV can handle left-right
    // or up-down camera arrangements
    bool isVerticalStereo = fabs(P2.at<double>(1, 3)) > fabs(P2.at<double>(0, 3));


// COMPUTE AND DISPLAY RECTIFICATION計算並顯示校正資訊
    if( !showRectified )
        return;


    Mat rmap[2][2];
// IF BY CALIBRATED (BOUGUET'S METHOD)
    if( useCalibrated )
    {
        // we already computed everything
    }
// OR ELSE HARTLEY'S METHOD
    else
 // use intrinsic parameters of each camera, but
 // compute the rectification transformation directly
 // from the fundamental matrix
    {
        vector<Point2f> allimgpt[2];
        for( k = 0; k < 2; k++ )
        {
            for( i = 0; i < nimages; i++ )
                std::copy(imagePoints[k][i].begin(), imagePoints[k][i].end(), back_inserter(allimgpt[k]));
        }
        F = findFundamentalMat(Mat(allimgpt[0]), Mat(allimgpt[1]), FM_8POINT, 0, 0);
        Mat H1, H2;
        stereoRectifyUncalibrated(Mat(allimgpt[0]), Mat(allimgpt[1]), F, imageSize, H1, H2, 3);


        R1 = cameraMatrix[0].inv()*H1*cameraMatrix[0];
        R2 = cameraMatrix[1].inv()*H2*cameraMatrix[1];
        P1 = cameraMatrix[0];
        P2 = cameraMatrix[1];
    }


/*
根據stereoRectify 計算出來的R 和 P 來計算影象的對映表 mapx,mapy
mapx,mapy這兩個對映表接下來可以給remap()函式呼叫,來校正影象,使得兩幅影象共面並且行對準
ininUndistortRectifyMap()的引數newCameraMatrix就是校正後的攝像機矩陣。在openCV裡面,校正後的計算機矩陣Mrect是跟投影矩陣P一起返回的。
所以我們在這裡傳入投影矩陣P,此函式可以從投影矩陣P中讀出校正後的攝像機矩陣
*/


    //Precompute maps for cv::remap()
    initUndistortRectifyMap(cameraMatrix[0], distCoeffs[0], R1, P1, imageSize, CV_16SC2, rmap[0][0], rmap[0][1]);
    initUndistortRectifyMap(cameraMatrix[1], distCoeffs[1], R2, P2, imageSize, CV_16SC2, rmap[1][0], rmap[1][1]);


/*
顯示校正結果
把左右兩幅影象顯示到同一個畫面上
這裡只顯示了最後一副影象的校正結果。並沒有把所有的影象都顯示出來
*/


    Mat canvas;
    double sf;
    int w, h;
    if( !isVerticalStereo )
    {
        sf = 600./MAX(imageSize.width, imageSize.height);
        w = cvRound(imageSize.width*sf);
        h = cvRound(imageSize.height*sf);
        canvas.create(h, w*2, CV_8UC3);
    }
    else
    {
        sf = 300./MAX(imageSize.width, imageSize.height);
        w = cvRound(imageSize.width*sf);
        h = cvRound(imageSize.height*sf);
        canvas.create(h*2, w, CV_8UC3);
    }


    for( i = 0; i < nimages; i++ )
    {
        for( k = 0; k < 2; k++ )
        {
            Mat img = imread(goodImageList[i*2+k], 0), rimg, cimg;
            remap(img, rimg, rmap[k][0], rmap[k][1], INTER_LINEAR);//對準左右影象,
            cvtColor(rimg, cimg, COLOR_GRAY2BGR);
            Mat canvasPart = !isVerticalStereo ? canvas(Rect(w*k, 0, w, h)) : canvas(Rect(0, h*k, w, h));
            resize(cimg, canvasPart, canvasPart.size(), 0, 0, INTER_AREA);
            if( useCalibrated )
            {
                Rect vroi(cvRound(validRoi[k].x*sf), cvRound(validRoi[k].y*sf),
                          cvRound(validRoi[k].width*sf), cvRound(validRoi[k].height*sf));
                rectangle(canvasPart, vroi, Scalar(0,0,255), 3, 8);
            }
        }


        if( !isVerticalStereo ) //畫上對應的線條 
            for( j = 0; j < canvas.rows; j += 16 )
                line(canvas, Point(0, j), Point(canvas.cols, j), Scalar(0, 255, 0), 1, 8); //畫平行線 
        else
            for( j = 0; j < canvas.cols; j += 16 )
                line(canvas, Point(j, 0), Point(j, canvas.rows), Scalar(0, 255, 0), 1, 8);
        imshow("rectified", canvas);//輸出立體校正後的圖片
        char c = (char)waitKey();
        if( c == 27 || c == 'q' || c == 'Q' )
            break;
    }
}




static bool readStringList( const string& filename, vector<string>& l )
{
    l.resize(0);
    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;
}


int main(int argc, char** argv)
{
    Size boardSize;
    string imagelistfn;
    bool showRectified;
    cv::CommandLineParser parser(argc, argv, "{w|9|}{h|6|}{s|1.0|}{nr||}{help||}{@input|stereo_calib.xml|}");
    if (parser.has("help"))
        return print_help();
    showRectified = !parser.has("nr");
    imagelistfn = parser.get<string>("@input");
    boardSize.width = parser.get<int>("w");//獲取影象的寬
    boardSize.height = parser.get<int>("h");//獲取影象的高
    float squareSize = parser.get<float>("s");//正方形棋盤格子 邊長
    if (!parser.check())//標定板 格子尺寸引數錯誤 
    {
        parser.printErrors();
        return 1;
    }
    vector<string> imagelist;//定義個一個字串容器存放影象列表
    bool ok = readStringList(imagelistfn, imagelist);
    if(!ok || imagelist.empty())
    {
        cout << "can not open " << imagelistfn << " or the string list is empty" << endl;
        return print_help();
    }
//標定的主程式
    StereoCalib(imagelist, boardSize, squareSize, false, true, showRectified);
    return 0;
}