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:
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
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 2D or 3D points from/to homogeneous coordinates, or simply 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.
Initializes a structure containing object information.
Parameters: | points (CvPoint3D32fs) – List of 3D points |
---|
The function allocates memory for the object structure and computes the object inverse matrix.
The preprocessed object data is stored in the structure CvPOSITObject , internal for OpenCV, which means that the user cannot directly access the structure data. The user may only create this structure and pass its pointer to the function.
An object is defined as a set of points given in a coordinate system. The function POSIT computes a vector that begins at a camera-related coordinate system center and ends at the points[0] of the object.
Once the work with a given object is finished, the function ReleasePOSITObject must be called to free memory.
Creates block matching stereo correspondence structure.
Parameters: |
|
---|
The function creates the stereo correspondence structure and initializes it. It is possible to override any of the parameters at any time between the calls to FindStereoCorrespondenceBM .
Creates the state of graph cut-based stereo correspondence algorithm.
Parameters: |
|
---|
The function creates the stereo correspondence structure and initializes it. It is possible to override any of the parameters at any time between the calls to FindStereoCorrespondenceGC .
The structure for block matching stereo correspondence algorithm.
- preFilterType¶
type of the prefilter, CV_STEREO_BM_NORMALIZED_RESPONSE or the default and the recommended CV_STEREO_BM_XSOBEL , int
- preFilterSize¶
~5x5..21x21, int
- preFilterCap¶
up to ~31, int
- SADWindowSize¶
Could be 5x5..21x21 or higher, but with 21x21 or smaller windows the processing speed is much higher, int
- minDisparity¶
minimum disparity (=0), int
- numberOfDisparities¶
maximum disparity - minimum disparity, int
- textureThreshold¶
the textureness threshold. That is, if the sum of absolute values of x-derivatives computed over SADWindowSize by SADWindowSize pixel neighborhood is smaller than the parameter, no disparity is computed at the pixel, int
- uniquenessRatio¶
the minimum margin in percents between the best (minimum) cost function value and the second best value to accept the computed disparity, int
- speckleWindowSize¶
the maximum area of speckles to remove (set to 0 to disable speckle filtering), int
- speckleRange¶
acceptable range of disparity variation in each connected component, int
- trySmallerWindows¶
not used currently (0), int
- roi1, roi2
These are the clipping ROIs for the left and the right images. The function StereoRectify returns the largest rectangles in the left and right images where after the rectification all the pixels are valid. If you copy those rectangles to the CvStereoBMState structure, the stereo correspondence function will automatically clear out the pixels outside of the “valid” disparity rectangle computed by GetValidDisparityROI . Thus you will get more “invalid disparity” pixels than usual, but the remaining pixels are more probable to be valid.
- disp12MaxDiff¶
The maximum allowed difference between the explicitly computed left-to-right disparity map and the implicitly (by ValidateDisparity ) computed right-to-left disparity. If for some pixel the difference is larger than the specified threshold, the disparity at the pixel is invalidated. By default this parameter is set to (-1), which means that the left-right check is not performed.
The block matching stereo correspondence algorithm, by Kurt Konolige, is very fast single-pass stereo matching algorithm that uses sliding sums of absolute differences between pixels in the left image and the pixels in the right image, shifted by some varying amount of pixels (from minDisparity to minDisparity+numberOfDisparities ). On a pair of images WxH the algorithm computes disparity in O(W*H*numberOfDisparities) time. In order to improve quality and readability of the disparity map, the algorithm includes pre-filtering and post-filtering procedures.
Note that the algorithm searches for the corresponding blocks in x direction only. It means that the supplied stereo pair should be rectified. Vertical stereo layout is not directly supported, but in such a case the images could be transposed by user.
The structure for graph cuts-based stereo correspondence algorithm
- Ithreshold¶
threshold for piece-wise linear data cost function (5 by default)
- interactionRadius¶
radius for smoothness cost function (1 by default; means Potts model)
- K, lambda, lambda1, lambda2
parameters for the cost function (usually computed adaptively from the input data)
- occlusionCost¶
10000 by default
- minDisparity
0 by default; see CvStereoBMState
- numberOfDisparities
defined by user; see CvStereoBMState
- maxIters¶
number of iterations; defined by user.
The graph cuts stereo correspondence algorithm, described in Kolmogorov03 (as KZ1 ), is non-realtime stereo correspondence algorithm that usually gives very accurate depth map with well-defined object boundaries. The algorithm represents stereo problem as a sequence of binary optimization problems, each of those is solved using maximum graph flow algorithm. The state structure above should not be allocated and initialized manually; instead, use CreateStereoGCState and then override necessary parameters if needed.
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 .
The function’s counterpart in the C++ API is
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 number of fundamental matrices found (1 or 3) and 0, if no matrix is found . 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.
Finds the perspective transformation between two planes.
Parameters: |
|
---|
The function finds 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
Computes the disparity map using block matching algorithm.
Parameters: |
|
---|
The function cvFindStereoCorrespondenceBM computes disparity map for the input rectified stereo pair. Invalid pixels (for which disparity can not be computed) are set to state->minDisparity - 1 (or to (state->minDisparity-1)*16 in the case of 16-bit fixed-point disparity map)
Computes the disparity map using graph cut-based algorithm.
Parameters: |
|
---|
The function computes disparity maps for the input rectified stereo pair. Note that the left disparity image will contain values in the following range:
or
and for the right disparity image the following will be true:
or
that is, the range for the left disparity image will be inversed, and the pixels for which no good match has been found, will be marked as occlusions.
Here is how the function can be used:
and this is the output left disparity image computed from the well-known Tsukuba stereo pair and multiplied by -16 (because the values in the left disparity images are usually negative):
Returns the new camera matrix based on the free scaling parameter
Parameters: |
|
---|
The function computes 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 an undistortion map.
Parameters: |
|
---|
The function is a simplified variant of InitUndistortRectifyMap where the rectification transformation R is identity matrix and newCameraMatrix=cameraMatrix .
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.
Implements the POSIT algorithm.
Parameters: |
|
---|
The function implements the POSIT algorithm. Image coordinates are given in a camera-related coordinate system. The focal length may be retrieved using the camera calibration functions. At every iteration of the algorithm a new perspective projection of the estimated pose is computed.
Difference norm between two projections is the maximal distance between corresponding points. The parameter criteria.epsilon serves to stop the algorithm if the difference is small.
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 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 .
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.
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 None ).