Advertisement
Guest User

stereo_calib

a guest
Nov 23rd, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 13.83 KB | None | 0 0
  1. /* This is sample from the OpenCV book. The copyright notice is below */
  2.  
  3. /* *************** License:**************************
  4.    Oct. 3, 2008
  5.    Right to use this code in any way you want without warranty, support or any guarantee of it working.
  6.  
  7.    BOOK: It would be nice if you cited it:
  8.    Learning OpenCV: Computer Vision with the OpenCV Library
  9.      by Gary Bradski and Adrian Kaehler
  10.      Published by O'Reilly Media, October 3, 2008
  11.  
  12.    AVAILABLE AT:
  13.      http://www.amazon.com/Learning-OpenCV-Computer-Vision-Library/dp/0596516134
  14.      Or: http://oreilly.com/catalog/9780596516130/
  15.      ISBN-10: 0596516134 or: ISBN-13: 978-0596516130
  16.  
  17.    OPENCV WEBSITES:
  18.      Homepage:      http://opencv.org
  19.      Online docs:   http://docs.opencv.org
  20.      Q&A forum:     http://answers.opencv.org
  21.      Issue tracker: http://code.opencv.org
  22.      GitHub:        https://github.com/Itseez/opencv/
  23.    ************************************************** */
  24.  
  25. #include "opencv2/calib3d/calib3d.hpp"
  26. #include "opencv2/highgui/highgui.hpp"
  27. #include "opencv2/imgproc/imgproc.hpp"
  28.  
  29. #include <vector>
  30. #include <string>
  31. #include <algorithm>
  32. #include <iostream>
  33. #include <iterator>
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <ctype.h>
  37.  
  38. using namespace cv;
  39. using namespace std;
  40.  
  41. static int print_help()
  42. {
  43.     cout <<
  44.             " Given a list of chessboard images, the number of corners (nx, ny)\n"
  45.             " on the chessboards, and a flag: useCalibrated for \n"
  46.             "   calibrated (0) or\n"
  47.             "   uncalibrated \n"
  48.             "     (1: use cvStereoCalibrate(), 2: compute fundamental\n"
  49.             "         matrix separately) stereo. \n"
  50.             " Calibrate the cameras and display the\n"
  51.             " rectified results along with the computed disparity images.   \n" << endl;
  52.     cout << "Usage:\n ./stereo_calib -w board_width -h board_height [-nr /*dot not view results*/] <image list XML/YML file>\n" << endl;
  53.     return 0;
  54. }
  55.  
  56.  
  57. static void
  58. StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=true, bool showRectified=true)
  59. {
  60.     if( imagelist.size() % 2 != 0 )
  61.     {
  62.         cout << "Error: the image list contains odd (non-even) number of elements\n";
  63.         return;
  64.     }
  65.  
  66.     bool displayCorners = false;//true;
  67.     const int maxScale = 2;
  68.     const float squareSize = 1.f;  // Set this to your actual square size
  69.     // ARRAY AND VECTOR STORAGE:
  70.  
  71.     vector<vector<Point2f> > imagePoints[2];
  72.     vector<vector<Point3f> > objectPoints;
  73.     Size imageSize;
  74.  
  75.     int i, j, k, nimages = (int)imagelist.size()/2;
  76.  
  77.     imagePoints[0].resize(nimages);
  78.     imagePoints[1].resize(nimages);
  79.     vector<string> goodImageList;
  80.  
  81.     for( i = j = 0; i < nimages; i++ )
  82.     {
  83.         for( k = 0; k < 2; k++ )
  84.         {
  85.             const string& filename = imagelist[i*2+k];
  86.             Mat img = imread(filename, 0);
  87.             if(img.empty())
  88.                 break;
  89.             if( imageSize == Size() )
  90.                 imageSize = img.size();
  91.             else if( img.size() != imageSize )
  92.             {
  93.                 cout << "The image " << filename << " has the size different from the first image size. Skipping the pair\n";
  94.                 break;
  95.             }
  96.             bool found = false;
  97.             vector<Point2f>& corners = imagePoints[k][j];
  98.             for( int scale = 1; scale <= maxScale; scale++ )
  99.             {
  100.                 Mat timg;
  101.                 if( scale == 1 )
  102.                     timg = img;
  103.                 else
  104.                     resize(img, timg, Size(), scale, scale);
  105.                 found = findChessboardCorners(timg, boardSize, corners,
  106.                     CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE);
  107.                 if( found )
  108.                 {
  109.                     if( scale > 1 )
  110.                     {
  111.                         Mat cornersMat(corners);
  112.                         cornersMat *= 1./scale;
  113.                     }
  114.                     break;
  115.                 }
  116.             }
  117.             if( displayCorners )
  118.             {
  119.                 cout << filename << endl;
  120.                 Mat cimg, cimg1;
  121.                 cvtColor(img, cimg, COLOR_GRAY2BGR);
  122.                 drawChessboardCorners(cimg, boardSize, corners, found);
  123.                 double sf = 640./MAX(img.rows, img.cols);
  124.                 resize(cimg, cimg1, Size(), sf, sf);
  125.                 imshow("corners", cimg1);
  126.                 char c = (char)waitKey(500);
  127.                 if( c == 27 || c == 'q' || c == 'Q' ) //Allow ESC to quit
  128.                     exit(-1);
  129.             }
  130.             else
  131.                 putchar('.');
  132.             if( !found )
  133.                 break;
  134.             cornerSubPix(img, corners, Size(11,11), Size(-1,-1),
  135.                          TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,
  136.                                       30, 0.01));
  137.         }
  138.         if( k == 2 )
  139.         {
  140.             goodImageList.push_back(imagelist[i*2]);
  141.             goodImageList.push_back(imagelist[i*2+1]);
  142.             j++;
  143.         }
  144.     }
  145.     cout << j << " pairs have been successfully detected.\n";
  146.     nimages = j;
  147.     if( nimages < 2 )
  148.     {
  149.         cout << "Error: too little pairs to run the calibration\n";
  150.         return;
  151.     }
  152.  
  153.     imagePoints[0].resize(nimages);
  154.     imagePoints[1].resize(nimages);
  155.     objectPoints.resize(nimages);
  156.  
  157.     for( i = 0; i < nimages; i++ )
  158.     {
  159.         for( j = 0; j < boardSize.height; j++ )
  160.             for( k = 0; k < boardSize.width; k++ )
  161.                 objectPoints[i].push_back(Point3f(j*squareSize, k*squareSize, 0));
  162.     }
  163.  
  164.     cout << "Running stereo calibration ...\n";
  165.  
  166.     Mat cameraMatrix[2], distCoeffs[2];
  167.     cameraMatrix[0] = Mat::eye(3, 3, CV_64F);
  168.     cameraMatrix[1] = Mat::eye(3, 3, CV_64F);
  169.     Mat R, T, E, F;
  170.  
  171.     double rms = stereoCalibrate(objectPoints, imagePoints[0], imagePoints[1],
  172.                     cameraMatrix[0], distCoeffs[0],
  173.                     cameraMatrix[1], distCoeffs[1],
  174.                     imageSize, R, T, E, F,
  175.                     TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, 1e-5),
  176.                     CV_CALIB_FIX_ASPECT_RATIO +
  177.                     CV_CALIB_ZERO_TANGENT_DIST +
  178.                     CV_CALIB_SAME_FOCAL_LENGTH +
  179.                     CV_CALIB_RATIONAL_MODEL +
  180.                     CV_CALIB_FIX_K3 + CV_CALIB_FIX_K4 + CV_CALIB_FIX_K5);
  181.     cout << "done with RMS error=" << rms << endl;
  182.  
  183. // CALIBRATION QUALITY CHECK
  184. // because the output fundamental matrix implicitly
  185. // includes all the output information,
  186. // we can check the quality of calibration using the
  187. // epipolar geometry constraint: m2^t*F*m1=0
  188.     double err = 0;
  189.     int npoints = 0;
  190.     vector<Vec3f> lines[2];
  191.     for( i = 0; i < nimages; i++ )
  192.     {
  193.         int npt = (int)imagePoints[0][i].size();
  194.         Mat imgpt[2];
  195.         for( k = 0; k < 2; k++ )
  196.         {
  197.             imgpt[k] = Mat(imagePoints[k][i]);
  198.             undistortPoints(imgpt[k], imgpt[k], cameraMatrix[k], distCoeffs[k], Mat(), cameraMatrix[k]);
  199.             computeCorrespondEpilines(imgpt[k], k+1, F, lines[k]);
  200.         }
  201.         for( j = 0; j < npt; j++ )
  202.         {
  203.             double errij = fabs(imagePoints[0][i][j].x*lines[1][j][0] +
  204.                                 imagePoints[0][i][j].y*lines[1][j][1] + lines[1][j][2]) +
  205.                            fabs(imagePoints[1][i][j].x*lines[0][j][0] +
  206.                                 imagePoints[1][i][j].y*lines[0][j][1] + lines[0][j][2]);
  207.             err += errij;
  208.         }
  209.         npoints += npt;
  210.     }
  211.     cout << "average reprojection err = " <<  err/npoints << endl;
  212.  
  213.     // save intrinsic parameters
  214.     FileStorage fs("intrinsics.yml", CV_STORAGE_WRITE);
  215.     if( fs.isOpened() )
  216.     {
  217.         fs << "M1" << cameraMatrix[0] << "D1" << distCoeffs[0] <<
  218.             "M2" << cameraMatrix[1] << "D2" << distCoeffs[1];
  219.         fs.release();
  220.     }
  221.     else
  222.         cout << "Error: can not save the intrinsic parameters\n";
  223.  
  224.     Mat R1, R2, P1, P2, Q;
  225.     Rect validRoi[2];
  226.  
  227.     stereoRectify(cameraMatrix[0], distCoeffs[0],
  228.                   cameraMatrix[1], distCoeffs[1],
  229.                   imageSize, R, T, R1, R2, P1, P2, Q,
  230.                   CALIB_ZERO_DISPARITY, 1, imageSize, &validRoi[0], &validRoi[1]);
  231.  
  232.     fs.open("extrinsics.yml", CV_STORAGE_WRITE);
  233.     if( fs.isOpened() )
  234.     {
  235.         fs << "R" << R << "T" << T << "R1" << R1 << "R2" << R2 << "P1" << P1 << "P2" << P2 << "Q" << Q;
  236.         fs.release();
  237.     }
  238.     else
  239.         cout << "Error: can not save the intrinsic parameters\n";
  240.  
  241.     // OpenCV can handle left-right
  242.     // or up-down camera arrangements
  243.     bool isVerticalStereo = fabs(P2.at<double>(1, 3)) > fabs(P2.at<double>(0, 3));
  244.  
  245. // COMPUTE AND DISPLAY RECTIFICATION
  246.     if( !showRectified )
  247.         return;
  248.  
  249.     Mat rmap[2][2];
  250. // IF BY CALIBRATED (BOUGUET'S METHOD)
  251.     if( useCalibrated )
  252.     {
  253.         // we already computed everything
  254.     }
  255. // OR ELSE HARTLEY'S METHOD
  256.     else
  257.  // use intrinsic parameters of each camera, but
  258.  // compute the rectification transformation directly
  259.  // from the fundamental matrix
  260.     {
  261.         vector<Point2f> allimgpt[2];
  262.         for( k = 0; k < 2; k++ )
  263.         {
  264.             for( i = 0; i < nimages; i++ )
  265.                 std::copy(imagePoints[k][i].begin(), imagePoints[k][i].end(), back_inserter(allimgpt[k]));
  266.         }
  267.         F = findFundamentalMat(Mat(allimgpt[0]), Mat(allimgpt[1]), FM_8POINT, 0, 0);
  268.         Mat H1, H2;
  269.         stereoRectifyUncalibrated(Mat(allimgpt[0]), Mat(allimgpt[1]), F, imageSize, H1, H2, 3);
  270.  
  271.         R1 = cameraMatrix[0].inv()*H1*cameraMatrix[0];
  272.         R2 = cameraMatrix[1].inv()*H2*cameraMatrix[1];
  273.         P1 = cameraMatrix[0];
  274.         P2 = cameraMatrix[1];
  275.     }
  276.  
  277.     //Precompute maps for cv::remap()
  278.     initUndistortRectifyMap(cameraMatrix[0], distCoeffs[0], R1, P1, imageSize, CV_16SC2, rmap[0][0], rmap[0][1]);
  279.     initUndistortRectifyMap(cameraMatrix[1], distCoeffs[1], R2, P2, imageSize, CV_16SC2, rmap[1][0], rmap[1][1]);
  280.  
  281.     Mat canvas;
  282.     double sf;
  283.     int w, h;
  284.     if( !isVerticalStereo )
  285.     {
  286.         sf = 600./MAX(imageSize.width, imageSize.height);
  287.         w = cvRound(imageSize.width*sf);
  288.         h = cvRound(imageSize.height*sf);
  289.         canvas.create(h, w*2, CV_8UC3);
  290.     }
  291.     else
  292.     {
  293.         sf = 300./MAX(imageSize.width, imageSize.height);
  294.         w = cvRound(imageSize.width*sf);
  295.         h = cvRound(imageSize.height*sf);
  296.         canvas.create(h*2, w, CV_8UC3);
  297.     }
  298.  
  299.     for( i = 0; i < nimages; i++ )
  300.     {
  301.         for( k = 0; k < 2; k++ )
  302.         {
  303.             Mat img = imread(goodImageList[i*2+k], 0), rimg, cimg;
  304.             remap(img, rimg, rmap[k][0], rmap[k][1], CV_INTER_LINEAR);
  305.             cvtColor(rimg, cimg, COLOR_GRAY2BGR);
  306.             Mat canvasPart = !isVerticalStereo ? canvas(Rect(w*k, 0, w, h)) : canvas(Rect(0, h*k, w, h));
  307.             resize(cimg, canvasPart, canvasPart.size(), 0, 0, CV_INTER_AREA);
  308.             if( useCalibrated )
  309.             {
  310.                 Rect vroi(cvRound(validRoi[k].x*sf), cvRound(validRoi[k].y*sf),
  311.                           cvRound(validRoi[k].width*sf), cvRound(validRoi[k].height*sf));
  312.                 rectangle(canvasPart, vroi, Scalar(0,0,255), 3, 8);
  313.             }
  314.         }
  315.  
  316.         if( !isVerticalStereo )
  317.             for( j = 0; j < canvas.rows; j += 16 )
  318.                 line(canvas, Point(0, j), Point(canvas.cols, j), Scalar(0, 255, 0), 1, 8);
  319.         else
  320.             for( j = 0; j < canvas.cols; j += 16 )
  321.                 line(canvas, Point(j, 0), Point(j, canvas.rows), Scalar(0, 255, 0), 1, 8);
  322.         imshow("rectified", canvas);
  323.         char c = (char)waitKey();
  324.         if( c == 27 || c == 'q' || c == 'Q' )
  325.             break;
  326.     }
  327. }
  328.  
  329.  
  330. static bool readStringList( const string& filename, vector<string>& l )
  331. {
  332.     l.resize(0);
  333.     FileStorage fs(filename, FileStorage::READ);
  334.     if( !fs.isOpened() )
  335.         return false;
  336.     FileNode n = fs.getFirstTopLevelNode();
  337.     if( n.type() != FileNode::SEQ )
  338.         return false;
  339.     FileNodeIterator it = n.begin(), it_end = n.end();
  340.     for( ; it != it_end; ++it )
  341.         l.push_back((string)*it);
  342.     return true;
  343. }
  344.  
  345. int main(int argc, char** argv)
  346. {
  347.     Size boardSize;
  348.     string imagelistfn;
  349.     bool showRectified = true;
  350.  
  351.     for( int i = 1; i < argc; i++ )
  352.     {
  353.         if( string(argv[i]) == "-w" )
  354.         {
  355.             if( sscanf(argv[++i], "%d", &boardSize.width) != 1 || boardSize.width <= 0 )
  356.             {
  357.                 cout << "invalid board width" << endl;
  358.                 return print_help();
  359.             }
  360.         }
  361.         else if( string(argv[i]) == "-h" )
  362.         {
  363.             if( sscanf(argv[++i], "%d", &boardSize.height) != 1 || boardSize.height <= 0 )
  364.             {
  365.                 cout << "invalid board height" << endl;
  366.                 return print_help();
  367.             }
  368.         }
  369.         else if( string(argv[i]) == "-nr" )
  370.             showRectified = false;
  371.         else if( string(argv[i]) == "--help" )
  372.             return print_help();
  373.         else if( argv[i][0] == '-' )
  374.         {
  375.             cout << "invalid option " << argv[i] << endl;
  376.             return 0;
  377.         }
  378.         else
  379.             imagelistfn = argv[i];
  380.     }
  381.  
  382.     if( imagelistfn == "" )
  383.     {
  384.         imagelistfn = "stereo_calib.xml";
  385.         boardSize = Size(10, 7);
  386.     }
  387.     else if( boardSize.width <= 0 || boardSize.height <= 0 )
  388.     {
  389.         cout << "if you specified XML file with chessboards, you should also specify the board width and height (-w and -h options)" << endl;
  390.         return 0;
  391.     }
  392.  
  393.     vector<string> imagelist;
  394.     bool ok = readStringList(imagelistfn, imagelist);
  395.     if(!ok || imagelist.empty())
  396.     {
  397.         cout << "can not open " << imagelistfn << " or the string list is empty" << endl;
  398.         return print_help();
  399.     }
  400.  
  401.     StereoCalib(imagelist, boardSize, true, showRectified);
  402.     return 0;
  403. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement