projectorcalibration.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. /*M///////////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  4. //
  5. // By downloading, copying, installing or using the software you agree to this license.
  6. // If you do not agree to this license, do not download, install,
  7. // copy or use the software.
  8. //
  9. //
  10. // License Agreement
  11. // For Open Source Computer Vision Library
  12. //
  13. // Copyright (C) 2015, OpenCV Foundation, all rights reserved.
  14. // Third party copyrights are property of their respective owners.
  15. //
  16. // Redistribution and use in source and binary forms, with or without modification,
  17. // are permitted provided that the following conditions are met:
  18. //
  19. // * Redistribution's of source code must retain the above copyright notice,
  20. // this list of conditions and the following disclaimer.
  21. //
  22. // * Redistribution's in binary form must reproduce the above copyright notice,
  23. // this list of conditions and the following disclaimer in the documentation
  24. // and/or other materials provided with the distribution.
  25. //
  26. // * The name of the copyright holders may not be used to endorse or promote products
  27. // derived from this software without specific prior written permission.
  28. //
  29. // This software is provided by the copyright holders and contributors "as is" and
  30. // any express or implied warranties, including, but not limited to, the implied
  31. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  32. // In no event shall the Intel Corporation or contributors be liable for any direct,
  33. // indirect, incidental, special, exemplary, or consequential damages
  34. // (including, but not limited to, procurement of substitute goods or services;
  35. // loss of use, data, or profits; or business interruption) however caused
  36. // and on any theory of liability, whether in contract, strict liability,
  37. // or tort (including negligence or otherwise) arising in any way out of
  38. // the use of this software, even if advised of the possibility of such damage.
  39. //
  40. //M*/
  41. #include <opencv2/highgui.hpp>
  42. #include <vector>
  43. #include <iostream>
  44. #include <fstream>
  45. #include <opencv2/core.hpp>
  46. #include <opencv2/core/utility.hpp>
  47. #include <opencv2/imgproc.hpp>
  48. #include <opencv2/calib3d.hpp>
  49. using namespace std;
  50. using namespace cv;
  51. static const char* keys =
  52. {
  53. "{@camSettingsPath | | Path of camera calibration file}"
  54. "{@projSettingsPath | | Path of projector settings}"
  55. "{@patternPath | | Path to checkerboard pattern}"
  56. "{@outputName | | Base name for the calibration data}"
  57. };
  58. static void help()
  59. {
  60. cout << "\nThis example calibrates a camera and a projector" << endl;
  61. cout << "To call: ./example_structured_light_projectorcalibration <cam_settings_path> "
  62. " <proj_settings_path> <chessboard_path> <calibration_basename>"
  63. " cam settings are parameters about the chessboard that needs to be detected to"
  64. " calibrate the camera and proj setting are the same kind of parameters about the chessboard"
  65. " that needs to be detected to calibrate the projector" << endl;
  66. }
  67. enum calibrationPattern{ CHESSBOARD, CIRCLES_GRID, ASYMETRIC_CIRCLES_GRID };
  68. struct Settings
  69. {
  70. Settings();
  71. int patternType;
  72. Size patternSize;
  73. Size subpixelSize;
  74. Size imageSize;
  75. float squareSize;
  76. int nbrOfFrames;
  77. };
  78. void loadSettings( String path, Settings &sttngs );
  79. void createObjectPoints( vector<Point3f> &patternCorners, Size patternSize, float squareSize,
  80. int patternType );
  81. void createProjectorObjectPoints( vector<Point2f> &patternCorners, Size patternSize, float squareSize,
  82. int patternType );
  83. double calibrate( vector< vector<Point3f> > objPoints, vector< vector<Point2f> > imgPoints,
  84. Mat &cameraMatrix, Mat &distCoeffs, vector<Mat> &r, vector<Mat> &t, Size imgSize );
  85. void fromCamToWorld( Mat cameraMatrix, vector<Mat> rV, vector<Mat> tV,
  86. vector< vector<Point2f> > imgPoints, vector< vector<Point3f> > &worldPoints );
  87. void saveCalibrationResults( String path, Mat camK, Mat camDistCoeffs, Mat projK, Mat projDistCoeffs,
  88. Mat fundamental );
  89. void saveCalibrationData( String path, vector<Mat> T1, vector<Mat> T2, vector<Mat> ptsProjCam, vector<Mat> ptsProjProj, vector<Mat> ptsProjCamN, vector<Mat> ptsProjProjN);
  90. void normalize(const Mat &pts, const int& dim, Mat& normpts, Mat &T);
  91. void fromVectorToMat( vector<Point2f> v, Mat &pts);
  92. void fromMatToVector( Mat pts, vector<Point2f> &v );
  93. int main( int argc, char **argv )
  94. {
  95. VideoCapture cap(CAP_PVAPI);
  96. Mat frame;
  97. int nbrOfValidFrames = 0;
  98. vector< vector<Point2f> > imagePointsCam, imagePointsProj, PointsInProj, imagePointsProjN, pointsInProjN;
  99. vector< vector<Point3f> > objectPointsCam, worldPointsProj;
  100. vector<Point3f> tempCam;
  101. vector<Point2f> tempProj;
  102. vector<Mat> T1, T2;
  103. vector<Mat> projInProj, projInCam;
  104. vector<Mat> projInProjN, projInCamN;
  105. vector<Mat> rVecs, tVecs, projectorRVecs, projectorTVecs;
  106. Mat cameraMatrix, distCoeffs, projectorMatrix, projectorDistCoeffs;
  107. Mat pattern;
  108. vector<Mat> images;
  109. Settings camSettings, projSettings;
  110. CommandLineParser parser(argc, argv, keys);
  111. String camSettingsPath = parser.get<String>(0);
  112. String projSettingsPath = parser.get<String>(1);
  113. String patternPath = parser.get<String>(2);
  114. String outputName = parser.get<String>(3);
  115. if( camSettingsPath.empty() || projSettingsPath.empty() || patternPath.empty() || outputName.empty() ){
  116. help();
  117. return -1;
  118. }
  119. pattern = imread(patternPath);
  120. loadSettings(camSettingsPath, camSettings);
  121. loadSettings(projSettingsPath, projSettings);
  122. projSettings.imageSize = Size(pattern.rows, pattern.cols);
  123. createObjectPoints(tempCam, camSettings.patternSize,
  124. camSettings.squareSize, camSettings.patternType);
  125. createProjectorObjectPoints(tempProj, projSettings.patternSize,
  126. projSettings.squareSize, projSettings.patternType);
  127. if(!cap.isOpened())
  128. {
  129. cout << "Camera could not be opened" << endl;
  130. return -1;
  131. }
  132. cap.set(CAP_PROP_PVAPI_PIXELFORMAT, CAP_PVAPI_PIXELFORMAT_BAYER8);
  133. namedWindow("pattern", WINDOW_NORMAL);
  134. setWindowProperty("pattern", WND_PROP_FULLSCREEN, WINDOW_FULLSCREEN);
  135. namedWindow("camera view", WINDOW_NORMAL);
  136. imshow("pattern", pattern);
  137. cout << "Press any key when ready" << endl;
  138. waitKey(0);
  139. while( nbrOfValidFrames < camSettings.nbrOfFrames )
  140. {
  141. cap >> frame;
  142. if( frame.data )
  143. {
  144. Mat color;
  145. cvtColor(frame, color, COLOR_BayerBG2BGR);
  146. if( camSettings.imageSize.height == 0 || camSettings.imageSize.width == 0 )
  147. {
  148. camSettings.imageSize = Size(frame.rows, frame.cols);
  149. }
  150. bool foundProj, foundCam;
  151. vector<Point2f> projPointBuf;
  152. vector<Point2f> camPointBuf;
  153. imshow("camera view", color);
  154. if( camSettings.patternType == CHESSBOARD && projSettings.patternType == CHESSBOARD )
  155. {
  156. int calibFlags = CALIB_CB_ADAPTIVE_THRESH;
  157. foundCam = findChessboardCorners(color, camSettings.patternSize,
  158. camPointBuf, calibFlags);
  159. foundProj = findChessboardCorners(color, projSettings.patternSize,
  160. projPointBuf, calibFlags);
  161. if( foundCam && foundProj )
  162. {
  163. Mat gray;
  164. cvtColor(color, gray, COLOR_BGR2GRAY);
  165. cout << "found pattern" << endl;
  166. Mat projCorners, camCorners;
  167. cornerSubPix(gray, camPointBuf, camSettings.subpixelSize, Size(-1, -1),
  168. TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 30, 0.1));
  169. cornerSubPix(gray, projPointBuf, projSettings.subpixelSize, Size(-1, -1),
  170. TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 30, 0.1));
  171. drawChessboardCorners(gray, camSettings.patternSize, camPointBuf, foundCam);
  172. drawChessboardCorners(gray, projSettings.patternSize, projPointBuf, foundProj);
  173. imshow("camera view", gray);
  174. char c = (char)waitKey(0);
  175. if( c == 10 )
  176. {
  177. cout << "saving pattern #" << nbrOfValidFrames << " for calibration" << endl;
  178. ostringstream name;
  179. name << nbrOfValidFrames;
  180. nbrOfValidFrames += 1;
  181. imagePointsCam.push_back(camPointBuf);
  182. imagePointsProj.push_back(projPointBuf);
  183. objectPointsCam.push_back(tempCam);
  184. PointsInProj.push_back(tempProj);
  185. images.push_back(frame);
  186. Mat ptsProjProj, ptsProjCam;
  187. Mat ptsProjProjN, ptsProjCamN;
  188. Mat TProjProj, TProjCam;
  189. vector<Point2f> ptsProjProjVec;
  190. vector<Point2f> ptsProjCamVec;
  191. fromVectorToMat(tempProj, ptsProjProj);
  192. normalize(ptsProjProj, 2, ptsProjProjN, TProjProj);
  193. fromMatToVector(ptsProjProjN, ptsProjProjVec);
  194. pointsInProjN.push_back(ptsProjProjVec);
  195. T2.push_back(TProjProj);
  196. projInProj.push_back(ptsProjProj);
  197. projInProjN.push_back(ptsProjProjN);
  198. fromVectorToMat(projPointBuf, ptsProjCam);
  199. normalize(ptsProjCam, 2, ptsProjCamN, TProjCam);
  200. fromMatToVector(ptsProjCamN, ptsProjCamVec);
  201. imagePointsProjN.push_back(ptsProjCamVec);
  202. T1.push_back(TProjCam);
  203. projInCam.push_back(ptsProjCam);
  204. projInCamN.push_back(ptsProjCamN);
  205. }
  206. else if( c == 32 )
  207. {
  208. cout << "capture discarded" << endl;
  209. }
  210. else if( c == 27 )
  211. {
  212. cout << "closing program" << endl;
  213. return -1;
  214. }
  215. }
  216. else
  217. {
  218. cout << "no pattern found, move board and press any key" << endl;
  219. imshow("camera view", frame);
  220. waitKey(0);
  221. }
  222. }
  223. }
  224. }
  225. saveCalibrationData(outputName + "_points.yml", T1, T2, projInCam, projInProj, projInCamN, projInProjN);
  226. double rms = calibrate(objectPointsCam, imagePointsCam, cameraMatrix, distCoeffs,
  227. rVecs, tVecs, camSettings.imageSize);
  228. cout << "rms = " << rms << endl;
  229. cout << "camera matrix = \n" << cameraMatrix << endl;
  230. cout << "dist coeffs = \n" << distCoeffs << endl;
  231. fromCamToWorld(cameraMatrix, rVecs, tVecs, imagePointsProj, worldPointsProj);
  232. rms = calibrate(worldPointsProj, PointsInProj, projectorMatrix, projectorDistCoeffs,
  233. projectorRVecs, projectorTVecs, projSettings.imageSize);
  234. cout << "rms = " << rms << endl;
  235. cout << "projector matrix = \n" << projectorMatrix << endl;
  236. cout << "projector dist coeffs = \n" << distCoeffs << endl;
  237. Mat stereoR, stereoT, essential, fundamental;
  238. Mat RCam, RProj, PCam, PProj, Q;
  239. rms = stereoCalibrate(worldPointsProj, imagePointsProj, PointsInProj, cameraMatrix, distCoeffs,
  240. projectorMatrix, projectorDistCoeffs, camSettings.imageSize, stereoR, stereoT,
  241. essential, fundamental);
  242. cout << "stereo calibrate: \n" << fundamental << endl;
  243. saveCalibrationResults(outputName, cameraMatrix, distCoeffs, projectorMatrix, projectorDistCoeffs, fundamental );
  244. return 0;
  245. }
  246. Settings::Settings(){
  247. patternType = CHESSBOARD;
  248. patternSize = Size(13, 9);
  249. subpixelSize = Size(11, 11);
  250. squareSize = 50;
  251. nbrOfFrames = 25;
  252. }
  253. void loadSettings( String path, Settings &sttngs )
  254. {
  255. FileStorage fsInput(path, FileStorage::READ);
  256. fsInput["PatternWidth"] >> sttngs.patternSize.width;
  257. fsInput["PatternHeight"] >> sttngs.patternSize.height;
  258. fsInput["SubPixelWidth"] >> sttngs.subpixelSize.width;
  259. fsInput["SubPixelHeight"] >> sttngs.subpixelSize.height;
  260. fsInput["SquareSize"] >> sttngs.squareSize;
  261. fsInput["NbrOfFrames"] >> sttngs.nbrOfFrames;
  262. fsInput["PatternType"] >> sttngs.patternType;
  263. fsInput.release();
  264. }
  265. double calibrate( vector< vector<Point3f> > objPoints, vector< vector<Point2f> > imgPoints,
  266. Mat &cameraMatrix, Mat &distCoeffs, vector<Mat> &r, vector<Mat> &t, Size imgSize )
  267. {
  268. int calibFlags = 0;
  269. double rms = calibrateCamera(objPoints, imgPoints, imgSize, cameraMatrix,
  270. distCoeffs, r, t, calibFlags);
  271. return rms;
  272. }
  273. void createObjectPoints( vector<Point3f> &patternCorners, Size patternSize, float squareSize,
  274. int patternType )
  275. {
  276. switch( patternType )
  277. {
  278. case CHESSBOARD:
  279. case CIRCLES_GRID:
  280. for( int i = 0; i < patternSize.height; ++i )
  281. {
  282. for( int j = 0; j < patternSize.width; ++j )
  283. {
  284. patternCorners.push_back(Point3f(float(i*squareSize), float(j*squareSize), 0));
  285. }
  286. }
  287. break;
  288. case ASYMETRIC_CIRCLES_GRID:
  289. break;
  290. }
  291. }
  292. void createProjectorObjectPoints( vector<Point2f> &patternCorners, Size patternSize, float squareSize,
  293. int patternType )
  294. {
  295. switch( patternType )
  296. {
  297. case CHESSBOARD:
  298. case CIRCLES_GRID:
  299. for( int i = 1; i <= patternSize.height; ++i )
  300. {
  301. for( int j = 1; j <= patternSize.width; ++j )
  302. {
  303. patternCorners.push_back(Point2f(float(j*squareSize), float(i*squareSize)));
  304. }
  305. }
  306. break;
  307. case ASYMETRIC_CIRCLES_GRID:
  308. break;
  309. }
  310. }
  311. void fromCamToWorld( Mat cameraMatrix, vector<Mat> rV, vector<Mat> tV,
  312. vector< vector<Point2f> > imgPoints, vector< vector<Point3f> > &worldPoints )
  313. {
  314. int s = (int) rV.size();
  315. Mat invK64, invK;
  316. invK64 = cameraMatrix.inv();
  317. invK64.convertTo(invK, CV_32F);
  318. for(int i = 0; i < s; ++i)
  319. {
  320. Mat r, t, rMat;
  321. rV[i].convertTo(r, CV_32F);
  322. tV[i].convertTo(t, CV_32F);
  323. Rodrigues(r, rMat);
  324. Mat transPlaneToCam = rMat.inv()*t;
  325. vector<Point3f> wpTemp;
  326. int s2 = (int) imgPoints[i].size();
  327. for(int j = 0; j < s2; ++j){
  328. Mat coords(3, 1, CV_32F);
  329. coords.at<float>(0, 0) = imgPoints[i][j].x;
  330. coords.at<float>(1, 0) = imgPoints[i][j].y;
  331. coords.at<float>(2, 0) = 1.0f;
  332. Mat worldPtCam = invK*coords;
  333. Mat worldPtPlane = rMat.inv()*worldPtCam;
  334. float scale = transPlaneToCam.at<float>(2)/worldPtPlane.at<float>(2);
  335. Mat worldPtPlaneReproject = scale*worldPtPlane - transPlaneToCam;
  336. Point3f pt;
  337. pt.x = worldPtPlaneReproject.at<float>(0);
  338. pt.y = worldPtPlaneReproject.at<float>(1);
  339. pt.z = 0;
  340. wpTemp.push_back(pt);
  341. }
  342. worldPoints.push_back(wpTemp);
  343. }
  344. }
  345. void saveCalibrationResults( String path, Mat camK, Mat camDistCoeffs, Mat projK, Mat projDistCoeffs,
  346. Mat fundamental )
  347. {
  348. FileStorage fs(path + ".yml", FileStorage::WRITE);
  349. fs << "camIntrinsics" << camK;
  350. fs << "camDistCoeffs" << camDistCoeffs;
  351. fs << "projIntrinsics" << projK;
  352. fs << "projDistCoeffs" << projDistCoeffs;
  353. fs << "fundamental" << fundamental;
  354. fs.release();
  355. }
  356. void saveCalibrationData( String path, vector<Mat> T1, vector<Mat> T2, vector<Mat> ptsProjCam, vector<Mat> ptsProjProj, vector<Mat> ptsProjCamN, vector<Mat> ptsProjProjN )
  357. {
  358. FileStorage fs(path + ".yml", FileStorage::WRITE);
  359. int size = (int) T1.size();
  360. fs << "size" << size;
  361. for( int i = 0; i < (int)T1.size(); ++i )
  362. {
  363. ostringstream nbr;
  364. nbr << i;
  365. fs << "TprojCam" + nbr.str() << T1[i];
  366. fs << "TProjProj" + nbr.str() << T2[i];
  367. fs << "ptsProjCam" + nbr.str() << ptsProjCam[i];
  368. fs << "ptsProjProj" + nbr.str() << ptsProjProj[i];
  369. fs << "ptsProjCamN" + nbr.str() << ptsProjCamN[i];
  370. fs << "ptsProjProjN" + nbr.str() << ptsProjProjN[i];
  371. }
  372. fs.release();
  373. }
  374. void normalize( const Mat &pts, const int& dim, Mat& normpts, Mat &T )
  375. {
  376. float averagedist = 0;
  377. float scale = 0;
  378. //centroid
  379. Mat centroid(dim,1,CV_32F);
  380. Scalar tmp;
  381. if( normpts.empty() )
  382. {
  383. normpts= Mat(pts.rows,pts.cols,CV_32F);
  384. }
  385. for( int i = 0 ; i < dim ; ++i )
  386. {
  387. tmp = mean(pts.row(i));
  388. centroid.at<float>(i,0) = (float)tmp[0];
  389. subtract(pts.row(i), centroid.at<float>(i, 0), normpts.row(i));
  390. }
  391. //average distance
  392. Mat ptstmp;
  393. for( int i = 0 ; i < normpts.cols; ++i )
  394. {
  395. ptstmp = normpts.col(i);
  396. averagedist = averagedist+(float)norm(ptstmp);
  397. }
  398. averagedist = averagedist / normpts.cols;
  399. scale = (float)(sqrt(static_cast<float>(dim)) / averagedist);
  400. normpts = normpts * scale;
  401. T=cv::Mat::eye(dim+1,dim+1,CV_32F);
  402. for( int i = 0; i < dim; ++i )
  403. {
  404. T.at<float>(i, i) = scale;
  405. T.at<float>(i, dim) = -scale*centroid.at<float>(i, 0);
  406. }
  407. }
  408. void fromVectorToMat( vector<Point2f> v, Mat &pts )
  409. {
  410. int nbrOfPoints = (int) v.size();
  411. if( pts.empty() )
  412. pts.create(2, nbrOfPoints, CV_32F);
  413. for( int i = 0; i < nbrOfPoints; ++i )
  414. {
  415. pts.at<float>(0, i) = v[i].x;
  416. pts.at<float>(1, i) = v[i].y;
  417. }
  418. }
  419. void fromMatToVector( Mat pts, vector<Point2f> &v )
  420. {
  421. int nbrOfPoints = pts.cols;
  422. for( int i = 0; i < nbrOfPoints; ++i )
  423. {
  424. Point2f temp;
  425. temp.x = pts.at<float>(0, i);
  426. temp.y = pts.at<float>(1, i);
  427. v.push_back(temp);
  428. }
  429. }