CLAHE Python bindings
[profile/ivi/opencv.git] / samples / cpp / stereo_calib.cpp
1 /* This is sample from the OpenCV book. The copyright notice is below */
2
3 /* *************** License:**************************
4    Oct. 3, 2008
5    Right to use this code in any way you want without warranty, support or any guarantee of it working.
6
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
11
12    AVAILABLE AT:
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
16
17    OTHER OPENCV SITES:
18    * The source code is on sourceforge at:
19      http://sourceforge.net/projects/opencvlibrary/
20    * The OpenCV wiki page (As of Oct 1, 2008 this is down for changing over servers, but should come back):
21      http://opencvlibrary.sourceforge.net/
22    * An active user group is at:
23      http://tech.groups.yahoo.com/group/OpenCV/
24    * The minutes of weekly OpenCV development meetings are at:
25      http://code.opencv.org/projects/opencv/wiki/Meeting_notes
26    ************************************************** */
27
28 #include "opencv2/calib3d/calib3d.hpp"
29 #include "opencv2/highgui/highgui.hpp"
30 #include "opencv2/imgproc/imgproc.hpp"
31
32 #include <vector>
33 #include <string>
34 #include <algorithm>
35 #include <iostream>
36 #include <iterator>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <ctype.h>
40
41 using namespace cv;
42 using namespace std;
43
44 static int print_help()
45 {
46     cout <<
47             " Given a list of chessboard images, the number of corners (nx, ny)\n"
48             " on the chessboards, and a flag: useCalibrated for \n"
49             "   calibrated (0) or\n"
50             "   uncalibrated \n"
51             "     (1: use cvStereoCalibrate(), 2: compute fundamental\n"
52             "         matrix separately) stereo. \n"
53             " Calibrate the cameras and display the\n"
54             " rectified results along with the computed disparity images.   \n" << endl;
55     cout << "Usage:\n ./stereo_calib -w board_width -h board_height [-nr /*dot not view results*/] <image list XML/YML file>\n" << endl;
56     return 0;
57 }
58
59
60 static void
61 StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=true, bool showRectified=true)
62 {
63     if( imagelist.size() % 2 != 0 )
64     {
65         cout << "Error: the image list contains odd (non-even) number of elements\n";
66         return;
67     }
68
69     bool displayCorners = false;//true;
70     const int maxScale = 2;
71     const float squareSize = 1.f;  // Set this to your actual square size
72     // ARRAY AND VECTOR STORAGE:
73
74     vector<vector<Point2f> > imagePoints[2];
75     vector<vector<Point3f> > objectPoints;
76     Size imageSize;
77
78     int i, j, k, nimages = (int)imagelist.size()/2;
79
80     imagePoints[0].resize(nimages);
81     imagePoints[1].resize(nimages);
82     vector<string> goodImageList;
83
84     for( i = j = 0; i < nimages; i++ )
85     {
86         for( k = 0; k < 2; k++ )
87         {
88             const string& filename = imagelist[i*2+k];
89             Mat img = imread(filename, 0);
90             if(img.empty())
91                 break;
92             if( imageSize == Size() )
93                 imageSize = img.size();
94             else if( img.size() != imageSize )
95             {
96                 cout << "The image " << filename << " has the size different from the first image size. Skipping the pair\n";
97                 break;
98             }
99             bool found = false;
100             vector<Point2f>& corners = imagePoints[k][j];
101             for( int scale = 1; scale <= maxScale; scale++ )
102             {
103                 Mat timg;
104                 if( scale == 1 )
105                     timg = img;
106                 else
107                     resize(img, timg, Size(), scale, scale);
108                 found = findChessboardCorners(timg, boardSize, corners,
109                     CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE);
110                 if( found )
111                 {
112                     if( scale > 1 )
113                     {
114                         Mat cornersMat(corners);
115                         cornersMat *= 1./scale;
116                     }
117                     break;
118                 }
119             }
120             if( displayCorners )
121             {
122                 cout << filename << endl;
123                 Mat cimg, cimg1;
124                 cvtColor(img, cimg, CV_GRAY2BGR);
125                 drawChessboardCorners(cimg, boardSize, corners, found);
126                 double sf = 640./MAX(img.rows, img.cols);
127                 resize(cimg, cimg1, Size(), sf, sf);
128                 imshow("corners", cimg1);
129                 char c = (char)waitKey(500);
130                 if( c == 27 || c == 'q' || c == 'Q' ) //Allow ESC to quit
131                     exit(-1);
132             }
133             else
134                 putchar('.');
135             if( !found )
136                 break;
137             cornerSubPix(img, corners, Size(11,11), Size(-1,-1),
138                          TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,
139                                       30, 0.01));
140         }
141         if( k == 2 )
142         {
143             goodImageList.push_back(imagelist[i*2]);
144             goodImageList.push_back(imagelist[i*2+1]);
145             j++;
146         }
147     }
148     cout << j << " pairs have been successfully detected.\n";
149     nimages = j;
150     if( nimages < 2 )
151     {
152         cout << "Error: too little pairs to run the calibration\n";
153         return;
154     }
155
156     imagePoints[0].resize(nimages);
157     imagePoints[1].resize(nimages);
158     objectPoints.resize(nimages);
159
160     for( i = 0; i < nimages; i++ )
161     {
162         for( j = 0; j < boardSize.height; j++ )
163             for( k = 0; k < boardSize.width; k++ )
164                 objectPoints[i].push_back(Point3f(j*squareSize, k*squareSize, 0));
165     }
166
167     cout << "Running stereo calibration ...\n";
168
169     Mat cameraMatrix[2], distCoeffs[2];
170     cameraMatrix[0] = Mat::eye(3, 3, CV_64F);
171     cameraMatrix[1] = Mat::eye(3, 3, CV_64F);
172     Mat R, T, E, F;
173
174     double rms = stereoCalibrate(objectPoints, imagePoints[0], imagePoints[1],
175                     cameraMatrix[0], distCoeffs[0],
176                     cameraMatrix[1], distCoeffs[1],
177                     imageSize, R, T, E, F,
178                     TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, 1e-5),
179                     CV_CALIB_FIX_ASPECT_RATIO +
180                     CV_CALIB_ZERO_TANGENT_DIST +
181                     CV_CALIB_SAME_FOCAL_LENGTH +
182                     CV_CALIB_RATIONAL_MODEL +
183                     CV_CALIB_FIX_K3 + CV_CALIB_FIX_K4 + CV_CALIB_FIX_K5);
184     cout << "done with RMS error=" << rms << endl;
185
186 // CALIBRATION QUALITY CHECK
187 // because the output fundamental matrix implicitly
188 // includes all the output information,
189 // we can check the quality of calibration using the
190 // epipolar geometry constraint: m2^t*F*m1=0
191     double err = 0;
192     int npoints = 0;
193     vector<Vec3f> lines[2];
194     for( i = 0; i < nimages; i++ )
195     {
196         int npt = (int)imagePoints[0][i].size();
197         Mat imgpt[2];
198         for( k = 0; k < 2; k++ )
199         {
200             imgpt[k] = Mat(imagePoints[k][i]);
201             undistortPoints(imgpt[k], imgpt[k], cameraMatrix[k], distCoeffs[k], Mat(), cameraMatrix[k]);
202             computeCorrespondEpilines(imgpt[k], k+1, F, lines[k]);
203         }
204         for( j = 0; j < npt; j++ )
205         {
206             double errij = fabs(imagePoints[0][i][j].x*lines[1][j][0] +
207                                 imagePoints[0][i][j].y*lines[1][j][1] + lines[1][j][2]) +
208                            fabs(imagePoints[1][i][j].x*lines[0][j][0] +
209                                 imagePoints[1][i][j].y*lines[0][j][1] + lines[0][j][2]);
210             err += errij;
211         }
212         npoints += npt;
213     }
214     cout << "average reprojection err = " <<  err/npoints << endl;
215
216     // save intrinsic parameters
217     FileStorage fs("intrinsics.yml", CV_STORAGE_WRITE);
218     if( fs.isOpened() )
219     {
220         fs << "M1" << cameraMatrix[0] << "D1" << distCoeffs[0] <<
221             "M2" << cameraMatrix[1] << "D2" << distCoeffs[1];
222         fs.release();
223     }
224     else
225         cout << "Error: can not save the intrinsic parameters\n";
226
227     Mat R1, R2, P1, P2, Q;
228     Rect validRoi[2];
229
230     stereoRectify(cameraMatrix[0], distCoeffs[0],
231                   cameraMatrix[1], distCoeffs[1],
232                   imageSize, R, T, R1, R2, P1, P2, Q,
233                   CALIB_ZERO_DISPARITY, 1, imageSize, &validRoi[0], &validRoi[1]);
234
235     fs.open("extrinsics.yml", CV_STORAGE_WRITE);
236     if( fs.isOpened() )
237     {
238         fs << "R" << R << "T" << T << "R1" << R1 << "R2" << R2 << "P1" << P1 << "P2" << P2 << "Q" << Q;
239         fs.release();
240     }
241     else
242         cout << "Error: can not save the intrinsic parameters\n";
243
244     // OpenCV can handle left-right
245     // or up-down camera arrangements
246     bool isVerticalStereo = fabs(P2.at<double>(1, 3)) > fabs(P2.at<double>(0, 3));
247
248 // COMPUTE AND DISPLAY RECTIFICATION
249     if( !showRectified )
250         return;
251
252     Mat rmap[2][2];
253 // IF BY CALIBRATED (BOUGUET'S METHOD)
254     if( useCalibrated )
255     {
256         // we already computed everything
257     }
258 // OR ELSE HARTLEY'S METHOD
259     else
260  // use intrinsic parameters of each camera, but
261  // compute the rectification transformation directly
262  // from the fundamental matrix
263     {
264         vector<Point2f> allimgpt[2];
265         for( k = 0; k < 2; k++ )
266         {
267             for( i = 0; i < nimages; i++ )
268                 std::copy(imagePoints[k][i].begin(), imagePoints[k][i].end(), back_inserter(allimgpt[k]));
269         }
270         F = findFundamentalMat(Mat(allimgpt[0]), Mat(allimgpt[1]), FM_8POINT, 0, 0);
271         Mat H1, H2;
272         stereoRectifyUncalibrated(Mat(allimgpt[0]), Mat(allimgpt[1]), F, imageSize, H1, H2, 3);
273
274         R1 = cameraMatrix[0].inv()*H1*cameraMatrix[0];
275         R2 = cameraMatrix[1].inv()*H2*cameraMatrix[1];
276         P1 = cameraMatrix[0];
277         P2 = cameraMatrix[1];
278     }
279
280     //Precompute maps for cv::remap()
281     initUndistortRectifyMap(cameraMatrix[0], distCoeffs[0], R1, P1, imageSize, CV_16SC2, rmap[0][0], rmap[0][1]);
282     initUndistortRectifyMap(cameraMatrix[1], distCoeffs[1], R2, P2, imageSize, CV_16SC2, rmap[1][0], rmap[1][1]);
283
284     Mat canvas;
285     double sf;
286     int w, h;
287     if( !isVerticalStereo )
288     {
289         sf = 600./MAX(imageSize.width, imageSize.height);
290         w = cvRound(imageSize.width*sf);
291         h = cvRound(imageSize.height*sf);
292         canvas.create(h, w*2, CV_8UC3);
293     }
294     else
295     {
296         sf = 300./MAX(imageSize.width, imageSize.height);
297         w = cvRound(imageSize.width*sf);
298         h = cvRound(imageSize.height*sf);
299         canvas.create(h*2, w, CV_8UC3);
300     }
301
302     for( i = 0; i < nimages; i++ )
303     {
304         for( k = 0; k < 2; k++ )
305         {
306             Mat img = imread(goodImageList[i*2+k], 0), rimg, cimg;
307             remap(img, rimg, rmap[k][0], rmap[k][1], CV_INTER_LINEAR);
308             cvtColor(rimg, cimg, CV_GRAY2BGR);
309             Mat canvasPart = !isVerticalStereo ? canvas(Rect(w*k, 0, w, h)) : canvas(Rect(0, h*k, w, h));
310             resize(cimg, canvasPart, canvasPart.size(), 0, 0, CV_INTER_AREA);
311             if( useCalibrated )
312             {
313                 Rect vroi(cvRound(validRoi[k].x*sf), cvRound(validRoi[k].y*sf),
314                           cvRound(validRoi[k].width*sf), cvRound(validRoi[k].height*sf));
315                 rectangle(canvasPart, vroi, Scalar(0,0,255), 3, 8);
316             }
317         }
318
319         if( !isVerticalStereo )
320             for( j = 0; j < canvas.rows; j += 16 )
321                 line(canvas, Point(0, j), Point(canvas.cols, j), Scalar(0, 255, 0), 1, 8);
322         else
323             for( j = 0; j < canvas.cols; j += 16 )
324                 line(canvas, Point(j, 0), Point(j, canvas.rows), Scalar(0, 255, 0), 1, 8);
325         imshow("rectified", canvas);
326         char c = (char)waitKey();
327         if( c == 27 || c == 'q' || c == 'Q' )
328             break;
329     }
330 }
331
332
333 static bool readStringList( const string& filename, vector<string>& l )
334 {
335     l.resize(0);
336     FileStorage fs(filename, FileStorage::READ);
337     if( !fs.isOpened() )
338         return false;
339     FileNode n = fs.getFirstTopLevelNode();
340     if( n.type() != FileNode::SEQ )
341         return false;
342     FileNodeIterator it = n.begin(), it_end = n.end();
343     for( ; it != it_end; ++it )
344         l.push_back((string)*it);
345     return true;
346 }
347
348 int main(int argc, char** argv)
349 {
350     Size boardSize;
351     string imagelistfn;
352     bool showRectified = true;
353
354     for( int i = 1; i < argc; i++ )
355     {
356         if( string(argv[i]) == "-w" )
357         {
358             if( sscanf(argv[++i], "%d", &boardSize.width) != 1 || boardSize.width <= 0 )
359             {
360                 cout << "invalid board width" << endl;
361                 return print_help();
362             }
363         }
364         else if( string(argv[i]) == "-h" )
365         {
366             if( sscanf(argv[++i], "%d", &boardSize.height) != 1 || boardSize.height <= 0 )
367             {
368                 cout << "invalid board height" << endl;
369                 return print_help();
370             }
371         }
372         else if( string(argv[i]) == "-nr" )
373             showRectified = false;
374         else if( string(argv[i]) == "--help" )
375             return print_help();
376         else if( argv[i][0] == '-' )
377         {
378             cout << "invalid option " << argv[i] << endl;
379             return 0;
380         }
381         else
382             imagelistfn = argv[i];
383     }
384
385     if( imagelistfn == "" )
386     {
387         imagelistfn = "stereo_calib.xml";
388         boardSize = Size(9, 6);
389     }
390     else if( boardSize.width <= 0 || boardSize.height <= 0 )
391     {
392         cout << "if you specified XML file with chessboards, you should also specify the board width and height (-w and -h options)" << endl;
393         return 0;
394     }
395
396     vector<string> imagelist;
397     bool ok = readStringList(imagelistfn, imagelist);
398     if(!ok || imagelist.empty())
399     {
400         cout << "can not open " << imagelistfn << " or the string list is empty" << endl;
401         return print_help();
402     }
403
404     StereoCalib(imagelist, boardSize, true, showRectified);
405     return 0;
406 }
407