calibration.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. #include "opencv2/core.hpp"
  2. #include <opencv2/core/utility.hpp>
  3. #include "opencv2/imgproc.hpp"
  4. #include "opencv2/calib3d.hpp"
  5. #include "opencv2/imgcodecs.hpp"
  6. #include "opencv2/videoio.hpp"
  7. #include "opencv2/highgui.hpp"
  8. #include <cctype>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <time.h>
  12. #include <iostream>
  13. using namespace cv;
  14. using namespace std;
  15. const char * usage =
  16. " \nexample command line for calibration from a live feed.\n"
  17. " calibration -w=4 -h=5 -s=0.025 -o=camera.yml -op -oe\n"
  18. " \n"
  19. " example command line for calibration from a list of stored images:\n"
  20. " imagelist_creator image_list.xml *.png\n"
  21. " calibration -w=4 -h=5 -s=0.025 -o=camera.yml -op -oe image_list.xml\n"
  22. " where image_list.xml is the standard OpenCV XML/YAML\n"
  23. " use imagelist_creator to create the xml or yaml list\n"
  24. " file consisting of the list of strings, e.g.:\n"
  25. " \n"
  26. "<?xml version=\"1.0\"?>\n"
  27. "<opencv_storage>\n"
  28. "<images>\n"
  29. "view000.png\n"
  30. "view001.png\n"
  31. "<!-- view002.png -->\n"
  32. "view003.png\n"
  33. "view010.png\n"
  34. "one_extra_view.jpg\n"
  35. "</images>\n"
  36. "</opencv_storage>\n";
  37. const char* liveCaptureHelp =
  38. "When the live video from camera is used as input, the following hot-keys may be used:\n"
  39. " <ESC>, 'q' - quit the program\n"
  40. " 'g' - start capturing images\n"
  41. " 'u' - switch undistortion on/off\n";
  42. static void help(char** argv)
  43. {
  44. printf( "This is a camera calibration sample.\n"
  45. "Usage: %s\n"
  46. " -w=<board_width> # the number of inner corners per one of board dimension\n"
  47. " -h=<board_height> # the number of inner corners per another board dimension\n"
  48. " [-pt=<pattern>] # the type of pattern: chessboard or circles' grid\n"
  49. " [-n=<number_of_frames>] # the number of frames to use for calibration\n"
  50. " # (if not specified, it will be set to the number\n"
  51. " # of board views actually available)\n"
  52. " [-d=<delay>] # a minimum delay in ms between subsequent attempts to capture a next view\n"
  53. " # (used only for video capturing)\n"
  54. " [-s=<squareSize>] # square size in some user-defined units (1 by default)\n"
  55. " [-o=<out_camera_params>] # the output filename for intrinsic [and extrinsic] parameters\n"
  56. " [-op] # write detected feature points\n"
  57. " [-oe] # write extrinsic parameters\n"
  58. " [-oo] # write refined 3D object points\n"
  59. " [-zt] # assume zero tangential distortion\n"
  60. " [-a=<aspectRatio>] # fix aspect ratio (fx/fy)\n"
  61. " [-p] # fix the principal point at the center\n"
  62. " [-v] # flip the captured images around the horizontal axis\n"
  63. " [-V] # use a video file, and not an image list, uses\n"
  64. " # [input_data] string for the video file name\n"
  65. " [-su] # show undistorted images after calibration\n"
  66. " [-ws=<number_of_pixel>] # Half of search window for cornerSubPix (11 by default)\n"
  67. " [-dt=<distance>] # actual distance between top-left and top-right corners of\n"
  68. " # the calibration grid. If this parameter is specified, a more\n"
  69. " # accurate calibration method will be used which may be better\n"
  70. " # with inaccurate, roughly planar target.\n"
  71. " [input_data] # input data, one of the following:\n"
  72. " # - text file with a list of the images of the board\n"
  73. " # the text file can be generated with imagelist_creator\n"
  74. " # - name of video file with a video of the board\n"
  75. " # if input_data not specified, a live view from the camera is used\n"
  76. "\n", argv[0] );
  77. printf("\n%s",usage);
  78. printf( "\n%s", liveCaptureHelp );
  79. }
  80. enum { DETECTION = 0, CAPTURING = 1, CALIBRATED = 2 };
  81. enum Pattern { CHESSBOARD, CIRCLES_GRID, ASYMMETRIC_CIRCLES_GRID };
  82. static double computeReprojectionErrors(
  83. const vector<vector<Point3f> >& objectPoints,
  84. const vector<vector<Point2f> >& imagePoints,
  85. const vector<Mat>& rvecs, const vector<Mat>& tvecs,
  86. const Mat& cameraMatrix, const Mat& distCoeffs,
  87. vector<float>& perViewErrors )
  88. {
  89. vector<Point2f> imagePoints2;
  90. int i, totalPoints = 0;
  91. double totalErr = 0, err;
  92. perViewErrors.resize(objectPoints.size());
  93. for( i = 0; i < (int)objectPoints.size(); i++ )
  94. {
  95. projectPoints(Mat(objectPoints[i]), rvecs[i], tvecs[i],
  96. cameraMatrix, distCoeffs, imagePoints2);
  97. err = norm(Mat(imagePoints[i]), Mat(imagePoints2), NORM_L2);
  98. int n = (int)objectPoints[i].size();
  99. perViewErrors[i] = (float)std::sqrt(err*err/n);
  100. totalErr += err*err;
  101. totalPoints += n;
  102. }
  103. return std::sqrt(totalErr/totalPoints);
  104. }
  105. static void calcChessboardCorners(Size boardSize, float squareSize, vector<Point3f>& corners, Pattern patternType = CHESSBOARD)
  106. {
  107. corners.resize(0);
  108. switch(patternType)
  109. {
  110. case CHESSBOARD:
  111. case CIRCLES_GRID:
  112. for( int i = 0; i < boardSize.height; i++ )
  113. for( int j = 0; j < boardSize.width; j++ )
  114. corners.push_back(Point3f(float(j*squareSize),
  115. float(i*squareSize), 0));
  116. break;
  117. case ASYMMETRIC_CIRCLES_GRID:
  118. for( int i = 0; i < boardSize.height; i++ )
  119. for( int j = 0; j < boardSize.width; j++ )
  120. corners.push_back(Point3f(float((2*j + i % 2)*squareSize),
  121. float(i*squareSize), 0));
  122. break;
  123. default:
  124. CV_Error(Error::StsBadArg, "Unknown pattern type\n");
  125. }
  126. }
  127. static bool runCalibration( vector<vector<Point2f> > imagePoints,
  128. Size imageSize, Size boardSize, Pattern patternType,
  129. float squareSize, float aspectRatio,
  130. float grid_width, bool release_object,
  131. int flags, Mat& cameraMatrix, Mat& distCoeffs,
  132. vector<Mat>& rvecs, vector<Mat>& tvecs,
  133. vector<float>& reprojErrs,
  134. vector<Point3f>& newObjPoints,
  135. double& totalAvgErr)
  136. {
  137. cameraMatrix = Mat::eye(3, 3, CV_64F);
  138. if( flags & CALIB_FIX_ASPECT_RATIO )
  139. cameraMatrix.at<double>(0,0) = aspectRatio;
  140. distCoeffs = Mat::zeros(8, 1, CV_64F);
  141. vector<vector<Point3f> > objectPoints(1);
  142. calcChessboardCorners(boardSize, squareSize, objectPoints[0], patternType);
  143. objectPoints[0][boardSize.width - 1].x = objectPoints[0][0].x + grid_width;
  144. newObjPoints = objectPoints[0];
  145. objectPoints.resize(imagePoints.size(),objectPoints[0]);
  146. double rms;
  147. int iFixedPoint = -1;
  148. if (release_object)
  149. iFixedPoint = boardSize.width - 1;
  150. rms = calibrateCameraRO(objectPoints, imagePoints, imageSize, iFixedPoint,
  151. cameraMatrix, distCoeffs, rvecs, tvecs, newObjPoints,
  152. flags | CALIB_FIX_K3 | CALIB_USE_LU);
  153. printf("RMS error reported by calibrateCamera: %g\n", rms);
  154. bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs);
  155. if (release_object) {
  156. cout << "New board corners: " << endl;
  157. cout << newObjPoints[0] << endl;
  158. cout << newObjPoints[boardSize.width - 1] << endl;
  159. cout << newObjPoints[boardSize.width * (boardSize.height - 1)] << endl;
  160. cout << newObjPoints.back() << endl;
  161. }
  162. objectPoints.clear();
  163. objectPoints.resize(imagePoints.size(), newObjPoints);
  164. totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints,
  165. rvecs, tvecs, cameraMatrix, distCoeffs, reprojErrs);
  166. return ok;
  167. }
  168. static void saveCameraParams( const string& filename,
  169. Size imageSize, Size boardSize,
  170. float squareSize, float aspectRatio, int flags,
  171. const Mat& cameraMatrix, const Mat& distCoeffs,
  172. const vector<Mat>& rvecs, const vector<Mat>& tvecs,
  173. const vector<float>& reprojErrs,
  174. const vector<vector<Point2f> >& imagePoints,
  175. const vector<Point3f>& newObjPoints,
  176. double totalAvgErr )
  177. {
  178. FileStorage fs( filename, FileStorage::WRITE );
  179. time_t tt;
  180. time( &tt );
  181. struct tm *t2 = localtime( &tt );
  182. char buf[1024];
  183. strftime( buf, sizeof(buf)-1, "%c", t2 );
  184. fs << "calibration_time" << buf;
  185. if( !rvecs.empty() || !reprojErrs.empty() )
  186. fs << "nframes" << (int)std::max(rvecs.size(), reprojErrs.size());
  187. fs << "image_width" << imageSize.width;
  188. fs << "image_height" << imageSize.height;
  189. fs << "board_width" << boardSize.width;
  190. fs << "board_height" << boardSize.height;
  191. fs << "square_size" << squareSize;
  192. if( flags & CALIB_FIX_ASPECT_RATIO )
  193. fs << "aspectRatio" << aspectRatio;
  194. if( flags != 0 )
  195. {
  196. sprintf( buf, "flags: %s%s%s%s",
  197. flags & CALIB_USE_INTRINSIC_GUESS ? "+use_intrinsic_guess" : "",
  198. flags & CALIB_FIX_ASPECT_RATIO ? "+fix_aspectRatio" : "",
  199. flags & CALIB_FIX_PRINCIPAL_POINT ? "+fix_principal_point" : "",
  200. flags & CALIB_ZERO_TANGENT_DIST ? "+zero_tangent_dist" : "" );
  201. //cvWriteComment( *fs, buf, 0 );
  202. }
  203. fs << "flags" << flags;
  204. fs << "camera_matrix" << cameraMatrix;
  205. fs << "distortion_coefficients" << distCoeffs;
  206. fs << "avg_reprojection_error" << totalAvgErr;
  207. if( !reprojErrs.empty() )
  208. fs << "per_view_reprojection_errors" << Mat(reprojErrs);
  209. if( !rvecs.empty() && !tvecs.empty() )
  210. {
  211. CV_Assert(rvecs[0].type() == tvecs[0].type());
  212. Mat bigmat((int)rvecs.size(), 6, rvecs[0].type());
  213. for( int i = 0; i < (int)rvecs.size(); i++ )
  214. {
  215. Mat r = bigmat(Range(i, i+1), Range(0,3));
  216. Mat t = bigmat(Range(i, i+1), Range(3,6));
  217. CV_Assert(rvecs[i].rows == 3 && rvecs[i].cols == 1);
  218. CV_Assert(tvecs[i].rows == 3 && tvecs[i].cols == 1);
  219. //*.t() is MatExpr (not Mat) so we can use assignment operator
  220. r = rvecs[i].t();
  221. t = tvecs[i].t();
  222. }
  223. //cvWriteComment( *fs, "a set of 6-tuples (rotation vector + translation vector) for each view", 0 );
  224. fs << "extrinsic_parameters" << bigmat;
  225. }
  226. if( !imagePoints.empty() )
  227. {
  228. Mat imagePtMat((int)imagePoints.size(), (int)imagePoints[0].size(), CV_32FC2);
  229. for( int i = 0; i < (int)imagePoints.size(); i++ )
  230. {
  231. Mat r = imagePtMat.row(i).reshape(2, imagePtMat.cols);
  232. Mat imgpti(imagePoints[i]);
  233. imgpti.copyTo(r);
  234. }
  235. fs << "image_points" << imagePtMat;
  236. }
  237. if( !newObjPoints.empty() )
  238. {
  239. fs << "grid_points" << newObjPoints;
  240. }
  241. }
  242. static bool readStringList( const string& filename, vector<string>& l )
  243. {
  244. l.resize(0);
  245. FileStorage fs(filename, FileStorage::READ);
  246. if( !fs.isOpened() )
  247. return false;
  248. size_t dir_pos = filename.rfind('/');
  249. if (dir_pos == string::npos)
  250. dir_pos = filename.rfind('\\');
  251. FileNode n = fs.getFirstTopLevelNode();
  252. if( n.type() != FileNode::SEQ )
  253. return false;
  254. FileNodeIterator it = n.begin(), it_end = n.end();
  255. for( ; it != it_end; ++it )
  256. {
  257. string fname = (string)*it;
  258. if (dir_pos != string::npos)
  259. {
  260. string fpath = samples::findFile(filename.substr(0, dir_pos + 1) + fname, false);
  261. if (fpath.empty())
  262. {
  263. fpath = samples::findFile(fname);
  264. }
  265. fname = fpath;
  266. }
  267. else
  268. {
  269. fname = samples::findFile(fname);
  270. }
  271. l.push_back(fname);
  272. }
  273. return true;
  274. }
  275. static bool runAndSave(const string& outputFilename,
  276. const vector<vector<Point2f> >& imagePoints,
  277. Size imageSize, Size boardSize, Pattern patternType, float squareSize,
  278. float grid_width, bool release_object,
  279. float aspectRatio, int flags, Mat& cameraMatrix,
  280. Mat& distCoeffs, bool writeExtrinsics, bool writePoints, bool writeGrid )
  281. {
  282. vector<Mat> rvecs, tvecs;
  283. vector<float> reprojErrs;
  284. double totalAvgErr = 0;
  285. vector<Point3f> newObjPoints;
  286. bool ok = runCalibration(imagePoints, imageSize, boardSize, patternType, squareSize,
  287. aspectRatio, grid_width, release_object, flags, cameraMatrix, distCoeffs,
  288. rvecs, tvecs, reprojErrs, newObjPoints, totalAvgErr);
  289. printf("%s. avg reprojection error = %.7f\n",
  290. ok ? "Calibration succeeded" : "Calibration failed",
  291. totalAvgErr);
  292. if( ok )
  293. saveCameraParams( outputFilename, imageSize,
  294. boardSize, squareSize, aspectRatio,
  295. flags, cameraMatrix, distCoeffs,
  296. writeExtrinsics ? rvecs : vector<Mat>(),
  297. writeExtrinsics ? tvecs : vector<Mat>(),
  298. writeExtrinsics ? reprojErrs : vector<float>(),
  299. writePoints ? imagePoints : vector<vector<Point2f> >(),
  300. writeGrid ? newObjPoints : vector<Point3f>(),
  301. totalAvgErr );
  302. return ok;
  303. }
  304. int main( int argc, char** argv )
  305. {
  306. Size boardSize, imageSize;
  307. float squareSize, aspectRatio = 1;
  308. Mat cameraMatrix, distCoeffs;
  309. string outputFilename;
  310. string inputFilename = "";
  311. int i, nframes;
  312. bool writeExtrinsics, writePoints;
  313. bool undistortImage = false;
  314. int flags = 0;
  315. VideoCapture capture;
  316. bool flipVertical;
  317. bool showUndistorted;
  318. bool videofile;
  319. int delay;
  320. clock_t prevTimestamp = 0;
  321. int mode = DETECTION;
  322. int cameraId = 0;
  323. vector<vector<Point2f> > imagePoints;
  324. vector<string> imageList;
  325. Pattern pattern = CHESSBOARD;
  326. cv::CommandLineParser parser(argc, argv,
  327. "{help ||}{w||}{h||}{pt|chessboard|}{n|10|}{d|1000|}{s|1|}{o|out_camera_data.yml|}"
  328. "{op||}{oe||}{zt||}{a||}{p||}{v||}{V||}{su||}"
  329. "{oo||}{ws|11|}{dt||}"
  330. "{@input_data|0|}");
  331. if (parser.has("help"))
  332. {
  333. help(argv);
  334. return 0;
  335. }
  336. boardSize.width = parser.get<int>( "w" );
  337. boardSize.height = parser.get<int>( "h" );
  338. if ( parser.has("pt") )
  339. {
  340. string val = parser.get<string>("pt");
  341. if( val == "circles" )
  342. pattern = CIRCLES_GRID;
  343. else if( val == "acircles" )
  344. pattern = ASYMMETRIC_CIRCLES_GRID;
  345. else if( val == "chessboard" )
  346. pattern = CHESSBOARD;
  347. else
  348. return fprintf( stderr, "Invalid pattern type: must be chessboard or circles\n" ), -1;
  349. }
  350. squareSize = parser.get<float>("s");
  351. nframes = parser.get<int>("n");
  352. delay = parser.get<int>("d");
  353. writePoints = parser.has("op");
  354. writeExtrinsics = parser.has("oe");
  355. bool writeGrid = parser.has("oo");
  356. if (parser.has("a")) {
  357. flags |= CALIB_FIX_ASPECT_RATIO;
  358. aspectRatio = parser.get<float>("a");
  359. }
  360. if ( parser.has("zt") )
  361. flags |= CALIB_ZERO_TANGENT_DIST;
  362. if ( parser.has("p") )
  363. flags |= CALIB_FIX_PRINCIPAL_POINT;
  364. flipVertical = parser.has("v");
  365. videofile = parser.has("V");
  366. if ( parser.has("o") )
  367. outputFilename = parser.get<string>("o");
  368. showUndistorted = parser.has("su");
  369. if ( isdigit(parser.get<string>("@input_data")[0]) )
  370. cameraId = parser.get<int>("@input_data");
  371. else
  372. inputFilename = parser.get<string>("@input_data");
  373. int winSize = parser.get<int>("ws");
  374. float grid_width = squareSize * (boardSize.width - 1);
  375. bool release_object = false;
  376. if (parser.has("dt")) {
  377. grid_width = parser.get<float>("dt");
  378. release_object = true;
  379. }
  380. if (!parser.check())
  381. {
  382. help(argv);
  383. parser.printErrors();
  384. return -1;
  385. }
  386. if ( squareSize <= 0 )
  387. return fprintf( stderr, "Invalid board square width\n" ), -1;
  388. if ( nframes <= 3 )
  389. return printf("Invalid number of images\n" ), -1;
  390. if ( aspectRatio <= 0 )
  391. return printf( "Invalid aspect ratio\n" ), -1;
  392. if ( delay <= 0 )
  393. return printf( "Invalid delay\n" ), -1;
  394. if ( boardSize.width <= 0 )
  395. return fprintf( stderr, "Invalid board width\n" ), -1;
  396. if ( boardSize.height <= 0 )
  397. return fprintf( stderr, "Invalid board height\n" ), -1;
  398. if( !inputFilename.empty() )
  399. {
  400. if( !videofile && readStringList(samples::findFile(inputFilename), imageList) )
  401. mode = CAPTURING;
  402. else
  403. capture.open(samples::findFileOrKeep(inputFilename));
  404. }
  405. else
  406. capture.open(cameraId);
  407. if( !capture.isOpened() && imageList.empty() )
  408. return fprintf( stderr, "Could not initialize video (%d) capture\n",cameraId ), -2;
  409. if( !imageList.empty() )
  410. nframes = (int)imageList.size();
  411. if( capture.isOpened() )
  412. printf( "%s", liveCaptureHelp );
  413. namedWindow( "Image View", 1 );
  414. for(i = 0;;i++)
  415. {
  416. Mat view, viewGray;
  417. bool blink = false;
  418. if( capture.isOpened() )
  419. {
  420. Mat view0;
  421. capture >> view0;
  422. view0.copyTo(view);
  423. }
  424. else if( i < (int)imageList.size() )
  425. view = imread(imageList[i], 1);
  426. if(view.empty())
  427. {
  428. if( imagePoints.size() > 0 )
  429. runAndSave(outputFilename, imagePoints, imageSize,
  430. boardSize, pattern, squareSize, grid_width, release_object, aspectRatio,
  431. flags, cameraMatrix, distCoeffs,
  432. writeExtrinsics, writePoints, writeGrid);
  433. break;
  434. }
  435. imageSize = view.size();
  436. if( flipVertical )
  437. flip( view, view, 0 );
  438. vector<Point2f> pointbuf;
  439. cvtColor(view, viewGray, COLOR_BGR2GRAY);
  440. bool found;
  441. switch( pattern )
  442. {
  443. case CHESSBOARD:
  444. found = findChessboardCorners( view, boardSize, pointbuf,
  445. CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_FAST_CHECK | CALIB_CB_NORMALIZE_IMAGE);
  446. break;
  447. case CIRCLES_GRID:
  448. found = findCirclesGrid( view, boardSize, pointbuf );
  449. break;
  450. case ASYMMETRIC_CIRCLES_GRID:
  451. found = findCirclesGrid( view, boardSize, pointbuf, CALIB_CB_ASYMMETRIC_GRID );
  452. break;
  453. default:
  454. return fprintf( stderr, "Unknown pattern type\n" ), -1;
  455. }
  456. // improve the found corners' coordinate accuracy
  457. if( pattern == CHESSBOARD && found) cornerSubPix( viewGray, pointbuf, Size(winSize,winSize),
  458. Size(-1,-1), TermCriteria( TermCriteria::EPS+TermCriteria::COUNT, 30, 0.0001 ));
  459. if( mode == CAPTURING && found &&
  460. (!capture.isOpened() || clock() - prevTimestamp > delay*1e-3*CLOCKS_PER_SEC) )
  461. {
  462. imagePoints.push_back(pointbuf);
  463. prevTimestamp = clock();
  464. blink = capture.isOpened();
  465. }
  466. if(found)
  467. drawChessboardCorners( view, boardSize, Mat(pointbuf), found );
  468. string msg = mode == CAPTURING ? "100/100" :
  469. mode == CALIBRATED ? "Calibrated" : "Press 'g' to start";
  470. int baseLine = 0;
  471. Size textSize = getTextSize(msg, 1, 1, 1, &baseLine);
  472. Point textOrigin(view.cols - 2*textSize.width - 10, view.rows - 2*baseLine - 10);
  473. if( mode == CAPTURING )
  474. {
  475. if(undistortImage)
  476. msg = cv::format( "%d/%d Undist", (int)imagePoints.size(), nframes );
  477. else
  478. msg = cv::format( "%d/%d", (int)imagePoints.size(), nframes );
  479. }
  480. putText( view, msg, textOrigin, 1, 1,
  481. mode != CALIBRATED ? Scalar(0,0,255) : Scalar(0,255,0));
  482. if( blink )
  483. bitwise_not(view, view);
  484. if( mode == CALIBRATED && undistortImage )
  485. {
  486. Mat temp = view.clone();
  487. undistort(temp, view, cameraMatrix, distCoeffs);
  488. }
  489. imshow("Image View", view);
  490. char key = (char)waitKey(capture.isOpened() ? 50 : 500);
  491. if( key == 27 )
  492. break;
  493. if( key == 'u' && mode == CALIBRATED )
  494. undistortImage = !undistortImage;
  495. if( capture.isOpened() && key == 'g' )
  496. {
  497. mode = CAPTURING;
  498. imagePoints.clear();
  499. }
  500. if( mode == CAPTURING && imagePoints.size() >= (unsigned)nframes )
  501. {
  502. if( runAndSave(outputFilename, imagePoints, imageSize,
  503. boardSize, pattern, squareSize, grid_width, release_object, aspectRatio,
  504. flags, cameraMatrix, distCoeffs,
  505. writeExtrinsics, writePoints, writeGrid))
  506. mode = CALIBRATED;
  507. else
  508. mode = DETECTION;
  509. if( !capture.isOpened() )
  510. break;
  511. }
  512. }
  513. if( !capture.isOpened() && showUndistorted )
  514. {
  515. Mat view, rview, map1, map2;
  516. initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(),
  517. getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0),
  518. imageSize, CV_16SC2, map1, map2);
  519. for( i = 0; i < (int)imageList.size(); i++ )
  520. {
  521. view = imread(imageList[i], 1);
  522. if(view.empty())
  523. continue;
  524. //undistort( view, rview, cameraMatrix, distCoeffs, cameraMatrix );
  525. remap(view, rview, map1, map2, INTER_LINEAR);
  526. imshow("Image View", rview);
  527. char c = (char)waitKey();
  528. if( c == 27 || c == 'q' || c == 'Q' )
  529. break;
  530. }
  531. }
  532. return 0;
  533. }