1 /* This is sample from the OpenCV book. The copyright notice is below */
3 /* *************** License:**************************
5 Right to use this code in any way you want without warranty, support or any guarantee of it working.
7 BOOK: It would be nice if you cited it:
8 Learning OpenCV: Computer Vision with the OpenCV Library
9 by Gary Bradski and Adrian Kaehler
10 Published by O'Reilly Media, October 3, 2008
13 http://www.amazon.com/Learning-OpenCV-Computer-Vision-Library/dp/0596516134
14 Or: http://oreilly.com/catalog/9780596516130/
15 ISBN-10: 0596516134 or: ISBN-13: 978-0596516130
18 Homepage: http://opencv.org
19 Online docs: http://docs.opencv.org
20 Q&A forum: http://answers.opencv.org
21 Issue tracker: http://code.opencv.org
22 GitHub: https://github.com/Itseez/opencv/
23 ************************************************** */
25 #include "opencv2/calib3d/calib3d.hpp"
26 #include "opencv2/highgui/highgui.hpp"
27 #include "opencv2/imgproc/imgproc.hpp"
41 static int print_help()
44 " Given a list of chessboard images, the number of corners (nx, ny)\n"
45 " on the chessboards, and a flag: useCalibrated for \n"
46 " calibrated (0) or\n"
48 " (1: use cvStereoCalibrate(), 2: compute fundamental\n"
49 " matrix separately) stereo. \n"
50 " Calibrate the cameras and display the\n"
51 " rectified results along with the computed disparity images. \n" << endl;
52 cout << "Usage:\n ./stereo_calib -w board_width -h board_height [-nr /*dot not view results*/] <image list XML/YML file>\n" << endl;
58 StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=true, bool showRectified=true)
60 if( imagelist.size() % 2 != 0 )
62 cout << "Error: the image list contains odd (non-even) number of elements\n";
66 bool displayCorners = false;//true;
67 const int maxScale = 2;
68 const float squareSize = 1.f; // Set this to your actual square size
69 // ARRAY AND VECTOR STORAGE:
71 vector<vector<Point2f> > imagePoints[2];
72 vector<vector<Point3f> > objectPoints;
75 int i, j, k, nimages = (int)imagelist.size()/2;
77 imagePoints[0].resize(nimages);
78 imagePoints[1].resize(nimages);
79 vector<string> goodImageList;
81 for( i = j = 0; i < nimages; i++ )
83 for( k = 0; k < 2; k++ )
85 const string& filename = imagelist[i*2+k];
86 Mat img = imread(filename, 0);
89 if( imageSize == Size() )
90 imageSize = img.size();
91 else if( img.size() != imageSize )
93 cout << "The image " << filename << " has the size different from the first image size. Skipping the pair\n";
97 vector<Point2f>& corners = imagePoints[k][j];
98 for( int scale = 1; scale <= maxScale; scale++ )
104 resize(img, timg, Size(), scale, scale);
105 found = findChessboardCorners(timg, boardSize, corners,
106 CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE);
111 Mat cornersMat(corners);
112 cornersMat *= 1./scale;
119 cout << filename << endl;
121 cvtColor(img, cimg, CV_GRAY2BGR);
122 drawChessboardCorners(cimg, boardSize, corners, found);
123 double sf = 640./MAX(img.rows, img.cols);
124 resize(cimg, cimg1, Size(), sf, sf);
125 imshow("corners", cimg1);
126 char c = (char)waitKey(500);
127 if( c == 27 || c == 'q' || c == 'Q' ) //Allow ESC to quit
134 cornerSubPix(img, corners, Size(11,11), Size(-1,-1),
135 TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,
140 goodImageList.push_back(imagelist[i*2]);
141 goodImageList.push_back(imagelist[i*2+1]);
145 cout << j << " pairs have been successfully detected.\n";
149 cout << "Error: too little pairs to run the calibration\n";
153 imagePoints[0].resize(nimages);
154 imagePoints[1].resize(nimages);
155 objectPoints.resize(nimages);
157 for( i = 0; i < nimages; i++ )
159 for( j = 0; j < boardSize.height; j++ )
160 for( k = 0; k < boardSize.width; k++ )
161 objectPoints[i].push_back(Point3f(j*squareSize, k*squareSize, 0));
164 cout << "Running stereo calibration ...\n";
166 Mat cameraMatrix[2], distCoeffs[2];
167 cameraMatrix[0] = Mat::eye(3, 3, CV_64F);
168 cameraMatrix[1] = Mat::eye(3, 3, CV_64F);
171 double rms = stereoCalibrate(objectPoints, imagePoints[0], imagePoints[1],
172 cameraMatrix[0], distCoeffs[0],
173 cameraMatrix[1], distCoeffs[1],
174 imageSize, R, T, E, F,
175 TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, 1e-5),
176 CV_CALIB_FIX_ASPECT_RATIO +
177 CV_CALIB_ZERO_TANGENT_DIST +
178 CV_CALIB_SAME_FOCAL_LENGTH +
179 CV_CALIB_RATIONAL_MODEL +
180 CV_CALIB_FIX_K3 + CV_CALIB_FIX_K4 + CV_CALIB_FIX_K5);
181 cout << "done with RMS error=" << rms << endl;
183 // CALIBRATION QUALITY CHECK
184 // because the output fundamental matrix implicitly
185 // includes all the output information,
186 // we can check the quality of calibration using the
187 // epipolar geometry constraint: m2^t*F*m1=0
190 vector<Vec3f> lines[2];
191 for( i = 0; i < nimages; i++ )
193 int npt = (int)imagePoints[0][i].size();
195 for( k = 0; k < 2; k++ )
197 imgpt[k] = Mat(imagePoints[k][i]);
198 undistortPoints(imgpt[k], imgpt[k], cameraMatrix[k], distCoeffs[k], Mat(), cameraMatrix[k]);
199 computeCorrespondEpilines(imgpt[k], k+1, F, lines[k]);
201 for( j = 0; j < npt; j++ )
203 double errij = fabs(imagePoints[0][i][j].x*lines[1][j][0] +
204 imagePoints[0][i][j].y*lines[1][j][1] + lines[1][j][2]) +
205 fabs(imagePoints[1][i][j].x*lines[0][j][0] +
206 imagePoints[1][i][j].y*lines[0][j][1] + lines[0][j][2]);
211 cout << "average reprojection err = " << err/npoints << endl;
213 // save intrinsic parameters
214 FileStorage fs("intrinsics.yml", CV_STORAGE_WRITE);
217 fs << "M1" << cameraMatrix[0] << "D1" << distCoeffs[0] <<
218 "M2" << cameraMatrix[1] << "D2" << distCoeffs[1];
222 cout << "Error: can not save the intrinsic parameters\n";
224 Mat R1, R2, P1, P2, Q;
227 stereoRectify(cameraMatrix[0], distCoeffs[0],
228 cameraMatrix[1], distCoeffs[1],
229 imageSize, R, T, R1, R2, P1, P2, Q,
230 CALIB_ZERO_DISPARITY, 1, imageSize, &validRoi[0], &validRoi[1]);
232 fs.open("extrinsics.yml", CV_STORAGE_WRITE);
235 fs << "R" << R << "T" << T << "R1" << R1 << "R2" << R2 << "P1" << P1 << "P2" << P2 << "Q" << Q;
239 cout << "Error: can not save the intrinsic parameters\n";
241 // OpenCV can handle left-right
242 // or up-down camera arrangements
243 bool isVerticalStereo = fabs(P2.at<double>(1, 3)) > fabs(P2.at<double>(0, 3));
245 // COMPUTE AND DISPLAY RECTIFICATION
250 // IF BY CALIBRATED (BOUGUET'S METHOD)
253 // we already computed everything
255 // OR ELSE HARTLEY'S METHOD
257 // use intrinsic parameters of each camera, but
258 // compute the rectification transformation directly
259 // from the fundamental matrix
261 vector<Point2f> allimgpt[2];
262 for( k = 0; k < 2; k++ )
264 for( i = 0; i < nimages; i++ )
265 std::copy(imagePoints[k][i].begin(), imagePoints[k][i].end(), back_inserter(allimgpt[k]));
267 F = findFundamentalMat(Mat(allimgpt[0]), Mat(allimgpt[1]), FM_8POINT, 0, 0);
269 stereoRectifyUncalibrated(Mat(allimgpt[0]), Mat(allimgpt[1]), F, imageSize, H1, H2, 3);
271 R1 = cameraMatrix[0].inv()*H1*cameraMatrix[0];
272 R2 = cameraMatrix[1].inv()*H2*cameraMatrix[1];
273 P1 = cameraMatrix[0];
274 P2 = cameraMatrix[1];
277 //Precompute maps for cv::remap()
278 initUndistortRectifyMap(cameraMatrix[0], distCoeffs[0], R1, P1, imageSize, CV_16SC2, rmap[0][0], rmap[0][1]);
279 initUndistortRectifyMap(cameraMatrix[1], distCoeffs[1], R2, P2, imageSize, CV_16SC2, rmap[1][0], rmap[1][1]);
284 if( !isVerticalStereo )
286 sf = 600./MAX(imageSize.width, imageSize.height);
287 w = cvRound(imageSize.width*sf);
288 h = cvRound(imageSize.height*sf);
289 canvas.create(h, w*2, CV_8UC3);
293 sf = 300./MAX(imageSize.width, imageSize.height);
294 w = cvRound(imageSize.width*sf);
295 h = cvRound(imageSize.height*sf);
296 canvas.create(h*2, w, CV_8UC3);
299 for( i = 0; i < nimages; i++ )
301 for( k = 0; k < 2; k++ )
303 Mat img = imread(goodImageList[i*2+k], 0), rimg, cimg;
304 remap(img, rimg, rmap[k][0], rmap[k][1], CV_INTER_LINEAR);
305 cvtColor(rimg, cimg, CV_GRAY2BGR);
306 Mat canvasPart = !isVerticalStereo ? canvas(Rect(w*k, 0, w, h)) : canvas(Rect(0, h*k, w, h));
307 resize(cimg, canvasPart, canvasPart.size(), 0, 0, CV_INTER_AREA);
310 Rect vroi(cvRound(validRoi[k].x*sf), cvRound(validRoi[k].y*sf),
311 cvRound(validRoi[k].width*sf), cvRound(validRoi[k].height*sf));
312 rectangle(canvasPart, vroi, Scalar(0,0,255), 3, 8);
316 if( !isVerticalStereo )
317 for( j = 0; j < canvas.rows; j += 16 )
318 line(canvas, Point(0, j), Point(canvas.cols, j), Scalar(0, 255, 0), 1, 8);
320 for( j = 0; j < canvas.cols; j += 16 )
321 line(canvas, Point(j, 0), Point(j, canvas.rows), Scalar(0, 255, 0), 1, 8);
322 imshow("rectified", canvas);
323 char c = (char)waitKey();
324 if( c == 27 || c == 'q' || c == 'Q' )
330 static bool readStringList( const string& filename, vector<string>& l )
333 FileStorage fs(filename, FileStorage::READ);
336 FileNode n = fs.getFirstTopLevelNode();
337 if( n.type() != FileNode::SEQ )
339 FileNodeIterator it = n.begin(), it_end = n.end();
340 for( ; it != it_end; ++it )
341 l.push_back((string)*it);
345 int main(int argc, char** argv)
349 bool showRectified = true;
351 for( int i = 1; i < argc; i++ )
353 if( string(argv[i]) == "-w" )
355 if( sscanf(argv[++i], "%d", &boardSize.width) != 1 || boardSize.width <= 0 )
357 cout << "invalid board width" << endl;
361 else if( string(argv[i]) == "-h" )
363 if( sscanf(argv[++i], "%d", &boardSize.height) != 1 || boardSize.height <= 0 )
365 cout << "invalid board height" << endl;
369 else if( string(argv[i]) == "-nr" )
370 showRectified = false;
371 else if( string(argv[i]) == "--help" )
373 else if( argv[i][0] == '-' )
375 cout << "invalid option " << argv[i] << endl;
379 imagelistfn = argv[i];
382 if( imagelistfn == "" )
384 imagelistfn = "stereo_calib.xml";
385 boardSize = Size(9, 6);
387 else if( boardSize.width <= 0 || boardSize.height <= 0 )
389 cout << "if you specified XML file with chessboards, you should also specify the board width and height (-w and -h options)" << endl;
393 vector<string> imagelist;
394 bool ok = readStringList(imagelistfn, imagelist);
395 if(!ok || imagelist.empty())
397 cout << "can not open " << imagelistfn << " or the string list is empty" << endl;
401 StereoCalib(imagelist, boardSize, true, showRectified);