opencv/samples/cpp/stereo_calib.cpp

408 lines
14 KiB
C++
Raw Normal View History

2010-11-28 00:15:16 +01:00
/* This is sample from the OpenCV book. The copyright notice is below */
/* *************** License:**************************
Oct. 3, 2008
2010-12-04 09:24:31 +01:00
Right to use this code in any way you want without warranty, support or any guarantee of it working.
2010-11-28 00:15:16 +01:00
BOOK: It would be nice if you cited it:
Learning OpenCV: Computer Vision with the OpenCV Library
by Gary Bradski and Adrian Kaehler
Published by O'Reilly Media, October 3, 2008
AVAILABLE AT:
2010-11-28 00:15:16 +01:00
http://www.amazon.com/Learning-OpenCV-Computer-Vision-Library/dp/0596516134
Or: http://oreilly.com/catalog/9780596516130/
ISBN-10: 0596516134 or: ISBN-13: 978-0596516130
2010-11-28 00:15:16 +01:00
OTHER OPENCV SITES:
* The source code is on sourceforge at:
http://sourceforge.net/projects/opencvlibrary/
* The OpenCV wiki page (As of Oct 1, 2008 this is down for changing over servers, but should come back):
http://opencvlibrary.sourceforge.net/
* An active user group is at:
http://tech.groups.yahoo.com/group/OpenCV/
* The minutes of weekly OpenCV development meetings are at:
http://pr.willowgarage.com/wiki/OpenCV
************************************************** */
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/highgui/highgui.hpp"
2010-11-28 20:41:55 +01:00
#include "opencv2/imgproc/imgproc.hpp"
2010-11-28 00:15:16 +01:00
#include <vector>
#include <string>
#include <algorithm>
2010-11-28 20:41:55 +01:00
#include <iostream>
#include <iterator>
2010-11-28 00:15:16 +01:00
#include <stdio.h>
2010-11-28 20:41:55 +01:00
#include <stdlib.h>
2010-11-28 00:15:16 +01:00
#include <ctype.h>
2010-11-28 20:41:55 +01:00
using namespace cv;
2010-11-28 00:15:16 +01:00
using namespace std;
static int print_help()
2010-12-04 09:24:31 +01:00
{
cout <<
" Given a list of chessboard images, the number of corners (nx, ny)\n"
" on the chessboards, and a flag: useCalibrated for \n"
" calibrated (0) or\n"
" uncalibrated \n"
" (1: use cvStereoCalibrate(), 2: compute fundamental\n"
" matrix separately) stereo. \n"
" Calibrate the cameras and display the\n"
" rectified results along with the computed disparity images. \n" << endl;
2010-12-04 09:24:31 +01:00
cout << "Usage:\n ./stereo_calib -w board_width -h board_height [-nr /*dot not view results*/] <image list XML/YML file>\n" << endl;
return 0;
}
2010-11-28 00:15:16 +01:00
static void
2010-11-28 20:41:55 +01:00
StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=true, bool showRectified=true)
2010-11-28 00:15:16 +01:00
{
2010-11-28 20:41:55 +01:00
if( imagelist.size() % 2 != 0 )
2010-11-28 00:15:16 +01:00
{
2010-11-28 20:41:55 +01:00
cout << "Error: the image list contains odd (non-even) number of elements\n";
2010-11-28 00:15:16 +01:00
return;
}
2010-11-29 14:31:52 +01:00
bool displayCorners = false;//true;
2010-11-28 20:41:55 +01:00
const int maxScale = 2;
const float squareSize = 1.f; // Set this to your actual square size
// ARRAY AND VECTOR STORAGE:
2010-11-28 20:41:55 +01:00
vector<vector<Point2f> > imagePoints[2];
vector<vector<Point3f> > objectPoints;
Size imageSize;
2010-11-28 20:41:55 +01:00
int i, j, k, nimages = (int)imagelist.size()/2;
2010-11-28 20:41:55 +01:00
imagePoints[0].resize(nimages);
imagePoints[1].resize(nimages);
vector<string> goodImageList;
2010-11-28 20:41:55 +01:00
for( i = j = 0; i < nimages; i++ )
2010-11-28 00:15:16 +01:00
{
2010-11-28 20:41:55 +01:00
for( k = 0; k < 2; k++ )
2010-11-28 00:15:16 +01:00
{
2010-11-28 20:41:55 +01:00
const string& filename = imagelist[i*2+k];
Mat img = imread(filename, 0);
if(img.empty())
break;
if( imageSize == Size() )
imageSize = img.size();
else if( img.size() != imageSize )
2010-11-28 00:15:16 +01:00
{
2010-11-28 20:41:55 +01:00
cout << "The image " << filename << " has the size different from the first image size. Skipping the pair\n";
break;
2010-11-28 00:15:16 +01:00
}
2010-11-28 20:41:55 +01:00
bool found = false;
vector<Point2f>& corners = imagePoints[k][j];
for( int scale = 1; scale <= maxScale; scale++ )
2010-11-28 00:15:16 +01:00
{
2010-11-28 20:41:55 +01:00
Mat timg;
if( scale == 1 )
timg = img;
else
resize(img, timg, Size(), scale, scale);
found = findChessboardCorners(timg, boardSize, corners,
2010-11-28 20:41:55 +01:00
CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE);
if( found )
{
if( scale > 1 )
{
Mat cornersMat(corners);
cornersMat *= 1./scale;
}
break;
}
2010-11-28 00:15:16 +01:00
}
2010-11-28 20:41:55 +01:00
if( displayCorners )
{
cout << filename << endl;
Mat cimg, cimg1;
cvtColor(img, cimg, CV_GRAY2BGR);
drawChessboardCorners(cimg, boardSize, corners, found);
double sf = 640./MAX(img.rows, img.cols);
resize(cimg, cimg1, Size(), sf, sf);
imshow("corners", cimg1);
char c = (char)waitKey(500);
if( c == 27 || c == 'q' || c == 'Q' ) //Allow ESC to quit
exit(-1);
}
else
putchar('.');
if( !found )
2010-11-28 00:15:16 +01:00
break;
2010-11-28 20:41:55 +01:00
cornerSubPix(img, corners, Size(11,11), Size(-1,-1),
TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,
30, 0.01));
2010-11-28 00:15:16 +01:00
}
2010-11-28 20:41:55 +01:00
if( k == 2 )
2010-11-28 00:15:16 +01:00
{
2010-11-28 20:41:55 +01:00
goodImageList.push_back(imagelist[i*2]);
goodImageList.push_back(imagelist[i*2+1]);
j++;
2010-11-28 00:15:16 +01:00
}
}
2010-11-28 20:41:55 +01:00
cout << j << " pairs have been successfully detected.\n";
nimages = j;
if( nimages < 2 )
{
cout << "Error: too little pairs to run the calibration\n";
return;
}
2010-11-28 20:41:55 +01:00
imagePoints[0].resize(nimages);
imagePoints[1].resize(nimages);
objectPoints.resize(nimages);
2010-11-28 20:41:55 +01:00
for( i = 0; i < nimages; i++ )
{
for( j = 0; j < boardSize.height; j++ )
for( k = 0; k < boardSize.width; k++ )
objectPoints[i].push_back(Point3f(j*squareSize, k*squareSize, 0));
}
2010-11-28 20:41:55 +01:00
cout << "Running stereo calibration ...\n";
2010-11-28 20:41:55 +01:00
Mat cameraMatrix[2], distCoeffs[2];
cameraMatrix[0] = Mat::eye(3, 3, CV_64F);
cameraMatrix[1] = Mat::eye(3, 3, CV_64F);
Mat R, T, E, F;
double rms = stereoCalibrate(objectPoints, imagePoints[0], imagePoints[1],
2010-11-28 20:41:55 +01:00
cameraMatrix[0], distCoeffs[0],
cameraMatrix[1], distCoeffs[1],
imageSize, R, T, E, F,
TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, 1e-5),
CV_CALIB_FIX_ASPECT_RATIO +
CV_CALIB_ZERO_TANGENT_DIST +
CV_CALIB_SAME_FOCAL_LENGTH +
CV_CALIB_RATIONAL_MODEL +
CV_CALIB_FIX_K3 + CV_CALIB_FIX_K4 + CV_CALIB_FIX_K5);
cout << "done with RMS error=" << rms << endl;
2010-11-28 00:15:16 +01:00
// CALIBRATION QUALITY CHECK
// because the output fundamental matrix implicitly
// includes all the output information,
// we can check the quality of calibration using the
// epipolar geometry constraint: m2^t*F*m1=0
2010-11-28 20:41:55 +01:00
double err = 0;
int npoints = 0;
vector<Vec3f> lines[2];
for( i = 0; i < nimages; i++ )
2010-11-28 00:15:16 +01:00
{
2010-11-28 20:41:55 +01:00
int npt = (int)imagePoints[0][i].size();
Mat imgpt[2];
for( k = 0; k < 2; k++ )
{
imgpt[k] = Mat(imagePoints[k][i]);
undistortPoints(imgpt[k], imgpt[k], cameraMatrix[k], distCoeffs[k], Mat(), cameraMatrix[k]);
computeCorrespondEpilines(imgpt[k], k+1, F, lines[k]);
}
for( j = 0; j < npt; j++ )
{
double errij = fabs(imagePoints[0][i][j].x*lines[1][j][0] +
imagePoints[0][i][j].y*lines[1][j][1] + lines[1][j][2]) +
fabs(imagePoints[1][i][j].x*lines[0][j][0] +
imagePoints[1][i][j].y*lines[0][j][1] + lines[0][j][2]);
err += errij;
}
npoints += npt;
2010-11-28 00:15:16 +01:00
}
2010-11-28 20:41:55 +01:00
cout << "average reprojection err = " << err/npoints << endl;
2010-11-28 00:15:16 +01:00
// save intrinsic parameters
2010-11-28 20:41:55 +01:00
FileStorage fs("intrinsics.yml", CV_STORAGE_WRITE);
if( fs.isOpened() )
{
fs << "M1" << cameraMatrix[0] << "D1" << distCoeffs[0] <<
"M2" << cameraMatrix[1] << "D2" << distCoeffs[1];
fs.release();
}
else
cout << "Error: can not save the intrinsic parameters\n";
2010-11-28 20:41:55 +01:00
Mat R1, R2, P1, P2, Q;
2010-11-29 14:31:52 +01:00
Rect validRoi[2];
2010-11-28 20:41:55 +01:00
stereoRectify(cameraMatrix[0], distCoeffs[0],
cameraMatrix[1], distCoeffs[1],
imageSize, R, T, R1, R2, P1, P2, Q,
2011-04-18 17:14:32 +02:00
CALIB_ZERO_DISPARITY, 1, imageSize, &validRoi[0], &validRoi[1]);
2010-11-28 20:41:55 +01:00
fs.open("extrinsics.yml", CV_STORAGE_WRITE);
if( fs.isOpened() )
2010-11-28 00:15:16 +01:00
{
2010-11-28 20:41:55 +01:00
fs << "R" << R << "T" << T << "R1" << R1 << "R2" << R2 << "P1" << P1 << "P2" << P2 << "Q" << Q;
fs.release();
}
else
cout << "Error: can not save the intrinsic parameters\n";
2010-11-28 20:41:55 +01:00
// OpenCV can handle left-right
// or up-down camera arrangements
bool isVerticalStereo = fabs(P2.at<double>(1, 3)) > fabs(P2.at<double>(0, 3));
2010-11-29 14:31:52 +01:00
// COMPUTE AND DISPLAY RECTIFICATION
2010-11-28 20:41:55 +01:00
if( !showRectified )
return;
2010-11-28 20:41:55 +01:00
Mat rmap[2][2];
2010-11-28 00:15:16 +01:00
// IF BY CALIBRATED (BOUGUET'S METHOD)
2010-11-29 14:31:52 +01:00
if( useCalibrated )
2010-11-28 20:41:55 +01:00
{
// we already computed everything
}
2010-11-29 14:31:52 +01:00
// OR ELSE HARTLEY'S METHOD
2010-11-28 20:41:55 +01:00
else
// use intrinsic parameters of each camera, but
// compute the rectification transformation directly
// from the fundamental matrix
{
vector<Point2f> allimgpt[2];
for( k = 0; k < 2; k++ )
2010-11-28 00:15:16 +01:00
{
2010-11-28 20:41:55 +01:00
for( i = 0; i < nimages; i++ )
std::copy(imagePoints[k][i].begin(), imagePoints[k][i].end(), back_inserter(allimgpt[k]));
2010-11-28 00:15:16 +01:00
}
2010-11-28 20:41:55 +01:00
F = findFundamentalMat(Mat(allimgpt[0]), Mat(allimgpt[1]), FM_8POINT, 0, 0);
Mat H1, H2;
stereoRectifyUncalibrated(Mat(allimgpt[0]), Mat(allimgpt[1]), F, imageSize, H1, H2, 3);
2010-11-28 20:41:55 +01:00
R1 = cameraMatrix[0].inv()*H1*cameraMatrix[0];
R2 = cameraMatrix[1].inv()*H2*cameraMatrix[1];
2010-11-29 14:31:52 +01:00
P1 = cameraMatrix[0];
P2 = cameraMatrix[1];
2010-11-28 00:15:16 +01:00
}
2010-11-28 20:41:55 +01:00
//Precompute maps for cv::remap()
initUndistortRectifyMap(cameraMatrix[0], distCoeffs[0], R1, P1, imageSize, CV_16SC2, rmap[0][0], rmap[0][1]);
initUndistortRectifyMap(cameraMatrix[1], distCoeffs[1], R2, P2, imageSize, CV_16SC2, rmap[1][0], rmap[1][1]);
2010-11-29 14:31:52 +01:00
Mat canvas;
double sf;
int w, h;
if( !isVerticalStereo )
{
2010-12-04 14:45:58 +01:00
sf = 600./MAX(imageSize.width, imageSize.height);
2010-11-29 14:31:52 +01:00
w = cvRound(imageSize.width*sf);
h = cvRound(imageSize.height*sf);
canvas.create(h, w*2, CV_8UC3);
}
else
{
2010-12-04 14:45:58 +01:00
sf = 300./MAX(imageSize.width, imageSize.height);
2010-11-29 14:31:52 +01:00
w = cvRound(imageSize.width*sf);
h = cvRound(imageSize.height*sf);
canvas.create(h*2, w, CV_8UC3);
}
2010-11-29 14:31:52 +01:00
for( i = 0; i < nimages; i++ )
2010-11-28 20:41:55 +01:00
{
2010-11-29 14:31:52 +01:00
for( k = 0; k < 2; k++ )
{
Mat img = imread(goodImageList[i*2+k], 0), rimg, cimg;
remap(img, rimg, rmap[k][0], rmap[k][1], CV_INTER_LINEAR);
cvtColor(rimg, cimg, CV_GRAY2BGR);
Mat canvasPart = !isVerticalStereo ? canvas(Rect(w*k, 0, w, h)) : canvas(Rect(0, h*k, w, h));
resize(cimg, canvasPart, canvasPart.size(), 0, 0, CV_INTER_AREA);
if( useCalibrated )
{
Rect vroi(cvRound(validRoi[k].x*sf), cvRound(validRoi[k].y*sf),
cvRound(validRoi[k].width*sf), cvRound(validRoi[k].height*sf));
2010-11-29 14:31:52 +01:00
rectangle(canvasPart, vroi, Scalar(0,0,255), 3, 8);
}
}
2010-11-29 14:31:52 +01:00
if( !isVerticalStereo )
for( j = 0; j < canvas.rows; j += 16 )
line(canvas, Point(0, j), Point(canvas.cols, j), Scalar(0, 255, 0), 1, 8);
else
for( j = 0; j < canvas.cols; j += 16 )
line(canvas, Point(j, 0), Point(j, canvas.rows), Scalar(0, 255, 0), 1, 8);
imshow("rectified", canvas);
char c = (char)waitKey();
if( c == 27 || c == 'q' || c == 'Q' )
break;
}
2010-11-28 20:41:55 +01:00
}
2010-11-28 20:41:55 +01:00
static bool readStringList( const string& filename, vector<string>& l )
{
l.resize(0);
FileStorage fs(filename, FileStorage::READ);
if( !fs.isOpened() )
return false;
FileNode n = fs.getFirstTopLevelNode();
if( n.type() != FileNode::SEQ )
return false;
FileNodeIterator it = n.begin(), it_end = n.end();
for( ; it != it_end; ++it )
l.push_back((string)*it);
return true;
}
2010-11-28 00:15:16 +01:00
int main(int argc, char** argv)
{
2010-11-28 20:41:55 +01:00
Size boardSize;
string imagelistfn;
2010-11-29 14:31:52 +01:00
bool showRectified = true;
2010-11-28 20:41:55 +01:00
for( int i = 1; i < argc; i++ )
2010-11-28 00:15:16 +01:00
{
2010-11-28 20:41:55 +01:00
if( string(argv[i]) == "-w" )
2010-11-29 14:31:52 +01:00
{
if( sscanf(argv[++i], "%d", &boardSize.width) != 1 || boardSize.width <= 0 )
{
cout << "invalid board width" << endl;
return print_help();
}
}
2010-11-28 20:41:55 +01:00
else if( string(argv[i]) == "-h" )
2010-11-29 14:31:52 +01:00
{
if( sscanf(argv[++i], "%d", &boardSize.height) != 1 || boardSize.height <= 0 )
{
cout << "invalid board height" << endl;
return print_help();
}
}
else if( string(argv[i]) == "-nr" )
showRectified = false;
2010-11-28 20:41:55 +01:00
else if( string(argv[i]) == "--help" )
return print_help();
else if( argv[i][0] == '-' )
{
cout << "invalid option " << argv[i] << endl;
return 0;
}
else
imagelistfn = argv[i];
}
2010-11-28 20:41:55 +01:00
if( imagelistfn == "" )
{
imagelistfn = "stereo_calib.xml";
boardSize = Size(9, 6);
}
2010-12-04 14:45:58 +01:00
else if( boardSize.width <= 0 || boardSize.height <= 0 )
{
cout << "if you specified XML file with chessboards, you should also specify the board width and height (-w and -h options)" << endl;
2010-12-04 14:45:58 +01:00
return 0;
}
2010-11-28 20:41:55 +01:00
vector<string> imagelist;
bool ok = readStringList(imagelistfn, imagelist);
2010-11-29 14:31:52 +01:00
if(!ok || imagelist.empty())
{
cout << "can not open " << imagelistfn << " or the string list is empty" << endl;
2010-11-28 20:41:55 +01:00
return print_help();
2010-11-29 14:31:52 +01:00
}
2010-11-29 14:31:52 +01:00
StereoCalib(imagelist, boardSize, true, showRectified);
2010-11-28 00:15:16 +01:00
return 0;
}