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