~paparazzi-uav/paparazzi/v5.0-manual

« back to all changes in this revision

Viewing changes to sw/ext/opencv_bebop/opencv/samples/cpp/calibration.cpp

  • Committer: Paparazzi buildbot
  • Date: 2016-05-18 15:00:29 UTC
  • Revision ID: felix.ruess+docbot@gmail.com-20160518150029-e8lgzi5kvb4p7un9
Manual import commit 4b8bbb730080dac23cf816b98908dacfabe2a8ec from v5.0 branch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#include "opencv2/core.hpp"
 
2
#include <opencv2/core/utility.hpp>
 
3
#include "opencv2/imgproc.hpp"
 
4
#include "opencv2/calib3d.hpp"
 
5
#include "opencv2/imgcodecs.hpp"
 
6
#include "opencv2/videoio.hpp"
 
7
#include "opencv2/highgui.hpp"
 
8
 
 
9
#include <cctype>
 
10
#include <stdio.h>
 
11
#include <string.h>
 
12
#include <time.h>
 
13
 
 
14
using namespace cv;
 
15
using namespace std;
 
16
 
 
17
const char * usage =
 
18
" \nexample command line for calibration from a live feed.\n"
 
19
"   calibration  -w=4 -h=5 -s=0.025 -o=camera.yml -op -oe\n"
 
20
" \n"
 
21
" example command line for calibration from a list of stored images:\n"
 
22
"   imagelist_creator image_list.xml *.png\n"
 
23
"   calibration -w=4 -h=5 -s=0.025 -o=camera.yml -op -oe image_list.xml\n"
 
24
" where image_list.xml is the standard OpenCV XML/YAML\n"
 
25
" use imagelist_creator to create the xml or yaml list\n"
 
26
" file consisting of the list of strings, e.g.:\n"
 
27
" \n"
 
28
"<?xml version=\"1.0\"?>\n"
 
29
"<opencv_storage>\n"
 
30
"<images>\n"
 
31
"view000.png\n"
 
32
"view001.png\n"
 
33
"<!-- view002.png -->\n"
 
34
"view003.png\n"
 
35
"view010.png\n"
 
36
"one_extra_view.jpg\n"
 
37
"</images>\n"
 
38
"</opencv_storage>\n";
 
39
 
 
40
 
 
41
 
 
42
 
 
43
const char* liveCaptureHelp =
 
44
    "When the live video from camera is used as input, the following hot-keys may be used:\n"
 
45
        "  <ESC>, 'q' - quit the program\n"
 
46
        "  'g' - start capturing images\n"
 
47
        "  'u' - switch undistortion on/off\n";
 
48
 
 
49
static void help()
 
50
{
 
51
    printf( "This is a camera calibration sample.\n"
 
52
        "Usage: calibration\n"
 
53
        "     -w=<board_width>         # the number of inner corners per one of board dimension\n"
 
54
        "     -h=<board_height>        # the number of inner corners per another board dimension\n"
 
55
        "     [-pt=<pattern>]          # the type of pattern: chessboard or circles' grid\n"
 
56
        "     [-n=<number_of_frames>]  # the number of frames to use for calibration\n"
 
57
        "                              # (if not specified, it will be set to the number\n"
 
58
        "                              #  of board views actually available)\n"
 
59
        "     [-d=<delay>]             # a minimum delay in ms between subsequent attempts to capture a next view\n"
 
60
        "                              # (used only for video capturing)\n"
 
61
        "     [-s=<squareSize>]       # square size in some user-defined units (1 by default)\n"
 
62
        "     [-o=<out_camera_params>] # the output filename for intrinsic [and extrinsic] parameters\n"
 
63
        "     [-op]                    # write detected feature points\n"
 
64
        "     [-oe]                    # write extrinsic parameters\n"
 
65
        "     [-zt]                    # assume zero tangential distortion\n"
 
66
        "     [-a=<aspectRatio>]      # fix aspect ratio (fx/fy)\n"
 
67
        "     [-p]                     # fix the principal point at the center\n"
 
68
        "     [-v]                     # flip the captured images around the horizontal axis\n"
 
69
        "     [-V]                     # use a video file, and not an image list, uses\n"
 
70
        "                              # [input_data] string for the video file name\n"
 
71
        "     [-su]                    # show undistorted images after calibration\n"
 
72
        "     [input_data]             # input data, one of the following:\n"
 
73
        "                              #  - text file with a list of the images of the board\n"
 
74
        "                              #    the text file can be generated with imagelist_creator\n"
 
75
        "                              #  - name of video file with a video of the board\n"
 
76
        "                              # if input_data not specified, a live view from the camera is used\n"
 
77
        "\n" );
 
78
    printf("\n%s",usage);
 
79
    printf( "\n%s", liveCaptureHelp );
 
80
}
 
81
 
 
82
enum { DETECTION = 0, CAPTURING = 1, CALIBRATED = 2 };
 
83
enum Pattern { CHESSBOARD, CIRCLES_GRID, ASYMMETRIC_CIRCLES_GRID };
 
84
 
 
85
static double computeReprojectionErrors(
 
86
        const vector<vector<Point3f> >& objectPoints,
 
87
        const vector<vector<Point2f> >& imagePoints,
 
88
        const vector<Mat>& rvecs, const vector<Mat>& tvecs,
 
89
        const Mat& cameraMatrix, const Mat& distCoeffs,
 
90
        vector<float>& perViewErrors )
 
91
{
 
92
    vector<Point2f> imagePoints2;
 
93
    int i, totalPoints = 0;
 
94
    double totalErr = 0, err;
 
95
    perViewErrors.resize(objectPoints.size());
 
96
 
 
97
    for( i = 0; i < (int)objectPoints.size(); i++ )
 
98
    {
 
99
        projectPoints(Mat(objectPoints[i]), rvecs[i], tvecs[i],
 
100
                      cameraMatrix, distCoeffs, imagePoints2);
 
101
        err = norm(Mat(imagePoints[i]), Mat(imagePoints2), NORM_L2);
 
102
        int n = (int)objectPoints[i].size();
 
103
        perViewErrors[i] = (float)std::sqrt(err*err/n);
 
104
        totalErr += err*err;
 
105
        totalPoints += n;
 
106
    }
 
107
 
 
108
    return std::sqrt(totalErr/totalPoints);
 
109
}
 
110
 
 
111
static void calcChessboardCorners(Size boardSize, float squareSize, vector<Point3f>& corners, Pattern patternType = CHESSBOARD)
 
112
{
 
113
    corners.resize(0);
 
114
 
 
115
    switch(patternType)
 
116
    {
 
117
      case CHESSBOARD:
 
118
      case CIRCLES_GRID:
 
119
        for( int i = 0; i < boardSize.height; i++ )
 
120
            for( int j = 0; j < boardSize.width; j++ )
 
121
                corners.push_back(Point3f(float(j*squareSize),
 
122
                                          float(i*squareSize), 0));
 
123
        break;
 
124
 
 
125
      case ASYMMETRIC_CIRCLES_GRID:
 
126
        for( int i = 0; i < boardSize.height; i++ )
 
127
            for( int j = 0; j < boardSize.width; j++ )
 
128
                corners.push_back(Point3f(float((2*j + i % 2)*squareSize),
 
129
                                          float(i*squareSize), 0));
 
130
        break;
 
131
 
 
132
      default:
 
133
        CV_Error(Error::StsBadArg, "Unknown pattern type\n");
 
134
    }
 
135
}
 
136
 
 
137
static bool runCalibration( vector<vector<Point2f> > imagePoints,
 
138
                    Size imageSize, Size boardSize, Pattern patternType,
 
139
                    float squareSize, float aspectRatio,
 
140
                    int flags, Mat& cameraMatrix, Mat& distCoeffs,
 
141
                    vector<Mat>& rvecs, vector<Mat>& tvecs,
 
142
                    vector<float>& reprojErrs,
 
143
                    double& totalAvgErr)
 
144
{
 
145
    cameraMatrix = Mat::eye(3, 3, CV_64F);
 
146
    if( flags & CALIB_FIX_ASPECT_RATIO )
 
147
        cameraMatrix.at<double>(0,0) = aspectRatio;
 
148
 
 
149
    distCoeffs = Mat::zeros(8, 1, CV_64F);
 
150
 
 
151
    vector<vector<Point3f> > objectPoints(1);
 
152
    calcChessboardCorners(boardSize, squareSize, objectPoints[0], patternType);
 
153
 
 
154
    objectPoints.resize(imagePoints.size(),objectPoints[0]);
 
155
 
 
156
    double rms = calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix,
 
157
                    distCoeffs, rvecs, tvecs, flags|CALIB_FIX_K4|CALIB_FIX_K5);
 
158
                    ///*|CALIB_FIX_K3*/|CALIB_FIX_K4|CALIB_FIX_K5);
 
159
    printf("RMS error reported by calibrateCamera: %g\n", rms);
 
160
 
 
161
    bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs);
 
162
 
 
163
    totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints,
 
164
                rvecs, tvecs, cameraMatrix, distCoeffs, reprojErrs);
 
165
 
 
166
    return ok;
 
167
}
 
168
 
 
169
 
 
170
static void saveCameraParams( const string& filename,
 
171
                       Size imageSize, Size boardSize,
 
172
                       float squareSize, float aspectRatio, int flags,
 
173
                       const Mat& cameraMatrix, const Mat& distCoeffs,
 
174
                       const vector<Mat>& rvecs, const vector<Mat>& tvecs,
 
175
                       const vector<float>& reprojErrs,
 
176
                       const vector<vector<Point2f> >& imagePoints,
 
177
                       double totalAvgErr )
 
178
{
 
179
    FileStorage fs( filename, FileStorage::WRITE );
 
180
 
 
181
    time_t tt;
 
182
    time( &tt );
 
183
    struct tm *t2 = localtime( &tt );
 
184
    char buf[1024];
 
185
    strftime( buf, sizeof(buf)-1, "%c", t2 );
 
186
 
 
187
    fs << "calibration_time" << buf;
 
188
 
 
189
    if( !rvecs.empty() || !reprojErrs.empty() )
 
190
        fs << "nframes" << (int)std::max(rvecs.size(), reprojErrs.size());
 
191
    fs << "image_width" << imageSize.width;
 
192
    fs << "image_height" << imageSize.height;
 
193
    fs << "board_width" << boardSize.width;
 
194
    fs << "board_height" << boardSize.height;
 
195
    fs << "square_size" << squareSize;
 
196
 
 
197
    if( flags & CALIB_FIX_ASPECT_RATIO )
 
198
        fs << "aspectRatio" << aspectRatio;
 
199
 
 
200
    if( flags != 0 )
 
201
    {
 
202
        sprintf( buf, "flags: %s%s%s%s",
 
203
            flags & CALIB_USE_INTRINSIC_GUESS ? "+use_intrinsic_guess" : "",
 
204
            flags & CALIB_FIX_ASPECT_RATIO ? "+fix_aspectRatio" : "",
 
205
            flags & CALIB_FIX_PRINCIPAL_POINT ? "+fix_principal_point" : "",
 
206
            flags & CALIB_ZERO_TANGENT_DIST ? "+zero_tangent_dist" : "" );
 
207
        //cvWriteComment( *fs, buf, 0 );
 
208
    }
 
209
 
 
210
    fs << "flags" << flags;
 
211
 
 
212
    fs << "camera_matrix" << cameraMatrix;
 
213
    fs << "distortion_coefficients" << distCoeffs;
 
214
 
 
215
    fs << "avg_reprojection_error" << totalAvgErr;
 
216
    if( !reprojErrs.empty() )
 
217
        fs << "per_view_reprojection_errors" << Mat(reprojErrs);
 
218
 
 
219
    if( !rvecs.empty() && !tvecs.empty() )
 
220
    {
 
221
        CV_Assert(rvecs[0].type() == tvecs[0].type());
 
222
        Mat bigmat((int)rvecs.size(), 6, rvecs[0].type());
 
223
        for( int i = 0; i < (int)rvecs.size(); i++ )
 
224
        {
 
225
            Mat r = bigmat(Range(i, i+1), Range(0,3));
 
226
            Mat t = bigmat(Range(i, i+1), Range(3,6));
 
227
 
 
228
            CV_Assert(rvecs[i].rows == 3 && rvecs[i].cols == 1);
 
229
            CV_Assert(tvecs[i].rows == 3 && tvecs[i].cols == 1);
 
230
            //*.t() is MatExpr (not Mat) so we can use assignment operator
 
231
            r = rvecs[i].t();
 
232
            t = tvecs[i].t();
 
233
        }
 
234
        //cvWriteComment( *fs, "a set of 6-tuples (rotation vector + translation vector) for each view", 0 );
 
235
        fs << "extrinsic_parameters" << bigmat;
 
236
    }
 
237
 
 
238
    if( !imagePoints.empty() )
 
239
    {
 
240
        Mat imagePtMat((int)imagePoints.size(), (int)imagePoints[0].size(), CV_32FC2);
 
241
        for( int i = 0; i < (int)imagePoints.size(); i++ )
 
242
        {
 
243
            Mat r = imagePtMat.row(i).reshape(2, imagePtMat.cols);
 
244
            Mat imgpti(imagePoints[i]);
 
245
            imgpti.copyTo(r);
 
246
        }
 
247
        fs << "image_points" << imagePtMat;
 
248
    }
 
249
}
 
250
 
 
251
static bool readStringList( const string& filename, vector<string>& l )
 
252
{
 
253
    l.resize(0);
 
254
    FileStorage fs(filename, FileStorage::READ);
 
255
    if( !fs.isOpened() )
 
256
        return false;
 
257
    FileNode n = fs.getFirstTopLevelNode();
 
258
    if( n.type() != FileNode::SEQ )
 
259
        return false;
 
260
    FileNodeIterator it = n.begin(), it_end = n.end();
 
261
    for( ; it != it_end; ++it )
 
262
        l.push_back((string)*it);
 
263
    return true;
 
264
}
 
265
 
 
266
 
 
267
static bool runAndSave(const string& outputFilename,
 
268
                const vector<vector<Point2f> >& imagePoints,
 
269
                Size imageSize, Size boardSize, Pattern patternType, float squareSize,
 
270
                float aspectRatio, int flags, Mat& cameraMatrix,
 
271
                Mat& distCoeffs, bool writeExtrinsics, bool writePoints )
 
272
{
 
273
    vector<Mat> rvecs, tvecs;
 
274
    vector<float> reprojErrs;
 
275
    double totalAvgErr = 0;
 
276
 
 
277
    bool ok = runCalibration(imagePoints, imageSize, boardSize, patternType, squareSize,
 
278
                   aspectRatio, flags, cameraMatrix, distCoeffs,
 
279
                   rvecs, tvecs, reprojErrs, totalAvgErr);
 
280
    printf("%s. avg reprojection error = %.2f\n",
 
281
           ok ? "Calibration succeeded" : "Calibration failed",
 
282
           totalAvgErr);
 
283
 
 
284
    if( ok )
 
285
        saveCameraParams( outputFilename, imageSize,
 
286
                         boardSize, squareSize, aspectRatio,
 
287
                         flags, cameraMatrix, distCoeffs,
 
288
                         writeExtrinsics ? rvecs : vector<Mat>(),
 
289
                         writeExtrinsics ? tvecs : vector<Mat>(),
 
290
                         writeExtrinsics ? reprojErrs : vector<float>(),
 
291
                         writePoints ? imagePoints : vector<vector<Point2f> >(),
 
292
                         totalAvgErr );
 
293
    return ok;
 
294
}
 
295
 
 
296
 
 
297
int main( int argc, char** argv )
 
298
{
 
299
    Size boardSize, imageSize;
 
300
    float squareSize, aspectRatio;
 
301
    Mat cameraMatrix, distCoeffs;
 
302
    string outputFilename;
 
303
    string inputFilename = "";
 
304
 
 
305
    int i, nframes;
 
306
    bool writeExtrinsics, writePoints;
 
307
    bool undistortImage = false;
 
308
    int flags = 0;
 
309
    VideoCapture capture;
 
310
    bool flipVertical;
 
311
    bool showUndistorted;
 
312
    bool videofile;
 
313
    int delay;
 
314
    clock_t prevTimestamp = 0;
 
315
    int mode = DETECTION;
 
316
    int cameraId = 0;
 
317
    vector<vector<Point2f> > imagePoints;
 
318
    vector<string> imageList;
 
319
    Pattern pattern = CHESSBOARD;
 
320
 
 
321
    cv::CommandLineParser parser(argc, argv,
 
322
        "{help ||}{w||}{h||}{pt|chessboard|}{n|10|}{d|1000|}{s|1|}{o|out_camera_data.yml|}"
 
323
        "{op||}{oe||}{zt||}{a|1|}{p||}{v||}{V||}{su||}"
 
324
        "{@input_data|0|}");
 
325
    if (parser.has("help"))
 
326
    {
 
327
        help();
 
328
        return 0;
 
329
    }
 
330
    boardSize.width = parser.get<int>( "w" );
 
331
    boardSize.height = parser.get<int>( "h" );
 
332
    if ( parser.has("pt") )
 
333
    {
 
334
        string val = parser.get<string>("pt");
 
335
        if( val == "circles" )
 
336
            pattern = CIRCLES_GRID;
 
337
        else if( val == "acircles" )
 
338
            pattern = ASYMMETRIC_CIRCLES_GRID;
 
339
        else if( val == "chessboard" )
 
340
            pattern = CHESSBOARD;
 
341
        else
 
342
            return fprintf( stderr, "Invalid pattern type: must be chessboard or circles\n" ), -1;
 
343
    }
 
344
    squareSize = parser.get<float>("s");
 
345
    nframes = parser.get<int>("n");
 
346
    aspectRatio = parser.get<float>("a");
 
347
    delay = parser.get<int>("d");
 
348
    writePoints = parser.has("op");
 
349
    writeExtrinsics = parser.has("oe");
 
350
    if (parser.has("a"))
 
351
        flags |= CALIB_FIX_ASPECT_RATIO;
 
352
    if ( parser.has("zt") )
 
353
        flags |= CALIB_ZERO_TANGENT_DIST;
 
354
    if ( parser.has("p") )
 
355
        flags |= CALIB_FIX_PRINCIPAL_POINT;
 
356
    flipVertical = parser.has("v");
 
357
    videofile = parser.has("V");
 
358
    if ( parser.has("o") )
 
359
        outputFilename = parser.get<string>("o");
 
360
    showUndistorted = parser.has("su");
 
361
    if ( isdigit(parser.get<string>("@input_data")[0]) )
 
362
        cameraId = parser.get<int>("@input_data");
 
363
    else
 
364
        inputFilename = parser.get<string>("@input_data");
 
365
    if (!parser.check())
 
366
    {
 
367
        help();
 
368
        parser.printErrors();
 
369
        return -1;
 
370
    }
 
371
    if ( squareSize <= 0 )
 
372
        return fprintf( stderr, "Invalid board square width\n" ), -1;
 
373
    if ( nframes <= 3 )
 
374
        return printf("Invalid number of images\n" ), -1;
 
375
    if ( aspectRatio <= 0 )
 
376
        return printf( "Invalid aspect ratio\n" ), -1;
 
377
    if ( delay <= 0 )
 
378
        return printf( "Invalid delay\n" ), -1;
 
379
    if ( boardSize.width <= 0 )
 
380
        return fprintf( stderr, "Invalid board width\n" ), -1;
 
381
    if ( boardSize.height <= 0 )
 
382
        return fprintf( stderr, "Invalid board height\n" ), -1;
 
383
 
 
384
    if( !inputFilename.empty() )
 
385
    {
 
386
        if( !videofile && readStringList(inputFilename, imageList) )
 
387
            mode = CAPTURING;
 
388
        else
 
389
            capture.open(inputFilename);
 
390
    }
 
391
    else
 
392
        capture.open(cameraId);
 
393
 
 
394
    if( !capture.isOpened() && imageList.empty() )
 
395
        return fprintf( stderr, "Could not initialize video (%d) capture\n",cameraId ), -2;
 
396
 
 
397
    if( !imageList.empty() )
 
398
        nframes = (int)imageList.size();
 
399
 
 
400
    if( capture.isOpened() )
 
401
        printf( "%s", liveCaptureHelp );
 
402
 
 
403
    namedWindow( "Image View", 1 );
 
404
 
 
405
    for(i = 0;;i++)
 
406
    {
 
407
        Mat view, viewGray;
 
408
        bool blink = false;
 
409
 
 
410
        if( capture.isOpened() )
 
411
        {
 
412
            Mat view0;
 
413
            capture >> view0;
 
414
            view0.copyTo(view);
 
415
        }
 
416
        else if( i < (int)imageList.size() )
 
417
            view = imread(imageList[i], 1);
 
418
 
 
419
        if(view.empty())
 
420
        {
 
421
            if( imagePoints.size() > 0 )
 
422
                runAndSave(outputFilename, imagePoints, imageSize,
 
423
                           boardSize, pattern, squareSize, aspectRatio,
 
424
                           flags, cameraMatrix, distCoeffs,
 
425
                           writeExtrinsics, writePoints);
 
426
            break;
 
427
        }
 
428
 
 
429
        imageSize = view.size();
 
430
 
 
431
        if( flipVertical )
 
432
            flip( view, view, 0 );
 
433
 
 
434
        vector<Point2f> pointbuf;
 
435
        cvtColor(view, viewGray, COLOR_BGR2GRAY);
 
436
 
 
437
        bool found;
 
438
        switch( pattern )
 
439
        {
 
440
            case CHESSBOARD:
 
441
                found = findChessboardCorners( view, boardSize, pointbuf,
 
442
                    CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_FAST_CHECK | CALIB_CB_NORMALIZE_IMAGE);
 
443
                break;
 
444
            case CIRCLES_GRID:
 
445
                found = findCirclesGrid( view, boardSize, pointbuf );
 
446
                break;
 
447
            case ASYMMETRIC_CIRCLES_GRID:
 
448
                found = findCirclesGrid( view, boardSize, pointbuf, CALIB_CB_ASYMMETRIC_GRID );
 
449
                break;
 
450
            default:
 
451
                return fprintf( stderr, "Unknown pattern type\n" ), -1;
 
452
        }
 
453
 
 
454
       // improve the found corners' coordinate accuracy
 
455
        if( pattern == CHESSBOARD && found) cornerSubPix( viewGray, pointbuf, Size(11,11),
 
456
            Size(-1,-1), TermCriteria( TermCriteria::EPS+TermCriteria::COUNT, 30, 0.1 ));
 
457
 
 
458
        if( mode == CAPTURING && found &&
 
459
           (!capture.isOpened() || clock() - prevTimestamp > delay*1e-3*CLOCKS_PER_SEC) )
 
460
        {
 
461
            imagePoints.push_back(pointbuf);
 
462
            prevTimestamp = clock();
 
463
            blink = capture.isOpened();
 
464
        }
 
465
 
 
466
        if(found)
 
467
            drawChessboardCorners( view, boardSize, Mat(pointbuf), found );
 
468
 
 
469
        string msg = mode == CAPTURING ? "100/100" :
 
470
            mode == CALIBRATED ? "Calibrated" : "Press 'g' to start";
 
471
        int baseLine = 0;
 
472
        Size textSize = getTextSize(msg, 1, 1, 1, &baseLine);
 
473
        Point textOrigin(view.cols - 2*textSize.width - 10, view.rows - 2*baseLine - 10);
 
474
 
 
475
        if( mode == CAPTURING )
 
476
        {
 
477
            if(undistortImage)
 
478
                msg = format( "%d/%d Undist", (int)imagePoints.size(), nframes );
 
479
            else
 
480
                msg = format( "%d/%d", (int)imagePoints.size(), nframes );
 
481
        }
 
482
 
 
483
        putText( view, msg, textOrigin, 1, 1,
 
484
                 mode != CALIBRATED ? Scalar(0,0,255) : Scalar(0,255,0));
 
485
 
 
486
        if( blink )
 
487
            bitwise_not(view, view);
 
488
 
 
489
        if( mode == CALIBRATED && undistortImage )
 
490
        {
 
491
            Mat temp = view.clone();
 
492
            undistort(temp, view, cameraMatrix, distCoeffs);
 
493
        }
 
494
 
 
495
        imshow("Image View", view);
 
496
        int key = 0xff & waitKey(capture.isOpened() ? 50 : 500);
 
497
 
 
498
        if( (key & 255) == 27 )
 
499
            break;
 
500
 
 
501
        if( key == 'u' && mode == CALIBRATED )
 
502
            undistortImage = !undistortImage;
 
503
 
 
504
        if( capture.isOpened() && key == 'g' )
 
505
        {
 
506
            mode = CAPTURING;
 
507
            imagePoints.clear();
 
508
        }
 
509
 
 
510
        if( mode == CAPTURING && imagePoints.size() >= (unsigned)nframes )
 
511
        {
 
512
            if( runAndSave(outputFilename, imagePoints, imageSize,
 
513
                       boardSize, pattern, squareSize, aspectRatio,
 
514
                       flags, cameraMatrix, distCoeffs,
 
515
                       writeExtrinsics, writePoints))
 
516
                mode = CALIBRATED;
 
517
            else
 
518
                mode = DETECTION;
 
519
            if( !capture.isOpened() )
 
520
                break;
 
521
        }
 
522
    }
 
523
 
 
524
    if( !capture.isOpened() && showUndistorted )
 
525
    {
 
526
        Mat view, rview, map1, map2;
 
527
        initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(),
 
528
                                getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0),
 
529
                                imageSize, CV_16SC2, map1, map2);
 
530
 
 
531
        for( i = 0; i < (int)imageList.size(); i++ )
 
532
        {
 
533
            view = imread(imageList[i], 1);
 
534
            if(view.empty())
 
535
                continue;
 
536
            //undistort( view, rview, cameraMatrix, distCoeffs, cameraMatrix );
 
537
            remap(view, rview, map1, map2, INTER_LINEAR);
 
538
            imshow("Image View", rview);
 
539
            int c = 0xff & waitKey();
 
540
            if( (c & 255) == 27 || c == 'q' || c == 'Q' )
 
541
                break;
 
542
        }
 
543
    }
 
544
 
 
545
    return 0;
 
546
}