calibration.cpp 29 KB

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