stereo_calib.cpp 13 KB

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