calibrate_camera.cpp 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. #include <ctime>
  2. #include <iostream>
  3. #include <vector>
  4. #include <opencv2/calib3d.hpp>
  5. #include <opencv2/highgui.hpp>
  6. #include <opencv2/imgproc.hpp>
  7. #include <opencv2/objdetect/aruco_detector.hpp>
  8. #include "aruco_samples_utility.hpp"
  9. using namespace std;
  10. using namespace cv;
  11. namespace {
  12. const char* about =
  13. "Calibration using a ArUco Planar Grid board\n"
  14. " To capture a frame for calibration, press 'c',\n"
  15. " If input comes from video, press any key for next frame\n"
  16. " To finish capturing, press 'ESC' key and calibration starts.\n";
  17. const char* keys =
  18. "{w | | Number of squares in X direction }"
  19. "{h | | Number of squares in Y direction }"
  20. "{l | | Marker side length (in meters) }"
  21. "{s | | Separation between two consecutive markers in the grid (in meters) }"
  22. "{d | | dictionary: DICT_4X4_50=0, DICT_4X4_100=1, DICT_4X4_250=2,"
  23. "DICT_4X4_1000=3, DICT_5X5_50=4, DICT_5X5_100=5, DICT_5X5_250=6, DICT_5X5_1000=7, "
  24. "DICT_6X6_50=8, DICT_6X6_100=9, DICT_6X6_250=10, DICT_6X6_1000=11, DICT_7X7_50=12,"
  25. "DICT_7X7_100=13, DICT_7X7_250=14, DICT_7X7_1000=15, DICT_ARUCO_ORIGINAL = 16}"
  26. "{cd | | Input file with custom dictionary }"
  27. "{@outfile |cam.yml| Output file with calibrated camera parameters }"
  28. "{v | | Input from video file, if ommited, input comes from camera }"
  29. "{ci | 0 | Camera id if input doesnt come from video (-v) }"
  30. "{dp | | File of marker detector parameters }"
  31. "{rs | false | Apply refind strategy }"
  32. "{zt | false | Assume zero tangential distortion }"
  33. "{a | | Fix aspect ratio (fx/fy) to this value }"
  34. "{pc | false | Fix the principal point at the center }";
  35. }
  36. int main(int argc, char *argv[]) {
  37. CommandLineParser parser(argc, argv, keys);
  38. parser.about(about);
  39. if(argc < 6) {
  40. parser.printMessage();
  41. return 0;
  42. }
  43. int markersX = parser.get<int>("w");
  44. int markersY = parser.get<int>("h");
  45. float markerLength = parser.get<float>("l");
  46. float markerSeparation = parser.get<float>("s");
  47. string outputFile = parser.get<string>(0);
  48. int calibrationFlags = 0;
  49. float aspectRatio = 1;
  50. if(parser.has("a")) {
  51. calibrationFlags |= CALIB_FIX_ASPECT_RATIO;
  52. aspectRatio = parser.get<float>("a");
  53. }
  54. if(parser.get<bool>("zt")) calibrationFlags |= CALIB_ZERO_TANGENT_DIST;
  55. if(parser.get<bool>("pc")) calibrationFlags |= CALIB_FIX_PRINCIPAL_POINT;
  56. aruco::Dictionary dictionary = readDictionatyFromCommandLine(parser);
  57. aruco::DetectorParameters detectorParams = readDetectorParamsFromCommandLine(parser);
  58. bool refindStrategy = parser.get<bool>("rs");
  59. int camId = parser.get<int>("ci");
  60. String video;
  61. if(parser.has("v")) {
  62. video = parser.get<String>("v");
  63. }
  64. if(!parser.check()) {
  65. parser.printErrors();
  66. return 0;
  67. }
  68. VideoCapture inputVideo;
  69. int waitTime;
  70. if(!video.empty()) {
  71. inputVideo.open(video);
  72. waitTime = 0;
  73. } else {
  74. inputVideo.open(camId);
  75. waitTime = 10;
  76. }
  77. //! [CalibrationWithArucoBoard1]
  78. // Create board object and ArucoDetector
  79. aruco::GridBoard gridboard(Size(markersX, markersY), markerLength, markerSeparation, dictionary);
  80. aruco::ArucoDetector detector(dictionary, detectorParams);
  81. // Collected frames for calibration
  82. vector<vector<vector<Point2f>>> allMarkerCorners;
  83. vector<vector<int>> allMarkerIds;
  84. Size imageSize;
  85. while(inputVideo.grab()) {
  86. Mat image, imageCopy;
  87. inputVideo.retrieve(image);
  88. vector<int> markerIds;
  89. vector<vector<Point2f>> markerCorners, rejectedMarkers;
  90. // Detect markers
  91. detector.detectMarkers(image, markerCorners, markerIds, rejectedMarkers);
  92. // Refind strategy to detect more markers
  93. if(refindStrategy) {
  94. detector.refineDetectedMarkers(image, gridboard, markerCorners, markerIds, rejectedMarkers);
  95. }
  96. //! [CalibrationWithArucoBoard1]
  97. // Draw results
  98. image.copyTo(imageCopy);
  99. if(!markerIds.empty()) {
  100. aruco::drawDetectedMarkers(imageCopy, markerCorners, markerIds);
  101. }
  102. putText(imageCopy, "Press 'c' to add current frame. 'ESC' to finish and calibrate",
  103. Point(10, 20), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 0, 0), 2);
  104. imshow("out", imageCopy);
  105. // Wait for key pressed
  106. char key = (char)waitKey(waitTime);
  107. if(key == 27) {
  108. break;
  109. }
  110. //! [CalibrationWithArucoBoard2]
  111. if(key == 'c' && !markerIds.empty()) {
  112. cout << "Frame captured" << endl;
  113. allMarkerCorners.push_back(markerCorners);
  114. allMarkerIds.push_back(markerIds);
  115. imageSize = image.size();
  116. }
  117. }
  118. //! [CalibrationWithArucoBoard2]
  119. if(allMarkerIds.empty()) {
  120. throw std::runtime_error("Not enough captures for calibration\n");
  121. }
  122. //! [CalibrationWithArucoBoard3]
  123. Mat cameraMatrix, distCoeffs;
  124. if(calibrationFlags & CALIB_FIX_ASPECT_RATIO) {
  125. cameraMatrix = Mat::eye(3, 3, CV_64F);
  126. cameraMatrix.at<double>(0, 0) = aspectRatio;
  127. }
  128. // Prepare data for calibration
  129. vector<Point3f> objectPoints;
  130. vector<Point2f> imagePoints;
  131. vector<Mat> processedObjectPoints, processedImagePoints;
  132. size_t nFrames = allMarkerCorners.size();
  133. for(size_t frame = 0; frame < nFrames; frame++) {
  134. Mat currentImgPoints, currentObjPoints;
  135. gridboard.matchImagePoints(allMarkerCorners[frame], allMarkerIds[frame], currentObjPoints, currentImgPoints);
  136. if(currentImgPoints.total() > 0 && currentObjPoints.total() > 0) {
  137. processedImagePoints.push_back(currentImgPoints);
  138. processedObjectPoints.push_back(currentObjPoints);
  139. }
  140. }
  141. // Calibrate camera
  142. double repError = calibrateCamera(processedObjectPoints, processedImagePoints, imageSize, cameraMatrix, distCoeffs,
  143. noArray(), noArray(), noArray(), noArray(), noArray(), calibrationFlags);
  144. //! [CalibrationWithArucoBoard3]
  145. bool saveOk = saveCameraParams(outputFile, imageSize, aspectRatio, calibrationFlags,
  146. cameraMatrix, distCoeffs, repError);
  147. if(!saveOk) {
  148. throw std::runtime_error("Cannot save output file\n");
  149. }
  150. cout << "Rep Error: " << repError << endl;
  151. cout << "Calibration saved to " << outputFile << endl;
  152. return 0;
  153. }