OpenCV双目视觉之立体校正

转自 https://blog.csdn.net/u014652390/article/details/71169927
本文试图从宏观的视角,解释这些个问题:这个校正是干嘛的,为啥要作这个立体校正呢,以及如何做。本文分享给像我一样“白手起家”的小伙伴们,要进行更深入的研究,可以参考文章后面的干货列表。吐舌头

如果用一句话来解释立体校正,那么,敲黑板,划重点“立体校正就是,把实际中非共面行对准的两幅图像,校正成共面行对准。”这话读起来有点深奥,配个图,就好理解啦!

(1)未校正以前左右眼视图


(2)校正后的左右眼视图

果然一图胜似千言万语啊。

       好了,到这里,第一个问题,你应该清楚了吧,不清楚的话,请举手!

那么接下来第二个问题来了,我把这左右眼图像对齐了,有什么用呢?我是没事找点事情干吗?我确实是闲来没事,但是OpenCV不会。先给张图感受一下~


我们知道,立体匹配是三维重建、立体导航、非接触测距等技术的关键步骤,它通过匹配两幅或者多幅图像来获取深度信息。并且广泛应用于,工业生产自动化、流水线控制、无人驾驶汽车(测距,导航)、安防监控、遥感图像分析、机器人智能控制等方面。”而立体图像校正是降低立体匹配计算复杂性的最有效方法之一。 因为当两个图像平面是完全共面行对准时,立体匹配从二维搜索降至一维搜索,并且可以过滤掉无匹配点。但是,在现实的双目立体视觉系统中,是不存在完全的共面行对准的两个摄像机图像平面的,所以我们要进行立体校正。

最后一个问题,那么作为小白的我,怎么做立体校正呢?

OpenCV的大致流程是这样的:


具体做法,参考调用代码:

 
 
  1. #include “opencv2/calib3d/calib3d.hpp”
  2. #include “opencv2/highgui/highgui.hpp”
  3. #include “opencv2/imgproc/imgproc.hpp”
  4. #include <vector>
  5. #include <string>
  6. #include <algorithm>
  7. #include <iostream>
  8. #include <iterator>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <ctype.h>
  12. using namespace cv;
  13. using namespace std;
  14. static void StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=true, bool showRectified=true)
  15. {
  16. if( imagelist.size() % 2 != 0 )
  17. {
  18. cout << “Error: the image list contains odd (non-even) number of elements\n”;
  19. return;
  20. }
  21. bool displayCorners = true; //true;
  22. const int maxScale = 2;
  23. const float squareSize = 1.f; // Set this to your actual square size
  24. // ARRAY AND VECTOR STORAGE:
  25. vector< vector<Point2f> > imagePoints[ 2];
  26. vector< vector<Point3f> > objectPoints;
  27. Size imageSize;
  28. int i, j, k, nimages = ( int)imagelist.size()/ 2;
  29. imagePoints[ 0].resize(nimages);
  30. imagePoints[ 1].resize(nimages);
  31. vector< string> goodImageList;
  32. for( i = j = 0; i < nimages; i++ )
  33. {
  34. for( k = 0; k < 2; k++ )
  35. {
  36. const string& filename = imagelist[i* 2+k];
  37. Mat img = imread(filename, 0);
  38. if(img.empty())
  39. break;
  40. if( imageSize == Size() )
  41. imageSize = img.size();
  42. else if( img.size() != imageSize )
  43. {
  44. cout << “The image " << filename << " has the size different from the first image size. Skipping the pair\n”;
  45. break;
  46. }
  47. bool found = false;
  48. vector<Point2f>& corners = imagePoints[k][j];
  49. for( int scale = 1; scale <= maxScale; scale++ )
  50. {
  51. Mat timg;
  52. if( scale == 1 )
  53. timg = img;
  54. else
  55. resize(img, timg, Size(), scale, scale);
  56. found = findChessboardCorners(timg, boardSize, corners,
  57. CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE);
  58. if( found )
  59. {
  60. if( scale > 1 )
  61. {
  62. Mat cornersMat(corners);
  63. cornersMat = 1./scale;
  64. }
  65. break;
  66. }
  67. }
  68. if( displayCorners )
  69. {
  70. cout << filename << endl;
  71. Mat cimg, cimg1;
  72. cvtColor(img, cimg, COLOR_GRAY2BGR);
  73. drawChessboardCorners(cimg, boardSize, corners, found);
  74. double sf = 640./MAX(img.rows, img.cols);
  75. resize(cimg, cimg1, Size(), sf, sf);
  76. imshow( “corners”, cimg1);
  77. char c = ( char)waitKey( 500);
  78. if( c == 27 || c == ‘q’ || c == ‘Q’ ) //Allow ESC to quit
  79. exit( -1);
  80. }
  81. else
  82. putchar( ’.’);
  83. if( !found )
  84. break;
  85. cornerSubPix(img, corners, Size( 11, 11), Size( -1, -1),
  86. TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,
  87. 30, 0.01));
  88. }
  89. if( k == 2 )
  90. {
  91. goodImageList.push_back(imagelist[i 2]);
  92. goodImageList.push_back(imagelist[i* 2+ 1]);
  93. j++;
  94. }
  95. }
  96. cout << j << " pairs have been successfully detected.\n";
  97. nimages = j;
  98. if( nimages < 2 )
  99. {
  100. cout << “Error: too little pairs to run the calibration\n”;
  101. return;
  102. }
  103. imagePoints[ 0].resize(nimages);
  104. imagePoints[ 1].resize(nimages);
  105. objectPoints.resize(nimages);
  106. for( i = 0; i < nimages; i++ )
  107. {
  108. for( j = 0; j < boardSize.height; j++ )
  109. for( k = 0; k < boardSize.width; k++ )
  110. objectPoints[i].push_back(Point3f(k squareSize, jsquareSize, 0));
  111. }
  112. cout << “Running stereo calibration …\n”;
  113. Mat cameraMatrix[ 2], distCoeffs[ 2];
  114. cameraMatrix[ 0] = Mat::eye( 3, 3, CV_64F);
  115. cameraMatrix[ 1] = Mat::eye( 3, 3, CV_64F);
  116. Mat R, T, E, F;
  117. double rms = stereoCalibrate(objectPoints, imagePoints[ 0], imagePoints[ 1],
  118. cameraMatrix[ 0], distCoeffs[ 0],
  119. cameraMatrix[ 1], distCoeffs[ 1],
  120. imageSize, R, T, E, F,
  121. TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, 1e-5),
  122. CV_CALIB_FIX_ASPECT_RATIO +
  123. CV_CALIB_ZERO_TANGENT_DIST +
  124. CV_CALIB_SAME_FOCAL_LENGTH +
  125. CV_CALIB_RATIONAL_MODEL +
  126. CV_CALIB_FIX_K3 + CV_CALIB_FIX_K4 + CV_CALIB_FIX_K5);
  127. cout << “done with RMS error=” << rms << endl;
  128. // CALIBRATION QUALITY CHECK
  129. // because the output fundamental matrix implicitly
  130. // includes all the output information,
  131. // we can check the quality of calibration using the
  132. // epipolar geometry constraint: m2^tFm1=0
  133. double err = 0;
  134. int npoints = 0;
  135. vector<Vec3f> lines[ 2];
  136. for( i = 0; i < nimages; i++ )
  137. {
  138. int npt = ( int)imagePoints[ 0][i].size();
  139. Mat imgpt[ 2];
  140. for( k = 0; k < 2; k++ )
  141. {
  142. imgpt[k] = Mat(imagePoints[k][i]);
  143. undistortPoints(imgpt[k], imgpt[k], cameraMatrix[k], distCoeffs[k], Mat(), cameraMatrix[k]);
  144. computeCorrespondEpilines(imgpt[k], k+ 1, F, lines[k]);
  145. }
  146. for( j = 0; j < npt; j++ )
  147. {
  148. double errij = fabs(imagePoints[ 0][i][j].x lines[1][j][0] +
  149. imagePoints[ 0][i][j].ylines[ 1][j][ 1] + lines[ 1][j][ 2]) +
  150. fabs(imagePoints[ 1][i][j].x lines[0][j][0] +
  151. imagePoints[ 1][i][j].ylines[ 0][j][ 1] + lines[ 0][j][ 2]);
  152. err += errij;
  153. }
  154. npoints += npt;
  155. }
  156. cout << "average reprojection err = " << err/npoints << endl;
  157. // save intrinsic parameters
  158. FileStorage fs(“intrinsics.yml”, CV_STORAGE_WRITE);
  159. if( fs.isOpened() )
  160. {
  161. fs << “M1” << cameraMatrix[ 0] << “D1” << distCoeffs[ 0] <<
  162. “M2” << cameraMatrix[ 1] << “D2” << distCoeffs[ 1];
  163. fs.release();
  164. }
  165. else
  166. cout << “Error: can not save the intrinsic parameters\n”;
  167. Mat R1, R2, P1, P2, Q;
  168. Rect validRoi[ 2];
  169. stereoRectify(cameraMatrix[ 0], distCoeffs[ 0],
  170. cameraMatrix[ 1], distCoeffs[ 1],
  171. imageSize, R, T, R1, R2, P1, P2, Q,
  172. CALIB_ZERO_DISPARITY, 1, imageSize, &validRoi[ 0], &validRoi[ 1]);
  173. fs.open( “extrinsics.yml”, CV_STORAGE_WRITE);
  174. if( fs.isOpened() )
  175. {
  176. fs << “R” << R << “T” << T << “R1” << R1 << “R2” << R2 << “P1” << P1 << “P2” << P2 << “Q” << Q;
  177. fs.release();
  178. }
  179. else
  180. cout << “Error: can not save the extrinsic parameters\n”;
  181. // OpenCV can handle left-right
  182. // or up-down camera arrangements
  183. bool isVerticalStereo = fabs(P2.at< double>( 1, 3)) > fabs(P2.at< double>( 0, 3));
  184. // COMPUTE AND DISPLAY RECTIFICATION
  185. if( !showRectified )
  186. return;
  187. Mat rmap[ 2][ 2];
  188. // IF BY CALIBRATED (BOUGUET’S METHOD)
  189. if( useCalibrated )
  190. {
  191. // we already computed everything
  192. }
  193. // OR ELSE HARTLEY’S METHOD
  194. else
  195. // use intrinsic parameters of each camera, but
  196. // compute the rectification transformation directly
  197. // from the fundamental matrix
  198. {
  199. vector<Point2f> allimgpt[ 2];
  200. for( k = 0; k < 2; k++ )
  201. {
  202. for( i = 0; i < nimages; i++ )
  203. std::copy(imagePoints[k][i].begin(), imagePoints[k][i].end(), back_inserter(allimgpt[k]));
  204. }
  205. F = findFundamentalMat(Mat(allimgpt[ 0]), Mat(allimgpt[ 1]), FM_8POINT, 0, 0);
  206. Mat H1, H2;
  207. stereoRectifyUncalibrated(Mat(allimgpt[ 0]), Mat(allimgpt[ 1]), F, imageSize, H1, H2, 3);
  208. R1 = cameraMatrix[ 0].inv() H1cameraMatrix[ 0];
  209. R2 = cameraMatrix[ 1].inv() H2cameraMatrix[ 1];
  210. P1 = cameraMatrix[ 0];
  211. P2 = cameraMatrix[ 1];
  212. }
  213. //Precompute maps for cv::remap()
  214. initUndistortRectifyMap(cameraMatrix[ 0], distCoeffs[ 0], R1, P1, imageSize, CV_16SC2, rmap[ 0][ 0], rmap[ 0][ 1]);
  215. initUndistortRectifyMap(cameraMatrix[ 1], distCoeffs[ 1], R2, P2, imageSize, CV_16SC2, rmap[ 1][ 0], rmap[ 1][ 1]);
  216. Mat canvas;
  217. double sf;
  218. int w, h;
  219. if( !isVerticalStereo )
  220. {
  221. sf = 600./MAX(imageSize.width, imageSize.height);
  222. w = cvRound(imageSize.width sf);
  223. h = cvRound(imageSize.heightsf);
  224. canvas.create(h, w* 2, CV_8UC3);
  225. }
  226. else
  227. {
  228. sf = 300./MAX(imageSize.width, imageSize.height);
  229. w = cvRound(imageSize.width sf);
  230. h = cvRound(imageSize.heightsf);
  231. canvas.create(h* 2, w, CV_8UC3);
  232. }
  233. for( i = 0; i < nimages; i++ )
  234. {
  235. for( k = 0; k < 2; k++ )
  236. {
  237. Mat img = imread(goodImageList[i* 2+k], 0), rimg, cimg;
  238. remap(img, rimg, rmap[k][ 0], rmap[k][ 1], CV_INTER_LINEAR);
  239. imshow( “单目相机校正”,rimg);
  240. waitKey();
  241. cvtColor(rimg, cimg, COLOR_GRAY2BGR);
  242. Mat canvasPart = !isVerticalStereo ? canvas(Rect(w k, 0, w, h)) : canvas(Rect(0, hk, w, h));
  243. resize(cimg, canvasPart, canvasPart.size(), 0, 0, CV_INTER_AREA);
  244. if( useCalibrated )
  245. {
  246. Rect vroi(cvRound(validRoi[k].xsf), cvRound(validRoi[k].ysf),
  247. cvRound (validRoi[k].widthsf), cvRound (validRoi[k].heightsf));
  248. rectangle(canvasPart, vroi, Scalar( 0, 0, 255), 3, 8);
  249. }
  250. }
  251. if( !isVerticalStereo )
  252. for( j = 0; j < canvas.rows; j += 16 )
  253. line(canvas, Point( 0, j), Point(canvas.cols, j), Scalar( 0, 255, 0), 1, 8);
  254. else
  255. for( j = 0; j < canvas.cols; j += 16 )
  256. line(canvas, Point(j, 0), Point(j, canvas.rows), Scalar( 0, 255, 0), 1, 8);
  257. imshow( “双目相机校正对齐”, canvas);
  258. waitKey();
  259. char c = ( char)waitKey();
  260. if( c == 27 || c == ‘q’ || c == ‘Q’ )
  261. break;
  262. }
  263. }
  264. static bool readStringList( const string& filename, vector<string>& l )
  265. {
  266. l.resize( 0);
  267. FileStorage fs(filename, FileStorage::READ);
  268. if( !fs.isOpened() )
  269. return false;
  270. FileNode n = fs.getFirstTopLevelNode();
  271. if( n.type() != FileNode::SEQ )
  272. return false;
  273. FileNodeIterator it = n.begin(), it_end = n.end();
  274. for( ; it != it_end; ++it )
  275. l.push_back(( string) it);
  276. return true;
  277. }
  278. int main(int argc, char* argv)
  279. {
  280. Size boardSize;
  281. string imagelistfn;
  282. bool showRectified = true;
  283. for( int i = 1; i < argc; i++ )
  284. {
  285. if( string(argv[i]) == “-w” )
  286. {
  287. if( sscanf(argv[++i], “%d”, &boardSize.width) != 1 || boardSize.width <= 0 )
  288. {
  289. cout << “invalid board width” << endl;
  290. return -1;
  291. }
  292. }
  293. else if( string(argv[i]) == “-h” )
  294. {
  295. if( sscanf(argv[++i], “%d”, &boardSize.height) != 1 || boardSize.height <= 0 )
  296. {
  297. cout << “invalid board height” << endl;
  298. return -1;
  299. }
  300. }
  301. else if( string(argv[i]) == “-nr” )
  302. showRectified = false;
  303. else if( string(argv[i]) == “–help” )
  304. return -1;
  305. else if( argv[i][ 0] == ‘-’ )
  306. {
  307. cout << "invalid option " << argv[i] << endl;
  308. return 0;
  309. }
  310. else
  311. imagelistfn = argv[i];
  312. }
  313. if( imagelistfn == “” )
  314. {
  315. imagelistfn = “stereo_calib.xml”;
  316. boardSize = Size( 9, 6);
  317. }
  318. else if( boardSize.width <= 0 || boardSize.height <= 0 )
  319. {
  320. cout << “if you specified XML file with chessboards, you should also specify the board width and height (-w and -h options)” << endl;
  321. return 0;
  322. }
  323. vector< string> imagelist;
  324. bool ok = readStringList(imagelistfn, imagelist);
  325. if(!ok || imagelist.empty())
  326. {
  327. cout << “can not open " << imagelistfn << " or the string list is empty” << endl;
  328. return -1;
  329. }
  330. StereoCalib(imagelist, boardSize, true, showRectified);
  331. return 0;
  332. }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值