The functions in this section use the so-called pinhole camera model. That is, a scene view is formed by projecting 3D points into the image plane using a perspective transformation.
or
Where are the coordinates of a 3D point in the world coordinate space, are the coordinates of the projection point in pixels. is called a camera matrix, or a matrix of intrinsic parameters. is a principal point (that is usually at the image center), and are the focal lengths expressed in pixel-related units. Thus, if an image from camera is scaled by some factor, all of these parameters should be scaled (multiplied/divided, respectively) by the same factor. The matrix of intrinsic parameters does not depend on the scene viewed and, once estimated, can be re-used (as long as the focal length is fixed (in case of zoom lens)). The joint rotation-translation matrix is called a matrix of extrinsic parameters. It is used to describe the camera motion around a static scene, or vice versa, rigid motion of an object in front of still camera. That is, translates coordinates of a point to some coordinate system, fixed with respect to the camera. The transformation above is equivalent to the following (when ):
Real lenses usually have some distortion, mostly radial distortion and slight tangential distortion. So, the above model is extended as:
, , , , , are radial distortion coefficients, , are tangential distortion coefficients. Higher-order coefficients are not considered in OpenCV. In the functions below the coefficients are passed or returned as
vector. That is, if the vector contains 4 elements, it means that . The distortion coefficients do not depend on the scene viewed, thus they also belong to the intrinsic camera parameters. And they remain the same regardless of the captured image resolution. That is, if, for example, a camera has been calibrated on images of resolution, absolutely the same distortion coefficients can be used for images of resolution from the same camera (while , , and need to be scaled appropriately).
The functions below use the above model to
Finds the camera intrinsic and extrinsic parameters from several views of a calibration pattern.
Parameters: |
|
---|
The function estimates the intrinsic camera parameters and extrinsic parameters for each of the views. The coordinates of 3D object points and their correspondent 2D projections in each view must be specified. That may be achieved by using an object with known geometry and easily detectable feature points. Such an object is called a calibration rig or calibration pattern, and OpenCV has built-in support for a chessboard as a calibration rig (see FindChessboardCorners ). Currently, initialization of intrinsic parameters (when CV_CALIB_USE_INTRINSIC_GUESS is not set) is only implemented for planar calibration patterns (where z-coordinates of the object points must be all 0’s). 3D calibration rigs can also be used as long as initial cameraMatrix is provided.
The algorithm does the following:
The function returns the final re-projection error. Note: if you’re using a non-square (=non-NxN) grid and findChessboardCorners() for calibration, and calibrateCamera returns bad values (i.e. zero distortion coefficients, an image center very far from , and / or large differences between and (ratios of 10:1 or more)), then you’ve probably used patternSize=cvSize(rows,cols) , but should use patternSize=cvSize(cols,rows) in FindChessboardCorners .
See also: FindChessboardCorners , FindExtrinsicCameraParams2 , initCameraMatrix2D() , StereoCalibrate , Undistort2
Computes some useful camera characteristics from the camera matrix
Parameters: |
|
---|
The function computes various useful camera characteristics from the previously estimated camera matrix.
Combines two rotation-and-shift transformations
Parameters: |
|
---|
The functions compute:
where denotes a rotation vector to rotation matrix transformation, and denotes the inverse transformation, see Rodrigues() .
Also, the functions can compute the derivatives of the output vectors w.r.t the input vectors (see matMulDeriv() ). The functions are used inside stereoCalibrate() but can also be used in your own code where Levenberg-Marquardt or another gradient-based solver is used to optimize a function that contains matrix multiplication.
For points in one image of a stereo pair, computes the corresponding epilines in the other image.
Parameters: |
|
---|
For every point in one of the two images of a stereo-pair the function finds the equation of the corresponding epipolar line in the other image.
From the fundamental matrix definition (see FindFundamentalMat ), line in the second image for the point in the first image (i.e. when whichImage=1 ) is computed as:
and, vice versa, when whichImage=2 , is computed from as:
Line coefficients are defined up to a scale. They are normalized, such that .
Convert points to/from homogeneous coordinates.
Parameters: |
|
---|
The functions convert 2D or 3D points from/to homogeneous coordinates, or simply copy or transpose the array. If the input array dimensionality is larger than the output, each coordinate is divided by the last coordinate:
If the output array dimensionality is larger, an extra 1 is appended to each point. Otherwise, the input array is simply copied (with optional transposition) to the output.
Decomposes the projection matrix into a rotation matrix and a camera matrix.
Parameters: |
|
---|
The function computes a decomposition of a projection matrix into a calibration and a rotation matrix and the position of the camera.
It optionally returns three rotation matrices, one for each axis, and the three Euler angles that could be used in OpenGL.
The function is based on RQDecomp3x3 .
Renders the detected chessboard corners.
Parameters: |
|
---|
The function draws the individual chessboard corners detected as red circles if the board was not found or as colored corners connected with lines if the board was found.
Finds the positions of the internal corners of the chessboard.
Parameters: |
|
---|
The function attempts to determine whether the input image is a view of the chessboard pattern and locate the internal chessboard corners. The function returns a non-zero value if all of the corners have been found and they have been placed in a certain order (row by row, left to right in every row), otherwise, if the function fails to find all the corners or reorder them, it returns 0. For example, a regular chessboard has 8 x 8 squares and 7 x 7 internal corners, that is, points, where the black squares touch each other. The coordinates detected are approximate, and to determine their position more accurately, the user may use the function FindCornerSubPix .
Sample usage of detecting and drawing chessboard corners:
Size patternsize(8,6); //interior number of corners
Mat gray = ....; //source image
vector<Point2f> corners; //this will be filled by the detected corners
//CALIB_CB_FAST_CHECK saves a lot of time on images
//that don't contain any chessboard corners
bool patternfound = findChessboardCorners(gray, patternsize, corners,
CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE
+ CALIB_CB_FAST_CHECK);
if(patternfound)
cornerSubPix(gray, corners, Size(11, 11), Size(-1, -1),
TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1));
drawChessboardCorners(img, patternsize, Mat(corners), patternfound);
Note: the function requires some white space (like a square-thick border, the wider the better) around the board to make the detection more robust in various environment (otherwise if there is no border and the background is dark, the outer black squares could not be segmented properly and so the square grouping and ordering algorithm will fail).
Finds the object pose from the 3D-2D point correspondences
Parameters: |
|
---|
The function estimates the object pose given a set of object points, their corresponding image projections, as well as the camera matrix and the distortion coefficients. This function finds such a pose that minimizes reprojection error, i.e. the sum of squared distances between the observed projections imagePoints and the projected (using ProjectPoints2 ) objectPoints .
Calculates the fundamental matrix from the corresponding points in two images.
Parameters: |
|
---|
The epipolar geometry is described by the following equation:
where is fundamental matrix, and are corresponding points in the first and the second images, respectively.
The function calculates the fundamental matrix using one of four methods listed above and returns the found fundamental matrix . Normally just 1 matrix is found, but in the case of 7-point algorithm the function may return up to 3 solutions ( matrix that stores all 3 matrices sequentially).
The calculated fundamental matrix may be passed further to ComputeCorrespondEpilines that finds the epipolar lines corresponding to the specified points. It can also be passed to StereoRectifyUncalibrated to compute the rectification transformation.
// Example. Estimation of fundamental matrix using RANSAC algorithm
int point_count = 100;
vector<Point2f> points1(point_count);
vector<Point2f> points2(point_count);
// initialize the points here ... */
for( int i = 0; i < point_count; i++ )
{
points1[i] = ...;
points2[i] = ...;
}
Mat fundamental_matrix =
findFundamentalMat(points1, points2, FM_RANSAC, 3, 0.99);
Finds the perspective transformation between two planes.
Parameters: |
|
---|
The functions find and return the perspective transformation between the source and the destination planes:
So that the back-projection error
is minimized. If the parameter method is set to the default value 0, the function uses all the point pairs to compute the initial homography estimate with a simple least-squares scheme.
However, if not all of the point pairs ( , ) fit the rigid perspective transformation (i.e. there are some outliers), this initial estimate will be poor. In this case one can use one of the 2 robust methods. Both methods, RANSAC and LMeDS , try many different random subsets of the corresponding point pairs (of 4 pairs each), estimate the homography matrix using this subset and a simple least-square algorithm and then compute the quality/goodness of the computed homography (which is the number of inliers for RANSAC or the median re-projection error for LMeDs). The best subset is then used to produce the initial estimate of the homography matrix and the mask of inliers/outliers.
Regardless of the method, robust or not, the computed homography matrix is refined further (using inliers only in the case of a robust method) with the Levenberg-Marquardt method in order to reduce the re-projection error even more.
The method RANSAC can handle practically any ratio of outliers, but it needs the threshold to distinguish inliers from outliers. The method LMeDS does not need any threshold, but it works correctly only when there are more than 50 % of inliers. Finally, if you are sure in the computed features, where can be only some small noise present, but no outliers, the default method could be the best choice.
The function is used to find initial intrinsic and extrinsic matrices. Homography matrix is determined up to a scale, thus it is normalized so that .
See also: GetAffineTransform , GetPerspectiveTransform , EstimateRigidMotion , WarpPerspective , PerspectiveTransform
Returns the default new camera matrix
Parameters: |
|
---|
The function returns the camera matrix that is either an exact copy of the input cameraMatrix (when centerPrinicipalPoint=false ), or the modified one (when centerPrincipalPoint =true).
In the latter case the new camera matrix will be:
where and are and elements of cameraMatrix , respectively.
By default, the undistortion functions in OpenCV (see initUndistortRectifyMap , undistort ) do not move the principal point. However, when you work with stereo, it’s important to move the principal points in both views to the same y-coordinate (which is required by most of stereo correspondence algorithms), and maybe to the same x-coordinate too. So you can form the new camera matrix for each view, where the principal points will be at the center.
Returns the new camera matrix based on the free scaling parameter
Parameters: |
|
---|
The function computes and returns the optimal new camera matrix based on the free scaling parameter. By varying this parameter the user may retrieve only sensible pixels alpha=0 , keep all the original image pixels if there is valuable information in the corners alpha=1 , or get something in between. When alpha>0 , the undistortion result will likely have some black pixels corresponding to “virtual” pixels outside of the captured distorted image. The original camera matrix, distortion coefficients, the computed new camera matrix and the newImageSize should be passed to InitUndistortRectifyMap to produce the maps for Remap .
Finds the initial camera matrix from the 3D-2D point correspondences
Parameters: |
|
---|
The function estimates and returns the initial camera matrix for camera calibration process. Currently, the function only supports planar calibration patterns, i.e. patterns where each object point has z-coordinate =0.
Computes the undistortion and rectification transformation map.
Parameters: |
|
---|
The function computes the joint undistortion+rectification transformation and represents the result in the form of maps for Remap . The undistorted image will look like the original, as if it was captured with a camera with camera matrix =newCameraMatrix and zero distortion. In the case of monocular camera newCameraMatrix is usually equal to cameraMatrix , or it can be computed by GetOptimalNewCameraMatrix for a better control over scaling. In the case of stereo camera newCameraMatrix is normally set to P1 or P2 computed by StereoRectify .
Also, this new camera will be oriented differently in the coordinate space, according to R . That, for example, helps to align two heads of a stereo camera so that the epipolar lines on both images become horizontal and have the same y- coordinate (in the case of horizontally aligned stereo camera).
The function actually builds the maps for the inverse mapping algorithm that is used by Remap . That is, for each pixel in the destination (corrected and rectified) image the function computes the corresponding coordinates in the source image (i.e. in the original image from camera). The process is the following:
where are the distortion coefficients.
In the case of a stereo camera this function is called twice, once for each camera head, after StereoRectify , which in its turn is called after StereoCalibrate . But if the stereo camera was not calibrated, it is still possible to compute the rectification transformations directly from the fundamental matrix using StereoRectifyUncalibrated . For each camera the function computes homography H as the rectification transformation in pixel domain, not a rotation matrix R in 3D space. The R can be computed from H as
where the cameraMatrix can be chosen arbitrarily.
Computes partial derivatives of the matrix product w.r.t each multiplied matrix
Parameters: |
|
---|
The function computes the partial derivatives of the elements of the matrix product w.r.t. the elements of each of the two input matrices. The function is used to compute Jacobian matrices in stereoCalibrate() , but can also be used in any other similar optimization function.
Project 3D points on to an image plane.
Parameters: |
|
---|
The function computes projections of 3D points to the image plane given intrinsic and extrinsic camera parameters. Optionally, the function computes jacobians - matrices of partial derivatives of image points coordinates (as functions of all the input parameters) with respect to the particular parameters, intrinsic and/or extrinsic. The jacobians are used during the global optimization in CalibrateCamera2 , FindExtrinsicCameraParams2 and StereoCalibrate . The function itself can also used to compute re-projection error given the current intrinsic and extrinsic parameters.
Note, that by setting rvec=tvec=(0,0,0) , or by setting cameraMatrix to 3x3 identity matrix, or by passing zero distortion coefficients, you can get various useful partial cases of the function, i.e. you can compute the distorted coordinates for a sparse set of points, or apply a perspective transformation (and also compute the derivatives) in the ideal zero-distortion setup etc.
Reprojects disparity image to 3D space.
Parameters: |
|
---|
The function transforms 1-channel disparity map to 3-channel image representing a 3D surface. That is, for each pixel (x,y) and the corresponding disparity d=disparity(x,y) it computes:
The matrix Q can be arbitrary matrix, e.g. the one computed by StereoRectify . To reproject a sparse set of points {(x,y,d),...} to 3D space, use PerspectiveTransform .
Computes the ‘RQ’ decomposition of 3x3 matrices.
Parameters: |
|
---|
The function computes a RQ decomposition using the given rotations. This function is used in DecomposeProjectionMatrix to decompose the left 3x3 submatrix of a projection matrix into a camera and a rotation matrix.
It optionally returns three rotation matrices, one for each axis, and the three Euler angles (as the return value) that could be used in OpenGL.
Converts a rotation matrix to a rotation vector or vice versa.
Parameters: |
|
---|
Inverse transformation can also be done easily, since
A rotation vector is a convenient and most-compact representation of a rotation matrix (since any rotation matrix has just 3 degrees of freedom). The representation is used in the global 3D geometry optimization procedures like CalibrateCamera2 , StereoCalibrate or FindExtrinsicCameraParams2 .
The class for computing stereo correspondence using block matching algorithm.
// Block matching stereo correspondence algorithmclass StereoBM
{
enum { NORMALIZED_RESPONSE = CV_STEREO_BM_NORMALIZED_RESPONSE,
BASIC_PRESET=CV_STEREO_BM_BASIC,
FISH_EYE_PRESET=CV_STEREO_BM_FISH_EYE,
NARROW_PRESET=CV_STEREO_BM_NARROW };
StereoBM();
// the preset is one of ..._PRESET above.
// ndisparities is the size of disparity range,
// in which the optimal disparity at each pixel is searched for.
// SADWindowSize is the size of averaging window used to match pixel blocks
// (larger values mean better robustness to noise, but yield blurry disparity maps)
StereoBM(int preset, int ndisparities=0, int SADWindowSize=21);
// separate initialization function
void init(int preset, int ndisparities=0, int SADWindowSize=21);
// computes the disparity for the two rectified 8-bit single-channel images.
// the disparity will be 16-bit signed (fixed-point) or 32-bit floating-point image of the same size as left.
void operator()( const Mat& left, const Mat& right, Mat& disparity, int disptype=CV_16S );
Ptr<CvStereoBMState> state;
};
The class is a C++ wrapper for and the associated functions. In particular, StereoBM::operator () is the wrapper for FindStereoCorrespondceBM . See the respective descriptions.
The class for computing stereo correspondence using semi-global block matching algorithm.
class StereoSGBM
{
StereoSGBM();
StereoSGBM(int minDisparity, int numDisparities, int SADWindowSize,
int P1=0, int P2=0, int disp12MaxDiff=0,
int preFilterCap=0, int uniquenessRatio=0,
int speckleWindowSize=0, int speckleRange=0,
bool fullDP=false);
virtual ~StereoSGBM();
virtual void operator()(const Mat& left, const Mat& right, Mat& disp);
int minDisparity;
int numberOfDisparities;
int SADWindowSize;
int preFilterCap;
int uniquenessRatio;
int P1, P2;
int speckleWindowSize;
int speckleRange;
int disp12MaxDiff;
bool fullDP;
...
};
The class implements modified H. Hirschmuller algorithm HH08 . The main differences between the implemented algorithm and the original one are:
StereoSGBM constructors
Parameters: |
|
---|
.
Parameters: |
|
---|
The first constructor initializes StereoSGBM with all the default parameters (so actually one will only have to set StereoSGBM::numberOfDisparities at minimum). The second constructor allows you to set each parameter to a custom value.
Computes disparity using SGBM algorithm for a rectified stereo pair
Parameters: |
|
---|
The method executes SGBM algorithm on a rectified stereo pair. See stereo_match.cpp OpenCV sample on how to prepare the images and call the method. Note that the method is not constant, thus you should not use the same StereoSGBM instance from within different threads simultaneously.
Calibrates stereo camera.
Parameters: |
|
---|
The function estimates transformation between the 2 cameras making a stereo pair. If we have a stereo camera, where the relative position and orientation of the 2 cameras is fixed, and if we computed poses of an object relative to the fist camera and to the second camera, (R1, T1) and (R2, T2), respectively (that can be done with FindExtrinsicCameraParams2 ), obviously, those poses will relate to each other, i.e. given ( , ) it should be possible to compute ( , ) - we only need to know the position and orientation of the 2nd camera relative to the 1st camera. That’s what the described function does. It computes ( , ) such that:
Optionally, it computes the essential matrix E:
where are components of the translation vector : . And also the function can compute the fundamental matrix F:
Besides the stereo-related information, the function can also perform full calibration of each of the 2 cameras. However, because of the high dimensionality of the parameter space and noise in the input data the function can diverge from the correct solution. Thus, if intrinsic parameters can be estimated with high accuracy for each of the cameras individually (e.g. using CalibrateCamera2 ), it is recommended to do so and then pass CV_CALIB_FIX_INTRINSIC flag to the function along with the computed intrinsic parameters. Otherwise, if all the parameters are estimated at once, it makes sense to restrict some parameters, e.g. pass CV_CALIB_SAME_FOCAL_LENGTH and CV_CALIB_ZERO_TANGENT_DIST flags, which are usually reasonable assumptions.
Similarly to CalibrateCamera2 , the function minimizes the total re-projection error for all the points in all the available views from both cameras. The function returns the final value of the re-projection error.
Computes rectification transforms for each head of a calibrated stereo camera.
Parameters: |
|
---|
The function computes the rotation matrices for each camera that (virtually) make both camera image planes the same plane. Consequently, that makes all the epipolar lines parallel and thus simplifies the dense stereo correspondence problem. On input the function takes the matrices computed by stereoCalibrate() and on output it gives 2 rotation matrices and also 2 projection matrices in the new coordinates. The 2 cases are distinguished by the function are:
Horizontal stereo, when 1st and 2nd camera views are shifted relative to each other mainly along the x axis (with possible small vertical shift). Then in the rectified images the corresponding epipolar lines in left and right cameras will be horizontal and have the same y-coordinate. P1 and P2 will look as:
where is horizontal shift between the cameras and if CV_CALIB_ZERO_DISPARITY is set.
Vertical stereo, when 1st and 2nd camera views are shifted relative to each other mainly in vertical direction (and probably a bit in the horizontal direction too). Then the epipolar lines in the rectified images will be vertical and have the same x coordinate. P2 and P2 will look as:
where is vertical shift between the cameras and if CALIB_ZERO_DISPARITY is set.
As you can see, the first 3 columns of P1 and P2 will effectively be the new “rectified” camera matrices. The matrices, together with R1 and R2 , can then be passed to InitUndistortRectifyMap to initialize the rectification map for each camera.
Below is the screenshot from stereo_calib.cpp sample. Some red horizontal lines, as you can see, pass through the corresponding image regions, i.e. the images are well rectified (which is what most stereo correspondence algorithms rely on). The green rectangles are roi1 and roi2 - indeed, their interior are all valid pixels.
Computes rectification transform for uncalibrated stereo camera.
Parameters: |
|
---|
The function computes the rectification transformations without knowing intrinsic parameters of the cameras and their relative position in space, hence the suffix “Uncalibrated”. Another related difference from StereoRectify is that the function outputs not the rectification transformations in the object (3D) space, but the planar perspective transformations, encoded by the homography matrices H1 and H2 . The function implements the algorithm Hartley99 .
Note that while the algorithm does not need to know the intrinsic parameters of the cameras, it heavily depends on the epipolar geometry. Therefore, if the camera lenses have significant distortion, it would better be corrected before computing the fundamental matrix and calling this function. For example, distortion coefficients can be estimated for each head of stereo camera separately by using CalibrateCamera2 and then the images can be corrected using Undistort2 , or just the point coordinates can be corrected with UndistortPoints .
Transforms an image to compensate for lens distortion.
Parameters: |
|
---|
The function transforms the image to compensate radial and tangential lens distortion.
The function is simply a combination of InitUndistortRectifyMap (with unity R ) and Remap (with bilinear interpolation). See the former function for details of the transformation being performed.
Those pixels in the destination image, for which there is no correspondent pixels in the source image, are filled with 0’s (black color).
The particular subset of the source image that will be visible in the corrected image can be regulated by newCameraMatrix . You can use GetOptimalNewCameraMatrix to compute the appropriate newCameraMatrix , depending on your requirements.
The camera matrix and the distortion parameters can be determined using CalibrateCamera2 . If the resolution of images is different from the used at the calibration stage, and need to be scaled accordingly, while the distortion coefficients remain the same.
Computes the ideal point coordinates from the observed point coordinates.
Parameters: |
|
---|
The function is similar to Undistort2 and InitUndistortRectifyMap , but it operates on a sparse set of points instead of a raster image. Also the function does some kind of reverse transformation to ProjectPoints2 (in the case of 3D object it will not reconstruct its 3D coordinates, of course; but for a planar object it will, up to a translation vector, if the proper R is specified).
// (u,v) is the input point, (u', v') is the output point
// camera_matrix=[fx 0 cx; 0 fy cy; 0 0 1]
// P=[fx' 0 cx' tx; 0 fy' cy' ty; 0 0 1 tz]
x" = (u - cx)/fx
y" = (v - cy)/fy
(x',y') = undistort(x",y",dist_coeffs)
[X,Y,W]T = R*[x' y' 1]T
x = X/W, y = Y/W
u' = x*fx' + cx'
v' = y*fy' + cy',
where undistort() is approximate iterative algorithm that estimates the normalized original point coordinates out of the normalized distorted point coordinates (“normalized” means that the coordinates do not depend on the camera matrix).
The function can be used both for a stereo camera head or for monocular camera (when R is empty ).