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. }




  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 双目视觉是一种基于人类双眼视觉原理的图像处理技术。OpenCV是一个流行的计算机视觉库,提供了用于双目视觉的定标、校正和测距等功能。 首先,双目视觉的定标是指测量和记录相机的内部参数和外部参数。内部参数包括焦距、主点位置和镜头畸变等,而外部参数则包括相机在三维空间中的位置和方向。OpenCV提供了一些函数和方法,可以通过拍摄一组特定的标定图案,来自动计算这些参数。 其次,校正双目视觉中的一个重要步骤。由于镜头畸变等因素,相机采集的图像可能存在突变和形变。校正处理可以通过将图像重新映射到一个无畸变的状态来修复这些问题。OpenCV提供了双目立体校正的函数和方法,可以校正和矫正双目图像,使其达到最佳的观测效果。 最后,测距是利用双目相机的图像信息来计算场景中物体的距离。双目视觉系统可以通过分析两个图像之间的视差(如左右眼图像中对应点的位置偏移)来计算物体的深度。OpenCV提供了一系列函数和算法,可以根据视差来进行三角测量,从而得出物体的实际距离。 综上所述,OpenCV提供了一套完整的双目视觉解决方案,包括定标、校正和测距等功能。这些功能可以帮助我们实现双目立体视觉应用,如三维重建、障碍物检测等,对于机器人、自动驾驶和增强现实等领域有着广泛的应用前景。 ### 回答2: 双目视觉是一种利用两个摄像头进行深度感知的技术。OpenCV是一个流行的计算机视觉库,它提供了一些用于双目视觉的函数和工具。 双目视觉系统需要进行定标和校正,以获得准确的测距结果。首先,需要进行定标,即确定两个摄像头的内部和外部参数。内部参数包括焦距、主点位置和畸变系数,这些参数描述了摄像头的几何特性。外部参数包括两个摄像头之间的旋转和平移关系。通过在空间中放置已知尺寸的棋盘格,并在两个摄像头中采集相应的图像,可以通过OpenCV的定标函数来计算这些参数。 完成定标后,需要进行校正校正旨在消除因摄像头的畸变引起的图像形状扭曲。OpenCV提供了双目校正函数,它可以根据定标结果来计算校正映射矩阵。这个映射矩阵可以将两个摄像头的图像转换为校正后的图像,使得校正后的图像的对应点在水平方向上具有相同的像素坐标。 校正后,可以利用双目视觉系统进行测距。通过对校正后的图像进行匹配,可以找到两个摄像头中相同场景中的对应点。然后,可以根据这些对应点的像素坐标和摄像头的基线长度,使用三角定位原理来计算物体的实际距离。OpenCV提供了一些函数来执行这些操作,可以通过计算视差(即对应点像素的差值)来获得物体与摄像头之间的距离。 总之,通过OpenCV的定标、校正和测距功能,可以实现双目视觉系统的建立和应用,用于实时测量和深度感知等应用领域。 ### 回答3: 双目视觉是一种使用两个摄像头同时获取场景信息的技术,通过计算两个摄像头之间的视差,可以实现三维场景的测量和距离计算。在进行双目视觉之前需要进行定标、校正和测距的步骤。 首先是定标步骤。双目相机需要确定两个摄像头之间的相对位置和姿态,这个过程称为相机的定标。定标时需要使用一个已知尺寸的物体,如棋盘格,拍摄多张图像,通过计算图像中棋盘格的角点坐标,可以得到相机的内外参数,包括焦距、畸变等参数。 接下来是校正步骤。校正是为了消除图像中的畸变,使得图像中的像素和实际物理距离之间能够相互对应。校正的过程主要包括去除镜头畸变和图像的对齐。通过定标得到的相机参数,可以将图像进行畸变矫正,使得棋盘格的角点在校正后的图像中在同一条直线上。同时,还需要对两个摄像头的图像进行对齐,使得左右眼的图像中相同位置的像素能够对应。 最后是测距步骤。在定标和校正之后,就可以进行双目视觉的测距了。测距的原理是根据视差来计算物体到摄像头的距离。通过获取左右眼图像中相同的像素点,计算其在图像中的视差,然后利用已知的相机参数和视差公式,可以得到物体的距离。在实际应用中,可以采用三角测距法或基于深度学习的方法来进行测距。 双目视觉的定标、校正和测距是实现双目测距的重要步骤,通过这些步骤可以得到准确的距离信息,从而实现更精确的三维场景重建、物体检测等应用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值