stereo_calib.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 "opencv2/objdetect/charuco_detector.hpp"
  23. #include <vector>
  24. #include <string>
  25. #include <algorithm>
  26. #include <iostream>
  27. #include <iterator>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <ctype.h>
  31. using namespace cv;
  32. using namespace std;
  33. static int print_help(char** argv)
  34. {
  35. cout <<
  36. " Given a list of chessboard or ChArUco images, the number of corners (nx, ny)\n"
  37. " on the chessboards and the number of squares (nx, ny) on ChArUco,\n"
  38. " and a flag: useCalibrated for \n"
  39. " calibrated (0) or\n"
  40. " uncalibrated \n"
  41. " (1: use stereoCalibrate(), 2: compute fundamental\n"
  42. " matrix separately) stereo. \n"
  43. " Calibrate the cameras and display the\n"
  44. " rectified results along with the computed disparity images. \n" << endl;
  45. cout << "Usage:\n " << argv[0] << " -w=<board_width default=9> -h=<board_height default=6>"
  46. <<" -t=<pattern type: chessboard or charucoboard default=chessboard> -s=<square_size default=1.0> -ms=<marker size default=0.5>"
  47. <<" -ad=<predefined aruco dictionary name default=DICT_4X4_50> -adf=<aruco dictionary file default=None>"
  48. <<" <image list XML/YML file default=stereo_calib.xml>\n" << endl;
  49. cout << "Available Aruco dictionaries: DICT_4X4_50, DICT_4X4_100, DICT_4X4_250, "
  50. << "DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250, DICT_5X5_1000, "
  51. << "DICT_6X6_50, DICT_6X6_100, DICT_6X6_250, DICT_6X6_1000, DICT_7X7_50, "
  52. << "DICT_7X7_100, DICT_7X7_250, DICT_7X7_1000, DICT_ARUCO_ORIGINAL, "
  53. << "DICT_APRILTAG_16h5, DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11\n";
  54. return 0;
  55. }
  56. static void
  57. StereoCalib(const vector<string>& imagelist, Size inputBoardSize, string type, float squareSize, float markerSize, cv::aruco::PredefinedDictionaryType arucoDict, string arucoDictFile, bool displayCorners = false, bool useCalibrated=true, bool showRectified=true)
  58. {
  59. if( imagelist.size() % 2 != 0 )
  60. {
  61. cout << "Error: the image list contains odd (non-even) number of elements\n";
  62. return;
  63. }
  64. const int maxScale = 2;
  65. // ARRAY AND VECTOR STORAGE:
  66. vector<vector<Point2f> > imagePoints[2];
  67. vector<vector<Point3f> > objectPoints;
  68. Size imageSize;
  69. int i, j, k, nimages = (int)imagelist.size()/2;
  70. imagePoints[0].resize(nimages);
  71. imagePoints[1].resize(nimages);
  72. vector<string> goodImageList;
  73. Size boardSizeInnerCorners, boardSizeUnits;
  74. if (type == "chessboard") {
  75. //chess board pattern boardSize is given in inner corners
  76. boardSizeInnerCorners = inputBoardSize;
  77. boardSizeUnits.height = inputBoardSize.height+1;
  78. boardSizeUnits.width = inputBoardSize.width+1;
  79. }
  80. else if (type == "charucoboard") {
  81. //ChArUco board pattern boardSize is given in squares units
  82. boardSizeUnits = inputBoardSize;
  83. boardSizeInnerCorners.width = inputBoardSize.width - 1;
  84. boardSizeInnerCorners.height = inputBoardSize.height - 1;
  85. }
  86. else {
  87. std::cout << "unknown pattern type " << type << "\n";
  88. return;
  89. }
  90. cv::aruco::Dictionary dictionary;
  91. if (arucoDictFile == "None") {
  92. dictionary = cv::aruco::getPredefinedDictionary(arucoDict);
  93. }
  94. else {
  95. cv::FileStorage dict_file(arucoDictFile, cv::FileStorage::Mode::READ);
  96. cv::FileNode fn(dict_file.root());
  97. dictionary.readDictionary(fn);
  98. }
  99. cv::aruco::CharucoBoard ch_board(boardSizeUnits, squareSize, markerSize, dictionary);
  100. cv::aruco::CharucoDetector ch_detector(ch_board);
  101. std::vector<int> markerIds;
  102. for( i = j = 0; i < nimages; i++ )
  103. {
  104. for( k = 0; k < 2; k++ )
  105. {
  106. const string& filename = imagelist[i*2+k];
  107. Mat img = imread(filename, IMREAD_GRAYSCALE);
  108. if(img.empty())
  109. break;
  110. if( imageSize == Size() )
  111. imageSize = img.size();
  112. else if( img.size() != imageSize )
  113. {
  114. cout << "The image " << filename << " has the size different from the first image size. Skipping the pair\n";
  115. break;
  116. }
  117. bool found = false;
  118. vector<Point2f>& corners = imagePoints[k][j];
  119. for( int scale = 1; scale <= maxScale; scale++ )
  120. {
  121. Mat timg;
  122. if( scale == 1 )
  123. timg = img;
  124. else
  125. resize(img, timg, Size(), scale, scale, INTER_LINEAR_EXACT);
  126. if (type == "chessboard") {
  127. found = findChessboardCorners(timg, boardSizeInnerCorners, corners,
  128. CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_NORMALIZE_IMAGE);
  129. }
  130. else if (type == "charucoboard") {
  131. ch_detector.detectBoard(timg, corners, markerIds);
  132. found = corners.size() == (size_t) (boardSizeInnerCorners.height*boardSizeInnerCorners.width);
  133. }
  134. else {
  135. cout << "Error: unknown pattern " << type << "\n";
  136. return;
  137. }
  138. if( found )
  139. {
  140. if( scale > 1 )
  141. {
  142. Mat cornersMat(corners);
  143. cornersMat *= 1./scale;
  144. }
  145. break;
  146. }
  147. }
  148. if( displayCorners )
  149. {
  150. cout << filename << endl;
  151. Mat cimg, cimg1;
  152. cvtColor(img, cimg, COLOR_GRAY2BGR);
  153. drawChessboardCorners(cimg, boardSizeInnerCorners, corners, found);
  154. double sf = 640./MAX(img.rows, img.cols);
  155. resize(cimg, cimg1, Size(), sf, sf, INTER_LINEAR_EXACT);
  156. imshow("corners", cimg1);
  157. char c = (char)waitKey(500);
  158. if( c == 27 || c == 'q' || c == 'Q' ) //Allow ESC to quit
  159. exit(-1);
  160. }
  161. else
  162. putchar('.');
  163. if( !found )
  164. break;
  165. if (type == "chessboard") {
  166. cornerSubPix(img, corners, Size(11, 11), Size(-1, -1),
  167. TermCriteria(TermCriteria::COUNT + TermCriteria::EPS,
  168. 30, 0.01));
  169. }
  170. }
  171. if( k == 2 )
  172. {
  173. goodImageList.push_back(imagelist[i*2]);
  174. goodImageList.push_back(imagelist[i*2+1]);
  175. j++;
  176. }
  177. }
  178. cout << j << " pairs have been successfully detected.\n";
  179. nimages = j;
  180. if( nimages < 2 )
  181. {
  182. cout << "Error: too little pairs to run the calibration\n";
  183. return;
  184. }
  185. imagePoints[0].resize(nimages);
  186. imagePoints[1].resize(nimages);
  187. objectPoints.resize(nimages);
  188. for( i = 0; i < nimages; i++ )
  189. {
  190. for( j = 0; j < boardSizeInnerCorners.height; j++ )
  191. for( k = 0; k < boardSizeInnerCorners.width; k++ )
  192. objectPoints[i].push_back(Point3f(k*squareSize, j*squareSize, 0));
  193. }
  194. cout << "Running stereo calibration ...\n";
  195. Mat cameraMatrix[2], distCoeffs[2];
  196. cameraMatrix[0] = initCameraMatrix2D(objectPoints,imagePoints[0],imageSize,0);
  197. cameraMatrix[1] = initCameraMatrix2D(objectPoints,imagePoints[1],imageSize,0);
  198. Mat R, T, E, F;
  199. double rms = stereoCalibrate(objectPoints, imagePoints[0], imagePoints[1],
  200. cameraMatrix[0], distCoeffs[0],
  201. cameraMatrix[1], distCoeffs[1],
  202. imageSize, R, T, E, F,
  203. CALIB_FIX_ASPECT_RATIO +
  204. CALIB_ZERO_TANGENT_DIST +
  205. CALIB_USE_INTRINSIC_GUESS +
  206. CALIB_SAME_FOCAL_LENGTH +
  207. CALIB_RATIONAL_MODEL +
  208. CALIB_FIX_K3 + CALIB_FIX_K4 + CALIB_FIX_K5,
  209. TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 100, 1e-5) );
  210. cout << "done with RMS error=" << rms << endl;
  211. // CALIBRATION QUALITY CHECK
  212. // because the output fundamental matrix implicitly
  213. // includes all the output information,
  214. // we can check the quality of calibration using the
  215. // epipolar geometry constraint: m2^t*F*m1=0
  216. double err = 0;
  217. int npoints = 0;
  218. vector<Vec3f> lines[2];
  219. for( i = 0; i < nimages; i++ )
  220. {
  221. int npt = (int)imagePoints[0][i].size();
  222. Mat imgpt[2];
  223. for( k = 0; k < 2; k++ )
  224. {
  225. imgpt[k] = Mat(imagePoints[k][i]);
  226. undistortPoints(imgpt[k], imgpt[k], cameraMatrix[k], distCoeffs[k], Mat(), cameraMatrix[k]);
  227. computeCorrespondEpilines(imgpt[k], k+1, F, lines[k]);
  228. }
  229. for( j = 0; j < npt; j++ )
  230. {
  231. double errij = fabs(imagePoints[0][i][j].x*lines[1][j][0] +
  232. imagePoints[0][i][j].y*lines[1][j][1] + lines[1][j][2]) +
  233. fabs(imagePoints[1][i][j].x*lines[0][j][0] +
  234. imagePoints[1][i][j].y*lines[0][j][1] + lines[0][j][2]);
  235. err += errij;
  236. }
  237. npoints += npt;
  238. }
  239. cout << "average epipolar err = " << err/npoints << endl;
  240. // save intrinsic parameters
  241. FileStorage fs("intrinsics.yml", FileStorage::WRITE);
  242. if( fs.isOpened() )
  243. {
  244. fs << "M1" << cameraMatrix[0] << "D1" << distCoeffs[0] <<
  245. "M2" << cameraMatrix[1] << "D2" << distCoeffs[1];
  246. fs.release();
  247. }
  248. else
  249. cout << "Error: can not save the intrinsic parameters\n";
  250. Mat R1, R2, P1, P2, Q;
  251. Rect validRoi[2];
  252. stereoRectify(cameraMatrix[0], distCoeffs[0],
  253. cameraMatrix[1], distCoeffs[1],
  254. imageSize, R, T, R1, R2, P1, P2, Q,
  255. CALIB_ZERO_DISPARITY, 1, imageSize, &validRoi[0], &validRoi[1]);
  256. fs.open("extrinsics.yml", FileStorage::WRITE);
  257. if( fs.isOpened() )
  258. {
  259. fs << "R" << R << "T" << T << "R1" << R1 << "R2" << R2 << "P1" << P1 << "P2" << P2 << "Q" << Q;
  260. fs.release();
  261. }
  262. else
  263. cout << "Error: can not save the extrinsic parameters\n";
  264. // OpenCV can handle left-right
  265. // or up-down camera arrangements
  266. bool isVerticalStereo = fabs(P2.at<double>(1, 3)) > fabs(P2.at<double>(0, 3));
  267. // COMPUTE AND DISPLAY RECTIFICATION
  268. if( !showRectified )
  269. return;
  270. Mat rmap[2][2];
  271. // IF BY CALIBRATED (BOUGUET'S METHOD)
  272. if( useCalibrated )
  273. {
  274. // we already computed everything
  275. }
  276. // OR ELSE HARTLEY'S METHOD
  277. else
  278. // use intrinsic parameters of each camera, but
  279. // compute the rectification transformation directly
  280. // from the fundamental matrix
  281. {
  282. vector<Point2f> allimgpt[2];
  283. for( k = 0; k < 2; k++ )
  284. {
  285. for( i = 0; i < nimages; i++ )
  286. std::copy(imagePoints[k][i].begin(), imagePoints[k][i].end(), back_inserter(allimgpt[k]));
  287. }
  288. F = findFundamentalMat(Mat(allimgpt[0]), Mat(allimgpt[1]), FM_8POINT, 0, 0);
  289. Mat H1, H2;
  290. stereoRectifyUncalibrated(Mat(allimgpt[0]), Mat(allimgpt[1]), F, imageSize, H1, H2, 3);
  291. R1 = cameraMatrix[0].inv()*H1*cameraMatrix[0];
  292. R2 = cameraMatrix[1].inv()*H2*cameraMatrix[1];
  293. P1 = cameraMatrix[0];
  294. P2 = cameraMatrix[1];
  295. }
  296. //Precompute maps for cv::remap()
  297. initUndistortRectifyMap(cameraMatrix[0], distCoeffs[0], R1, P1, imageSize, CV_16SC2, rmap[0][0], rmap[0][1]);
  298. initUndistortRectifyMap(cameraMatrix[1], distCoeffs[1], R2, P2, imageSize, CV_16SC2, rmap[1][0], rmap[1][1]);
  299. Mat canvas;
  300. double sf;
  301. int w, h;
  302. if( !isVerticalStereo )
  303. {
  304. sf = 600./MAX(imageSize.width, imageSize.height);
  305. w = cvRound(imageSize.width*sf);
  306. h = cvRound(imageSize.height*sf);
  307. canvas.create(h, w*2, CV_8UC3);
  308. }
  309. else
  310. {
  311. sf = 300./MAX(imageSize.width, imageSize.height);
  312. w = cvRound(imageSize.width*sf);
  313. h = cvRound(imageSize.height*sf);
  314. canvas.create(h*2, w, CV_8UC3);
  315. }
  316. for( i = 0; i < nimages; i++ )
  317. {
  318. for( k = 0; k < 2; k++ )
  319. {
  320. Mat img = imread(goodImageList[i*2+k], IMREAD_GRAYSCALE), rimg, cimg;
  321. remap(img, rimg, rmap[k][0], rmap[k][1], INTER_LINEAR);
  322. cvtColor(rimg, cimg, COLOR_GRAY2BGR);
  323. Mat canvasPart = !isVerticalStereo ? canvas(Rect(w*k, 0, w, h)) : canvas(Rect(0, h*k, w, h));
  324. resize(cimg, canvasPart, canvasPart.size(), 0, 0, INTER_AREA);
  325. if( useCalibrated )
  326. {
  327. Rect vroi(cvRound(validRoi[k].x*sf), cvRound(validRoi[k].y*sf),
  328. cvRound(validRoi[k].width*sf), cvRound(validRoi[k].height*sf));
  329. rectangle(canvasPart, vroi, Scalar(0,0,255), 3, 8);
  330. }
  331. }
  332. if( !isVerticalStereo )
  333. for( j = 0; j < canvas.rows; j += 16 )
  334. line(canvas, Point(0, j), Point(canvas.cols, j), Scalar(0, 255, 0), 1, 8);
  335. else
  336. for( j = 0; j < canvas.cols; j += 16 )
  337. line(canvas, Point(j, 0), Point(j, canvas.rows), Scalar(0, 255, 0), 1, 8);
  338. imshow("rectified", canvas);
  339. char c = (char)waitKey();
  340. if( c == 27 || c == 'q' || c == 'Q' )
  341. break;
  342. }
  343. }
  344. static bool readStringList( const string& filename, vector<string>& l )
  345. {
  346. l.resize(0);
  347. FileStorage fs(filename, FileStorage::READ);
  348. if( !fs.isOpened() )
  349. return false;
  350. FileNode n = fs.getFirstTopLevelNode();
  351. if( n.type() != FileNode::SEQ )
  352. return false;
  353. FileNodeIterator it = n.begin(), it_end = n.end();
  354. for( ; it != it_end; ++it )
  355. l.push_back((string)*it);
  356. return true;
  357. }
  358. int main(int argc, char** argv)
  359. {
  360. Size inputBoardSize;
  361. string imagelistfn;
  362. bool showRectified;
  363. cv::CommandLineParser parser(argc, argv, "{w|9|}{h|6|}{t|chessboard|}{s|1.0|}{ms|0.5|}{ad|DICT_4X4_50|}{adf|None|}{nr||}{help||}{@input|stereo_calib.xml|}");
  364. if (parser.has("help"))
  365. return print_help(argv);
  366. showRectified = !parser.has("nr");
  367. imagelistfn = samples::findFile(parser.get<string>("@input"));
  368. inputBoardSize.width = parser.get<int>("w");
  369. inputBoardSize.height = parser.get<int>("h");
  370. string type = parser.get<string>("t");
  371. float squareSize = parser.get<float>("s");
  372. float markerSize = parser.get<float>("ms");
  373. string arucoDictName = parser.get<string>("ad");
  374. string arucoDictFile = parser.get<string>("adf");
  375. cv::aruco::PredefinedDictionaryType arucoDict;
  376. if (arucoDictName == "DICT_4X4_50") { arucoDict = cv::aruco::DICT_4X4_50; }
  377. else if (arucoDictName == "DICT_4X4_100") { arucoDict = cv::aruco::DICT_4X4_100; }
  378. else if (arucoDictName == "DICT_4X4_250") { arucoDict = cv::aruco::DICT_4X4_250; }
  379. else if (arucoDictName == "DICT_4X4_1000") { arucoDict = cv::aruco::DICT_4X4_1000; }
  380. else if (arucoDictName == "DICT_5X5_50") { arucoDict = cv::aruco::DICT_5X5_50; }
  381. else if (arucoDictName == "DICT_5X5_100") { arucoDict = cv::aruco::DICT_5X5_100; }
  382. else if (arucoDictName == "DICT_5X5_250") { arucoDict = cv::aruco::DICT_5X5_250; }
  383. else if (arucoDictName == "DICT_5X5_1000") { arucoDict = cv::aruco::DICT_5X5_1000; }
  384. else if (arucoDictName == "DICT_6X6_50") { arucoDict = cv::aruco::DICT_6X6_50; }
  385. else if (arucoDictName == "DICT_6X6_100") { arucoDict = cv::aruco::DICT_6X6_100; }
  386. else if (arucoDictName == "DICT_6X6_250") { arucoDict = cv::aruco::DICT_6X6_250; }
  387. else if (arucoDictName == "DICT_6X6_1000") { arucoDict = cv::aruco::DICT_6X6_1000; }
  388. else if (arucoDictName == "DICT_7X7_50") { arucoDict = cv::aruco::DICT_7X7_50; }
  389. else if (arucoDictName == "DICT_7X7_100") { arucoDict = cv::aruco::DICT_7X7_100; }
  390. else if (arucoDictName == "DICT_7X7_250") { arucoDict = cv::aruco::DICT_7X7_250; }
  391. else if (arucoDictName == "DICT_7X7_1000") { arucoDict = cv::aruco::DICT_7X7_1000; }
  392. else if (arucoDictName == "DICT_ARUCO_ORIGINAL") { arucoDict = cv::aruco::DICT_ARUCO_ORIGINAL; }
  393. else if (arucoDictName == "DICT_APRILTAG_16h5") { arucoDict = cv::aruco::DICT_APRILTAG_16h5; }
  394. else if (arucoDictName == "DICT_APRILTAG_25h9") { arucoDict = cv::aruco::DICT_APRILTAG_25h9; }
  395. else if (arucoDictName == "DICT_APRILTAG_36h10") { arucoDict = cv::aruco::DICT_APRILTAG_36h10; }
  396. else if (arucoDictName == "DICT_APRILTAG_36h11") { arucoDict = cv::aruco::DICT_APRILTAG_36h11; }
  397. else {
  398. cout << "incorrect name of aruco dictionary \n";
  399. return 1;
  400. }
  401. if (!parser.check())
  402. {
  403. parser.printErrors();
  404. return 1;
  405. }
  406. vector<string> imagelist;
  407. bool ok = readStringList(imagelistfn, imagelist);
  408. if(!ok || imagelist.empty())
  409. {
  410. cout << "can not open " << imagelistfn << " or the string list is empty" << endl;
  411. return print_help(argv);
  412. }
  413. StereoCalib(imagelist, inputBoardSize, type, squareSize, markerSize, arucoDict, arucoDictFile, false, true, showRectified);
  414. return 0;
  415. }