]> rtime.felk.cvut.cz Git - opencv.git/blob - opencv/doc/cv_calibration_3d.tex
f8b02967c381e37fac5af86d1e59666256f1ddb2
[opencv.git] / opencv / doc / cv_calibration_3d.tex
1 \section{Camera Calibration and 3D Reconstruction}
2
3 The functions in this section use the so-called pinhole camera model. That
4 is, a scene view is formed by projecting 3D points into the image plane
5 using a perspective transformation.
6
7 \[
8 s \; m' = A [R|t] M'
9 \]
10
11 or
12
13 \[
14 s \vecthree{u}{v}{1} = \vecthreethree
15 {f_x}{0}{c_x}
16 {0}{f_y}{c_y}
17 {0}{0}{1}
18 \begin{bmatrix}
19  r_{11} & r_{12} & r_{13} & t_1 \\
20  r_{21} & r_{22} & r_{23} & t_2 \\
21  r_{31} & r_{32} & r_{33} & t_3
22 \end{bmatrix}
23 \begin{bmatrix}X\\Y\\Z\\1 \end{bmatrix}
24 \]
25
26 Where $(X, Y, Z)$ are the coordinates of a 3D point in the world
27 coordinate space, $(u, v)$ are the coordinates of the projection point
28 in pixels. $A$ is called a camera matrix, or a matrix of
29 intrinsic parameters. $(cx, cy)$ is a principal point (that is
30 usually at the image center), and $fx, fy$ are the focal lengths
31 expressed in pixel-related units. Thus, if an image from camera is
32 scaled by some factor, all of these parameters should
33 be scaled (multiplied/divided, respectively) by the same factor. The
34 matrix of intrinsic parameters does not depend on the scene viewed and,
35 once estimated, can be re-used (as long as the focal length is fixed (in
36 case of zoom lens)). The joint rotation-translation matrix $[R|t]$
37 is called a matrix of extrinsic parameters. It is used to describe the
38 camera motion around a static scene, or vice versa, rigid motion of an
39 object in front of still camera. That is, $[R|t]$ translates
40 coordinates of a point $(X, Y, Z)$ to some coordinate system,
41 fixed with respect to the camera. The transformation above is equivalent
42 to the following (when $z \ne 0$):
43
44 \[
45 \begin{array}{l}
46 \vecthree{x}{y}{z} = R \vecthree{X}{Y}{Z} + t\\
47 x' = x/z\\
48 y' = y/z\\
49 u = f_x*x' + c_x\\
50 v = f_y*y' + c_y
51 \end{array}
52 \]
53
54 Real lenses usually have some distortion, mostly
55 radial distortion and slight tangential distortion. So, the above model
56 is extended as:
57
58 \[
59 \begin{array}{l}
60 \vecthree{x}{y}{z} = R \vecthree{X}{Y}{Z} + t\\
61 x' = x/z\\
62 y' = y/z\\
63 x'' = x' (1 + k_1 r^2 + k_2 r^4 + k_3 r^6) + 2 p_1 x' y' + p_2(r^2 + 2 x'^2) \\
64 y'' = y' (1 + k_1 r^2 + k_2 r^4 + k_3 r^6) + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' \\
65 \text{where} \quad r^2 = x'^2 + y'^2 \\
66 u = f_x*x'' + c_x\\
67 v = f_y*y'' + c_y
68 \end{array}
69 \]
70
71 $k_1$, $k_2$, $k_3$ are radial distortion coefficients, $p_1$, $p_2$ are tangential distortion coefficients.
72 Higher-order coefficients are not considered in OpenCV. In the functions below the coefficients are passed or returned as
73 \[ (k_1, k_2, p_1, p_2[, k_3]) \]vector. That is, if the vector contains 4 elements, it means that $k_3=0$.
74 The distortion coefficients do not depend on the scene viewed, thus they also belong to the intrinsic camera parameters.
75 \emph{And they remain the same regardless of the captured image resolution.}
76 That is, if, for example, a camera has been calibrated on images of $320
77 \times 240$ resolution, absolutely the same distortion coefficients can
78 be used for images of $640 \times 480$ resolution from the same camera (while $f_x$,
79 $f_y$, $c_x$ and $c_y$ need to be scaled appropriately).
80
81 The functions below use the above model to
82
83 \begin{itemize}
84  \item Project 3D points to the image plane given intrinsic and extrinsic parameters
85  \item Compute extrinsic parameters given intrinsic parameters, a few 3D points and their projections.
86  \item Estimate intrinsic and extrinsic camera parameters from several views of a known calibration pattern (i.e. every view is described by several 3D-2D point correspondences).
87  \item Estimate the relative position and orientation of the stereo camera "heads" and compute the \emph{rectification} transformation that makes the camera optical axes parallel.
88 \end{itemize}
89
90 \ifCPy
91
92 \cvCPyFunc{CalcImageHomography}
93 Calculates the homography matrix for an oblong planar object (e.g. arm).
94
95 \cvdefC{
96 void cvCalcImageHomography( \par float* line,\par CvPoint3D32f* center,\par float* intrinsic,\par float* homography );
97 }
98 \cvdefPy{CalcImageHomography(line,center)-> (intrinsic,homography)}
99
100 \begin{description}
101 \cvarg{line}{the main object axis direction (vector (dx,dy,dz))}
102 \cvarg{center}{object center ((cx,cy,cz))}
103 \cvarg{intrinsic}{intrinsic camera parameters (3x3 matrix)}
104 \cvarg{homography}{output homography matrix (3x3)}
105 \end{description}
106
107 The function calculates the homography
108 matrix for the initial image transformation from image plane to the
109 plane, defined by a 3D oblong object line (See \_\_Figure 6-10\_\_
110 in the OpenCV Guide 3D Reconstruction Chapter).
111
112 \fi
113
114 \cvfunc{CalibrateCamera2}{calibrateCamera}
115 Finds the camera intrinsic and extrinsic parameters from several views of a calibration pattern.
116
117 \cvdefC{double cvCalibrateCamera2( \par const CvMat* objectPoints,\par const CvMat* imagePoints,\par const CvMat* pointCounts,\par CvSize imageSize,\par CvMat* cameraMatrix,\par CvMat* distCoeffs,\par CvMat* rvecs=NULL,\par CvMat* tvecs=NULL,\par int flags=0 );}
118 \cvdefPy{CalibrateCamera2(objectPoints,imagePoints,pointCounts,imageSize,cameraMatrix,distCoeffs,rvecs,tvecs,flags=0)-> None}
119 \cvdefCpp{double calibrateCamera( const vector<vector<Point3f> >\& objectPoints,\par
120                       const vector<vector<Point2f> >\& imagePoints,\par
121                       Size imageSize,\par
122                       Mat\& cameraMatrix, Mat\& distCoeffs,\par
123                       vector<Mat>\& rvecs, vector<Mat>\& tvecs,\par
124                       int flags=0 );}
125 \begin{description}
126 \ifCPy
127 \cvarg{objectPoints}{The joint matrix of object points - calibration pattern features in the model coordinate space. It is floating-point 3xN or Nx3 1-channel, or 1xN or Nx1 3-channel array, where N is the total number of points in all views.}
128 \cvarg{imagePoints}{The joint matrix of object points projections in the camera views. It is floating-point 2xN or Nx2 1-channel, or 1xN or Nx1 2-channel array, where N is the total number of points in all views}
129 \cvarg{pointCounts}{Integer 1xM or Mx1 vector (where M is the number of calibration pattern views) containing the number of points in each particular view. The sum of vector elements must match the size of \texttt{objectPoints} and \texttt{imagePoints} (=N).}
130 \fi
131 \ifCpp
132 \cvarg{objectPoints}{The vector of vectors of points on the calibration pattern in its coordinate system, one vector per view. If the same calibration pattern is shown in each view and it's fully visible then all the vectors will be the same, although it is possible to use partially occluded patterns, or even different patterns in different views - then the vectors will be different. The points are 3D, but since they are in the pattern coordinate system, then if the rig is planar, it may have sense to put the model to the XY coordinate plane, so that Z-coordinate of each input object point is 0}
133 \cvarg{imagePoints}{The vector of vectors of the object point projections on the calibration pattern views, one vector per a view. The projections must be in the same order as the corresponding object points.}
134 \fi
135 \cvarg{imageSize}{Size of the image, used only to initialize the intrinsic camera matrix}
136 \cvarg{cameraMatrix}{The output 3x3 floating-point camera matrix $A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}$.\newline
137 If \texttt{CV\_CALIB\_USE\_INTRINSIC\_GUESS} and/or \texttt{CV\_CALIB\_FIX\_ASPECT\_RATIO} are specified, some or all of \texttt{fx, fy, cx, cy} must be initialized before calling the function}
138 \cvarg{distCoeffs}{The output \cvCPy{4x1, 1x4,} 5x1 or 1x5 vector of distortion coefficients $(k_1, k_2, p_1, p_2[, k_3])$}.
139 \cvarg{rvecs}{The output \cvCPy{3x\emph{M} or \emph{M}x3 1-channel, or 1x\emph{M} or \emph{M}x1 3-channel array}\cvCpp{vector} of rotation vectors (see \cvCross{Rodrigues2}{Rodrigues}), estimated for each pattern view. That is, each k-th rotation vector together with the corresponding k-th translation vector (see the next output parameter description) brings the calibration pattern from the model coordinate space (in which object points are specified) to the world coordinate space, i.e. real position of the calibration pattern in the k-th pattern view (k=0..\emph{M}-1)}
140 \cvarg{tvecs}{The output \cvCPy{3x\emph{M} or \emph{M}x3 1-channel, or 1x\emph{M} or \emph{M}x1 3-channel array}\cvCpp{vector} of translation vectors, estimated for each pattern view.}
141 \cvarg{flags}{Different flags, may be 0 or combination of the following values:
142 \begin{description}
143 \cvarg{CV\_CALIB\_USE\_INTRINSIC\_GUESS}{\texttt{cameraMatrix} contains the valid initial values of \texttt{fx, fy, cx, cy} that are optimized further. Otherwise, \texttt{(cx, cy)} is initially set to the image center (\texttt{imageSize} is used here), and focal distances are computed in some least-squares fashion. Note, that if intrinsic parameters are known, there is no need to use this function just to estimate the extrinsic parameters. Use \cvCross{FindExtrinsicCameraParams2}{solvePnP} instead.}
144 \cvarg{CV\_CALIB\_FIX\_PRINCIPAL\_POINT}{The principal point is not changed during the global optimization, it stays at the center or at the other location specified when \newline \texttt{CV\_CALIB\_USE\_INTRINSIC\_GUESS} is set too.}
145 \cvarg{CV\_CALIB\_FIX\_ASPECT\_RATIO}{The functions considers only \texttt{fy} as a free parameter, the ratio \texttt{fx/fy} stays the same as in the input \texttt{cameraMatrix}. \newline When \texttt{CV\_CALIB\_USE\_INTRINSIC\_GUESS} is not set, the actual input values of \texttt{fx} and \texttt{fy} are ignored, only their ratio is computed and used further.}
146 \cvarg{CV\_CALIB\_ZERO\_TANGENT\_DIST}{Tangential distortion coefficients $(p_1, p_2)$ will be set to zeros and stay zero.}}
147 \end{description}
148 \end{description}
149
150 The function estimates the intrinsic camera
151 parameters and extrinsic parameters for each of the views. The
152 coordinates of 3D object points and their correspondent 2D projections
153 in each view must be specified. That may be achieved by using an
154 object with known geometry and easily detectable feature points.
155 Such an object is called a calibration rig or calibration pattern,
156 and OpenCV has built-in support for a chessboard as a calibration
157 rig (see \cvCross{FindChessboardCorners}{findChessboardCorners}). Currently, initialization
158 of intrinsic parameters (when \texttt{CV\_CALIB\_USE\_INTRINSIC\_GUESS}
159 is not set) is only implemented for planar calibration patterns
160 (where z-coordinates of the object points must be all 0's). 3D
161 calibration rigs can also be used as long as initial \texttt{cameraMatrix}
162 is provided.
163
164 The algorithm does the following:
165 \begin{enumerate}
166     \item First, it computes the initial intrinsic parameters (the option only available for planar calibration patterns) or reads them from the input parameters. The distortion coefficients are all set to zeros initially (unless some of \texttt{CV\_CALIB\_FIX\_K?} are specified).
167     \item The initial camera pose is estimated as if the intrinsic parameters have been already known. This is done using \cvCross{FindExtrinsicCameraParams2}{solvePnP}
168     \item After that the global Levenberg-Marquardt optimization algorithm is run to minimize the reprojection error, i.e. the total sum of squared distances between the observed feature points \texttt{imagePoints} and the projected (using the current estimates for camera parameters and the poses) object points \texttt{objectPoints}; see \cvCross{ProjectPoints2}{projectPoints}.
169 \end{enumerate}
170
171 \ifPy
172 \else
173 The function returns the final re-projection error.
174 \fi
175
176 Note: if you're using a non-square (=non-NxN) grid and
177 \cvCppCross{findChessboardCorners} for calibration, and \texttt{calibrateCamera} returns
178 bad values (i.e. zero distortion coefficients, an image center very far from
179 $(w/2-0.5,h/2-0.5)$, and / or large differences between $f_x$ and $f_y$ (ratios of
180 10:1 or more)), then you've probably used \texttt{patternSize=cvSize(rows,cols)},
181 but should use \texttt{patternSize=cvSize(cols,rows)} in \cvCross{FindChessboardCorners}{findChessboardCorners}.
182
183 See also: \cvCross{FindChessboardCorners}{findChessboardCorners}, \cvCross{FindExtrinsicCameraParams2}{solvePnP}, \cvCppCross{initCameraMatrix2D}, \cvCross{StereoCalibrate}{stereoCalibrate}, \cvCross{Undistort2}{undistort}
184
185 \ifCpp
186
187 \cvCppFunc{calibrationMatrixValues}
188 Computes some useful camera characteristics from the camera matrix
189
190 \cvdefCpp{void calibrationMatrixValues( const Mat\& cameraMatrix,\par
191                               Size imageSize,\par
192                               double apertureWidth,\par
193                               double apertureHeight,\par
194                               double\& fovx,\par
195                               double\& fovy,\par
196                               double\& focalLength,\par
197                               Point2d\& principalPoint,\par
198                               double\& aspectRatio );}
199 \begin{description}
200 \cvarg{cameraMatrix}{The input camera matrix that can be estimated by \cvCppCross{calibrateCamera} or \cvCppCross{stereoCalibrate}}
201 \cvarg{imageSize}{The input image size in pixels}
202 \cvarg{apertureWidth}{Physical width of the sensor}
203 \cvarg{apertureHeight}{Physical height of the sensor}
204 \cvarg{fovx}{The output field of view in degrees along the horizontal sensor axis}
205 \cvarg{fovy}{The output field of view in degrees along the vertical sensor axis}
206 \cvarg{focalLength}{The focal length of the lens in mm}
207 \cvarg{principalPoint}{The principal point in pixels}
208 \cvarg{aspectRatio}{$f_y/f_x$}
209 \end{description}
210
211 The function computes various useful camera characteristics from the previously estimated camera matrix.
212
213 \cvCppFunc{composeRT}
214 Combines two rotation-and-shift transformations
215
216 \cvdefCpp{void composeRT( const Mat\& rvec1, const Mat\& tvec1,\par
217                 const Mat\& rvec2, const Mat\& tvec2,\par
218                 Mat\& rvec3, Mat\& tvec3 );\newline
219 void composeRT( const Mat\& rvec1, const Mat\& tvec1,\par
220                 const Mat\& rvec2, const Mat\& tvec2,\par
221                 Mat\& rvec3, Mat\& tvec3,\par
222                 Mat\& dr3dr1, Mat\& dr3dt1,\par
223                 Mat\& dr3dr2, Mat\& dr3dt2,\par
224                 Mat\& dt3dr1, Mat\& dt3dt1,\par
225                 Mat\& dt3dr2, Mat\& dt3dt2 );}
226 \begin{description}
227 \cvarg{rvec1}{The first rotation vector}
228 \cvarg{tvec1}{The first translation vector}
229 \cvarg{rvec2}{The second rotation vector}
230 \cvarg{tvec2}{The second translation vector}
231 \cvarg{rvec3}{The output rotation vector of the superposition}
232 \cvarg{tvec3}{The output translation vector of the superposition}
233 \cvarg{d??d??}{The optional output derivatives of \texttt{rvec3} or \texttt{tvec3} w.r.t. \texttt{rvec?} or \texttt{tvec?}}
234 \end{description}
235
236 The functions compute:
237
238 \[ \begin{array}{l}
239 \texttt{rvec3} = \mathrm{rodrigues}^{-1}\left(\mathrm{rodrigues}(\texttt{rvec2}) \cdot
240 \mathrm{rodrigues}(\texttt{rvec1})\right) \\
241 \texttt{tvec3} = \mathrm{rodrigues}(\texttt{rvec2}) \cdot \texttt{tvec1} + \texttt{tvec2}
242 \end{array}, \]
243
244 where $\mathrm{rodrigues}$ denotes a rotation vector to rotation matrix transformation, and $\mathrm{rodrigues}^{-1}$ denotes the inverse transformation, see \cvCppCross{Rodrigues}.
245
246 Also, the functions can compute the derivatives of the output vectors w.r.t the input vectors (see \cvCppCross{matMulDeriv}).
247 The functions are used inside \cvCppCross{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.
248
249 \fi
250
251 \cvfunc{ComputeCorrespondEpilines}{computeCorrespondEpilines}
252 For points in one image of a stereo pair, computes the corresponding epilines in the other image.
253
254 \cvdefC{void cvComputeCorrespondEpilines( \par const CvMat* points,\par int whichImage,\par const CvMat* F, \par CvMat* lines);}
255 \cvdefPy{ComputeCorrespondEpilines(points, whichImage, F, lines) -> None}
256 \cvdefCpp{void computeCorrespondEpilines( const Mat\& points,\par
257                                 int whichImage, const Mat\& F,\par
258                                 vector<Vec3f>\& lines );}
259 \begin{description}
260 \cvCPy{\cvarg{points}{The input points. \texttt{2xN, Nx2, 3xN} or \texttt{Nx3} array (where \texttt{N} number of points). Multi-channel \texttt{1xN} or \texttt{Nx1} array is also acceptable}}
261 \cvCpp{\cvarg{points}{The input points. $N \times 1$ or $1 \times N$ matrix of type \texttt{CV\_32FC2} or \texttt{vector<Point2f>}}}
262 \cvarg{whichImage}{Index of the image (1 or 2) that contains the \texttt{points}}
263 \cvarg{F}{The fundamental matrix that can be estimated using \cvCross{FindFundamentalMat}{findFundamentalMat}
264 or \cvCross{StereoRectify}{stereoRectify}.}
265 \cvarg{lines}{\cvCPy{The output epilines, a \texttt{3xN} or \texttt{Nx3} array.}\cvCpp{The output vector of the corresponding to the points epipolar lines in the other image.} Each line $ax + by + c=0$ is encoded by 3 numbers $(a, b, c)$}
266 \end{description}
267
268 For every point in one of the two images of a stereo-pair the function finds the equation of the
269 corresponding epipolar line in the other image.
270
271 From the fundamental matrix definition (see \cvCross{FindFundamentalMat}{findFundamentalMat}),
272 line $l^{(2)}_i$ in the second image for the point $p^{(1)}_i$ in the first image (i.e. when \texttt{whichImage=1}) is computed as:
273
274 \[ l^{(2)}_i = F p^{(1)}_i \]
275
276 and, vice versa, when \texttt{whichImage=2}, $l^{(1)}_i$ is computed from $p^{(2)}_i$ as:
277
278 \[ l^{(1)}_i = F^T p^{(2)}_i \]
279
280 Line coefficients are defined up to a scale. They are normalized, such that $a_i^2+b_i^2=1$.
281
282
283 \cvfunc{ConvertPointsHomogeneous}{convertPointsHomogeneous}
284 Convert points to/from homogeneous coordinates.
285
286 \cvdefC{void cvConvertPointsHomogeneous( \par const CvMat* src,\par CvMat* dst );}
287
288 \cvdefPy{ConvertPointsHomogeneous( src, dst ) -> None}
289
290 \cvdefCpp{void convertPointsHomogeneous( const Mat\& src, vector<Point3f>\& dst );
291
292 void convertPointsHomogeneous( const Mat\& src, vector<Point2f>\& dst );}
293
294 \begin{description}
295 \ifC
296 \cvarg{src}{The input point array, \texttt{2xN, Nx2, 3xN, Nx3, 4xN or Nx4 (where \texttt{N} is the number of points)}. Multi-channel \texttt{1xN} or \texttt{Nx1} array is also acceptable}
297 \cvarg{dst}{The output point array, must contain the same number of points as the input; The dimensionality must be the same, 1 less or 1 more than the input, and also within 2 to 4}
298 \else
299 \cvarg{src}{The input array or vector of 2D or 3D points}
300 \cvarg{dst}{The output vector of 3D or 2D points, respectively}
301 \fi
302 \end{description}
303
304 The \cvC{function converts}\cvCpp{functions convert} 2D or 3D points from/to homogeneous coordinates, or simply \cvC{copies or transposes}\cvCpp{copy or transpose} the array. If the input array dimensionality is larger than the output, each coordinate is divided by the last coordinate:
305
306 \[
307 \begin{array}{l}
308 (x,y[,z],w) -> (x',y'[,z'])\\
309 \text{where} \\
310 x' = x/w \\
311 y' = y/w \\
312 z' = z/w \quad \text{(if output is 3D)}
313 \end{array}
314 \]
315
316 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.
317
318 \cvC{\textbf{Note} because the function accepts a large variety of array layouts, it may report an error when input/output array dimensionality is ambiguous. It is always safe to use the function with number of points $\texttt{N} \ge 5$, or to use multi-channel \texttt{Nx1} or \texttt{1xN} arrays.}
319
320 \ifCPy
321
322 \cvCPyFunc{CreatePOSITObject}
323 Initializes a structure containing object information.
324
325 \cvdefC{
326 CvPOSITObject* cvCreatePOSITObject( \par CvPoint3D32f* points,\par int point\_count );
327 }\cvdefPy{CreatePOSITObject(points)-> POSITObject}
328
329 \begin{description}
330 \ifC
331 \cvarg{points}{Pointer to the points of the 3D object model}
332 \cvarg{point\_count}{Number of object points}
333 \else
334 \cvarg{points}{List of 3D points}
335 \fi
336 \end{description}
337
338 The function allocates memory for the object structure and computes the object inverse matrix.
339
340 The preprocessed object data is stored in the structure \cvCPyCross{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.
341
342 An object is defined as a set of points given in a coordinate system. The function \cvCPyCross{POSIT} computes a vector that begins at a camera-related coordinate system center and ends at the \texttt{points[0]} of the object.
343
344 Once the work with a given object is finished, the function \cvCPyCross{ReleasePOSITObject} must be called to free memory.
345
346 \cvCPyFunc{CreateStereoBMState}
347 Creates block matching stereo correspondence structure.
348
349 \cvdefC{
350
351 CvStereoBMState* cvCreateStereoBMState( int preset=CV\_STEREO\_BM\_BASIC,
352                                         int numberOfDisparities=0 );
353
354 }
355 \cvdefPy{CreateStereoBMState(preset=CV\_STEREO\_BM\_BASIC,numberOfDisparities=0)-> StereoBMState}
356
357 \begin{description}
358 \cvarg{preset}{ID of one of the pre-defined parameter sets. Any of the parameters can be overridden after creating the structure.  Values are
359 \begin{description}
360 \cvarg{CV_STEREO_BM_BASIC}{Parameters suitable for general cameras}
361 \cvarg{CV_STEREO_BM_FISH_EYE}{Parameters suitable for wide-angle cameras}
362 \cvarg{CV_STEREO_BM_NARROW}{Parameters suitable for narrow-angle cameras}
363 \end{description}
364 }
365 \cvarg{numberOfDisparities}{The number of disparities. If the parameter is 0, it is taken from the preset, otherwise the supplied value overrides the one from preset.}
366 \end{description}
367
368 The function creates the stereo correspondence structure and initializes
369 it. It is possible to override any of the parameters at any time between
370 the calls to \cvCPyCross{FindStereoCorrespondenceBM}.
371
372 \cvCPyFunc{CreateStereoGCState}
373 Creates the state of graph cut-based stereo correspondence algorithm.
374
375 \cvdefC{
376
377 CvStereoGCState* cvCreateStereoGCState( int numberOfDisparities,
378                                         int maxIters );
379
380 }
381 \cvdefPy{CreateStereoGCState(numberOfDisparities,maxIters)-> StereoGCState}
382
383 \begin{description}
384 \cvarg{numberOfDisparities}{The number of disparities. The disparity search range will be $\texttt{state->minDisparity} \le disparity < \texttt{state->minDisparity} + \texttt{state->numberOfDisparities}$}
385 \cvarg{maxIters}{Maximum number of iterations. On each iteration all possible (or reasonable) alpha-expansions are tried. The algorithm may terminate earlier if it could not find an alpha-expansion that decreases the overall cost function value. See \cite{Kolmogorov03}  for details. }
386 \end{description}
387
388 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 \cvCPyCross{FindStereoCorrespondenceGC}.
389
390 \cvclass{CvStereoBMState}
391 The structure for block matching stereo correspondence algorithm.
392
393 \ifC
394 \begin{lstlisting}
395 typedef struct CvStereoBMState
396 {
397     //pre filters (normalize input images):
398     int       preFilterType; // 0 for now
399     int       preFilterSize; // ~5x5..21x21
400     int       preFilterCap;  // up to ~31
401     //correspondence using Sum of Absolute Difference (SAD):
402     int       SADWindowSize; // Could be 5x5..21x21
403     int       minDisparity;  // minimum disparity (=0)
404     int       numberOfDisparities; // maximum disparity - minimum disparity
405     //post filters (knock out bad matches):
406     int       textureThreshold; // areas with no texture are ignored
407     float     uniquenessRatio;// filter out pixels if there are other close matches
408                               // with different disparity
409     int       speckleWindowSize; // the maximum area of speckles to remove
410                                  // (set to 0 to disable speckle filtering)
411     int       speckleRange; // acceptable range of disparity variation in each connected component
412     // internal data
413     ...
414 }
415 CvStereoBMState;
416 \end{lstlisting}
417 \else
418 \begin{description}
419 \cvarg{preFilterType}{0 for now, int}
420 \cvarg{preFilterSize}{~5x5..21x21, int}
421 \cvarg{preFilterCap}{up to ~31, int}
422 \cvarg{SADWindowSize}{Could be 5x5..21x21, int}
423 \cvarg{minDisparity}{minimum disparity (=0), int}
424 \cvarg{numberOfDisparities}{maximum disparity - minimum disparity, int}
425 \cvarg{textureThreshold}{areas with no texture are ignored, int}
426 \cvarg{uniquenessRatio}{filter out pixels if there are other close matches with different disparity, float}
427 \cvarg{speckleWindowSize}{the maximum area of speckles to remove (set to 0 to disable speckle filtering), int}
428 \cvarg{speckleRange}{acceptable range of disparity variation in each connected component, int}
429 \end{description}
430 \fi
431
432 The block matching stereo correspondence algorithm, by Kurt Konolige, is very fast one-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 \texttt{minDisparity} to \texttt{minDisparity+numberOfDisparities}). On a pair of images WxH the algorithm computes disparity in \texttt{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.
433
434 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.
435
436 \cvclass{CvStereoGCState}
437 The structure for graph cuts-based stereo correspondence algorithm
438
439 \ifC
440 \begin{lstlisting}
441 typedef struct CvStereoGCState
442 {
443     int Ithreshold; // threshold for piece-wise linear data cost function (5 by default)
444     int interactionRadius; // radius for smoothness cost function (1 by default; means Potts model)
445     float K, lambda, lambda1, lambda2; // parameters for the cost function
446                                        // (usually computed adaptively from the input data)
447     int occlusionCost; // 10000 by default
448     int minDisparity; // 0 by default; see CvStereoBMState
449     int numberOfDisparities; // defined by user; see CvStereoBMState
450     int maxIters; // number of iterations; defined by user.
451
452     // internal buffers
453     CvMat* left;
454     CvMat* right;
455     CvMat* dispLeft;
456     CvMat* dispRight;
457     CvMat* ptrLeft;
458     CvMat* ptrRight;
459     CvMat* vtxBuf;
460     CvMat* edgeBuf;
461 }
462 CvStereoGCState;
463 \end{lstlisting}
464 \else
465 \begin{description}
466 \cvarg{Ithreshold}{threshold for piece-wise linear data cost function (5 by default)}
467 \cvarg{interactionRadius}{radius for smoothness cost function (1 by default; means Potts model)}
468 \cvarg{K, lambda, lambda1, lambda2}{parameters for the cost function (usually computed adaptively from the input data)}
469 \cvarg{occlusionCost}{10000 by default}
470 \cvarg{minDisparity}{0 by default; see \cross{CvStereoBMState}}
471 \cvarg{numberOfDisparities}{defined by user; see \cross{CvStereoBMState}}
472 \cvarg{maxIters}{number of iterations; defined by user.}
473 \end{description}
474 \fi
475
476 The graph cuts stereo correspondence algorithm, described in \cite{Kolmogorov03} (as \textbf{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 \cvCPyCross{CreateStereoGCState} and then override necessary parameters if needed.
477
478 \fi
479
480 \cvfunc{DecomposeProjectionMatrix}{decomposeProjectionMatrix}
481 Decomposes the projection matrix into a rotation matrix and a camera matrix.
482
483 \cvdefC{
484 void cvDecomposeProjectionMatrix( \par const CvMat *projMatrix,\par CvMat *cameraMatrix,\par CvMat *rotMatrix,\par CvMat *transVect,\par CvMat *rotMatrX=NULL,\par CvMat *rotMatrY=NULL,\par CvMat *rotMatrZ=NULL,\par CvPoint3D64f *eulerAngles=NULL);
485 }
486
487 \cvdefPy{DecomposeProjectionMatrix(projMatrix, cameraMatrix, rotMatrix, transVect, rotMatrX = None, rotMatrY = None, rotMatrZ = None) -> eulerAngles}
488
489 \cvdefCpp{void decomposeProjectionMatrix( const Mat\& projMatrix,\par
490                                 Mat\& cameraMatrix,\par
491                                 Mat\& rotMatrix, Mat\& transVect );\newline
492 void decomposeProjectionMatrix( const Mat\& projMatrix, \par
493                                 Mat\& cameraMatrix,\par
494                                 Mat\& rotMatrix, Mat\& transVect,\par
495                                 Mat\& rotMatrixX, Mat\& rotMatrixY,\par
496                                 Mat\& rotMatrixZ, Vec3d\& eulerAngles );}
497 \begin{description}
498 \cvarg{projMatrix}{The 3x4 input projection matrix P}
499 \cvarg{cameraMatrix}{The output 3x3 camera matrix K}
500 \cvarg{rotMatrix}{The output 3x3 external rotation matrix R}
501 \cvarg{transVect}{The output 4x1 translation vector T}
502 \cvarg{rotMatrX}{Optional 3x3 rotation matrix around x-axis}
503 \cvarg{rotMatrY}{Optional 3x3 rotation matrix around y-axis}
504 \cvarg{rotMatrZ}{Optional 3x3 rotation matrix around z-axis}
505 \cvarg{eulerAngles}{Optional 3 points containing the three Euler angles of rotation}
506 \end{description}
507
508 The function computes a decomposition of a projection matrix into a calibration and a rotation matrix and the position of the camera.
509
510 It optionally returns three rotation matrices, one for each axis, and the three Euler angles that could be used in OpenGL.
511
512 The function is based on \cvCross{RQDecomp3x3}{RQDecomp3x3}.
513
514 \cvfunc{DrawChessboardCorners}{drawChessboardCorners}
515 Renders the detected chessboard corners.
516
517 \cvdefC{
518 void cvDrawChessboardCorners( \par CvArr* image,\par CvSize patternSize,\par CvPoint2D32f* corners,\par int count,\par int patternWasFound );
519 }\cvdefPy{DrawChessboardCorners(image,patternSize,corners,patternWasFound)-> None}
520 \cvdefCpp{void drawChessboardCorners( Mat\& image, Size patternSize,\par
521                             const Mat\& corners,\par
522                             bool patternWasFound );}
523 \begin{description}
524 \cvarg{image}{The destination image; it must be an 8-bit color image}
525 \cvarg{patternSize}{The number of inner corners per chessboard row and column. (patternSize = cvSize(points\_per\_row,points\_per\_colum) = cvSize(columns,rows) )}
526 \cvarg{corners}{The array of corners detected}
527 \cvC{\cvarg{count}{The number of corners}}
528 \cvarg{patternWasFound}{Indicates whether the complete board was found \cvCPy{$(\ne 0)$} or not \cvCPy{$(=0)$}. One may just pass the return value \cvCPyCross{FindChessboardCorners}{findChessboardCorners} here}
529 \end{description}
530
531 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.
532
533 \cvfunc{FindChessboardCorners}{findChessboardCorners}
534 Finds the positions of the internal corners of the chessboard.
535
536 \cvdefC{int cvFindChessboardCorners( \par const void* image,\par CvSize patternSize,\par CvPoint2D32f* corners,\par int* cornerCount=NULL,\par int flags=CV\_CALIB\_CB\_ADAPTIVE\_THRESH );}
537 \cvdefPy{FindChessboardCorners(image, patternSize, flags=CV\_CALIB\_CB\_ADAPTIVE\_THRESH) -> corners}
538 \cvdefCpp{bool findChessboardCorners( const Mat\& image, Size patternSize,\par
539                             vector<Point2f>\& corners,\par
540                             int flags=CV\_CALIB\_CB\_ADAPTIVE\_THRESH+\par
541                                  CV\_CALIB\_CB\_NORMALIZE\_IMAGE );}
542 \begin{description}
543 \cvarg{image}{Source chessboard view; it must be an 8-bit grayscale or color image}
544 \cvarg{patternSize}{The number of inner corners per chessboard row and column
545 ( patternSize = cvSize(points\_per\_row,points\_per\_colum) = cvSize(columns,rows) )}
546 \cvarg{corners}{The output array of corners detected}
547 \cvC{\cvarg{cornerCount}{The output corner counter. If it is not NULL, it stores the number of corners found}}
548 \cvarg{flags}{Various operation flags, can be 0 or a combination of the following values:
549 \begin{description}
550  \cvarg{CV\_CALIB\_CB\_ADAPTIVE\_THRESH}{use adaptive thresholding to convert the image to black and white, rather than a fixed threshold level (computed from the average image brightness).}
551  \cvarg{CV\_CALIB\_CB\_NORMALIZE\_IMAGE}{normalize the image gamma with \cvCross{EqualizeHist}{equalizeHist} before applying fixed or adaptive thresholding.}
552  \cvarg{CV\_CALIB\_CB\_FILTER\_QUADS}{use additional criteria (like contour area, perimeter, square-like shape) to filter out false quads that are extracted at the contour retrieval stage.}
553 \end{description}}
554 \end{description}
555
556 The function attempts to determine
557 whether the input image is a view of the chessboard pattern and
558 locate the internal chessboard corners. The function returns a non-zero
559 value if all of the corners have been found and they have been placed
560 in a certain order (row by row, left to right in every row),
561 otherwise, if the function fails to find all the corners or reorder
562 them, it returns 0. For example, a regular chessboard has 8 x 8
563 squares and 7 x 7 internal corners, that is, points, where the black
564 squares touch each other. The coordinates detected are approximate,
565 and to determine their position more accurately, the user may use
566 the function \cvCross{FindCornerSubPix}{cornerSubPix}.
567
568 \textbf{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).
569
570 \cvfunc{FindExtrinsicCameraParams2}{solvePnP}
571 Finds the object pose from the 3D-2D point correspondences
572
573 \cvdefC{void cvFindExtrinsicCameraParams2( \par const CvMat* objectPoints,\par const CvMat* imagePoints,\par const CvMat* cameraMatrix,\par const CvMat* distCoeffs,\par CvMat* rvec,\par CvMat* tvec );}
574 \cvdefPy{FindExtrinsicCameraParams2(objectPoints,imagePoints,cameraMatrix,distCoeffs,rvec,tvec)-> None}
575 \cvdefCpp{void solvePnP( const Mat\& objectPoints,\par
576                const Mat\& imagePoints,\par
577                const Mat\& cameraMatrix,\par
578                const Mat\& distCoeffs,\par
579                Mat\& rvec, Mat\& tvec,\par
580                bool useExtrinsicGuess=false );}
581 \begin{description}
582 \cvarg{objectPoints}{The array of object points in the object coordinate space, 3xN or Nx3 1-channel, or 1xN or Nx1 3-channel, where N is the number of points. \cvCpp{Can also pass \texttt{vector<Point3f>} here.}}
583 \cvarg{imagePoints}{The array of corresponding image points, 2xN or Nx2 1-channel or 1xN or Nx1 2-channel, where N is the number of points. \cvCpp{Can also pass \texttt{vector<Point2f>} here.}}
584 \cvarg{cameraMatrix}{The input camera matrix $A = \vecthreethree{fx}{0}{cx}{0}{fy}{cy}{0}{0}{1} $}
585 \cvarg{distCoeffs}{The input 4x1, 1x4, 5x1 or 1x5 vector of distortion coefficients $(k_1, k_2, p_1, p_2[, k_3])$. If it is NULL, all of the distortion coefficients are set to 0}
586 \cvarg{rvec}{The output rotation vector (see \cvCross{Rodrigues2}{Rodrigues}) that (together with \texttt{tvec}) brings points from the model coordinate system to the camera coordinate system}
587 \cvarg{tvec}{The output translation vector}
588 \end{description}
589
590 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 \texttt{imagePoints} and the projected (using \cvCross{ProjectPoints2}{projectPoints}) \texttt{objectPoints}.
591
592
593 \cvfunc{FindFundamentalMat}{findFundamentalMat}
594 Calculates the fundamental matrix from the corresponding points in two images.
595
596 \cvdefC{
597 int cvFindFundamentalMat( \par const CvMat* points1,\par const CvMat* points2,\par CvMat* fundamentalMatrix,\par int    method=CV\_FM\_RANSAC,\par double param1=1.,\par double param2=0.99,\par CvMat* status=NULL);
598 }
599 \cvdefPy{FindFundamentalMat(points1, points2, fundamentalMatrix, method=CV\_FM\_RANSAC, param1=1., param2=0.99, status = None) -> None}
600 \cvdefCpp{Mat findFundamentalMat( const Mat\& points1, const Mat\& points2,\par
601                         vector<uchar>\& status, int method=FM\_RANSAC,\par
602                         double param1=3., double param2=0.99 );\newline
603 Mat findFundamentalMat( const Mat\& points1, const Mat\& points2,\par
604                         int method=FM\_RANSAC,\par
605                         double param1=3., double param2=0.99 );}
606 \begin{description}
607 \cvarg{points1}{Array of \texttt{N} points from the first image.\cvCPy{It can be \texttt{2xN, Nx2, 3xN} or \texttt{Nx3} 1-channel array or  \texttt{1xN} or \texttt{Nx1} 2- or 3-channel array}. The point coordinates should be floating-point (single or double precision)}
608 \cvarg{points2}{Array of the second image points of the same size and format as \texttt{points1}}
609 \cvCPy{\cvarg{fundamentalMatrix}{The output fundamental matrix or matrices. The size should be 3x3 or 9x3 (7-point method may return up to 3 matrices)}}
610 \cvarg{method}{Method for computing the fundamental matrix
611 \begin{description}
612   \cvarg{CV\_FM\_7POINT}{for a 7-point algorithm. $N = 7$}
613   \cvarg{CV\_FM\_8POINT}{for an 8-point algorithm. $N \ge 8$}
614   \cvarg{CV\_FM\_RANSAC}{for the RANSAC algorithm. $N \ge 8$}
615   \cvarg{CV\_FM\_LMEDS}{for the LMedS algorithm. $N \ge 8$}
616 \end{description}}
617 \cvarg{param1}{The parameter is used for RANSAC. It is the maximum distance from point to epipolar line in pixels, beyond which the point is considered an outlier and is not used for computing the final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the point localization, image resolution and the image noise}
618 \cvarg{param2}{The parameter is used for RANSAC or LMedS methods only. It specifies the desirable level of confidence (probability) that the estimated matrix is correct}
619 \cvarg{status}{The \cvCPy{optional} output array of N elements, every element of which is set to 0 for outliers and to 1 for the other points. The array is computed only in RANSAC and LMedS methods. For other methods it is set to all 1's}
620 \end{description}
621
622 The epipolar geometry is described by the following equation:
623
624 \[ [p_2; 1]^T F [p_1; 1] = 0 \]
625
626 where $F$ is fundamental matrix, $p_1$ and $p_2$ are corresponding points in the first and the second images, respectively.
627
628 The function calculates the fundamental matrix using one of four methods listed above and returns \cvCpp{the found fundamental matrix}\cvCPy{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 ($9 \times 3$ matrix that stores all 3 matrices sequentially).
629
630 The calculated fundamental matrix may be passed further to
631 \cvCross{ComputeCorrespondEpilines}{computeCorrespondEpilines} that finds the epipolar lines
632 corresponding to the specified points. It can also be passed to \cvCross{StereoRectifyUncalibrated}{stereoRectifyUncalibrated} to compute the rectification transformation.
633
634 \ifC
635 % Example. Estimation of fundamental matrix using RANSAC algorithm
636 \begin{lstlisting}
637 int point_count = 100;
638 CvMat* points1;
639 CvMat* points2;
640 CvMat* status;
641 CvMat* fundamental_matrix;
642
643 points1 = cvCreateMat(1,point_count,CV_32FC2);
644 points2 = cvCreateMat(1,point_count,CV_32FC2);
645 status = cvCreateMat(1,point_count,CV_8UC1);
646
647 /* Fill the points here ... */
648 for( i = 0; i < point_count; i++ )
649 {
650     points1->data.fl[i*2] = <x,,1,i,,>;
651     points1->data.fl[i*2+1] = <y,,1,i,,>;
652     points2->data.fl[i*2] = <x,,2,i,,>;
653     points2->data.fl[i*2+1] = <y,,2,i,,>;
654 }
655
656 fundamental_matrix = cvCreateMat(3,3,CV_32FC1);
657 int fm_count = cvFindFundamentalMat( points1,points2,fundamental_matrix,
658                                      CV_FM_RANSAC,1.0,0.99,status );
659 \end{lstlisting}
660 \fi
661 \ifCpp
662 \begin{lstlisting}
663 // Example. Estimation of fundamental matrix using RANSAC algorithm
664 int point_count = 100;
665 vector<Point2f> points1(point_count);
666 vector<Point2f> points2(point_count);
667
668 // initialize the points here ... */
669 for( int i = 0; i < point_count; i++ )
670 {
671     points1[i] = ...;
672     points2[i] = ...;
673 }
674
675 Mat fundamental_matrix =
676  findFundamentalMat(points1, points2, FM_RANSAC, 3, 0.99);
677 \end{lstlisting}
678 \fi
679
680 \cvfunc{FindHomography}{findHomography}
681 Finds the perspective transformation between two planes.
682
683 \cvdefC{void cvFindHomography( \par const CvMat* srcPoints,\par const CvMat* dstPoints,\par CvMat* H \par
684 int method=0, \par double ransacReprojThreshold=0, \par CvMat* status=NULL);}
685 \cvdefPy{FindHomography(srcPoints,dstPoints,H,method,ransacReprojThreshold=0.0, status=None)-> H}
686 \cvdefCpp{Mat findHomography( const Mat\& srcPoints, const Mat\& dstPoints,\par
687                     Mat\& status, int method=0,\par
688                     double ransacReprojThreshold=0 );\newline
689 Mat findHomography( const Mat\& srcPoints, const Mat\& dstPoints,\par
690                     vector<uchar>\& status, int method=0,\par
691                     double ransacReprojThreshold=0 );\newline
692 Mat findHomography( const Mat\& srcPoints, const Mat\& dstPoints,\par
693                     int method=0, double ransacReprojThreshold=0 );}
694
695 \begin{description}
696
697 \cvCPy{\cvarg{srcPoints}{Coordinates of the points in the original plane, 2xN, Nx2, 3xN or Nx3 1-channel array (the latter two are for representation in homogeneous coordinates), where N is the number of points. 1xN or Nx1 2- or 3-channel array can also be passed.}
698 \cvarg{dstPoints}{Point coordinates in the destination plane, 2xN, Nx2, 3xN or Nx3 1-channel, or 1xN or Nx1 2- or 3-channel array.}}
699 \cvCpp{\cvarg{srcPoints}{Coordinates of the points in the original plane, a matrix of type \texttt{CV\_32FC2} or a \texttt{vector<Point2f>}.}
700 \cvarg{dstPoints}{Coordinates of the points in the target plane, a matrix of type \texttt{CV\_32FC2} or a \texttt{vector<Point2f>}.}}
701
702 \cvCPy{\cvarg{H}{The output 3x3 homography matrix}}
703 \cvarg{method}{ The method used to computed homography matrix; one of the following:
704 \begin{description}
705 \cvarg{0}{a regular method using all the points}
706 \cvarg{CV\_RANSAC}{RANSAC-based robust method}
707 \cvarg{CV\_LMEDS}{Least-Median robust method}
708 \end{description}}
709 \cvarg{ransacReprojThreshold}{The maximum allowed reprojection error to treat a point pair as an inlier (used in the RANSAC method only). That is, if
710 \[\|\texttt{dstPoints}_i - \texttt{convertPointHomogeneous}(\texttt{H} \texttt{srcPoints}_i)\| > \texttt{ransacReprojThreshold}\]
711 then the point $i$ is considered an outlier. If \texttt{srcPoints} and \texttt{dstPoints} are measured in pixels, it usually makes sense to set this parameter somewhere in the range 1 to 10.}
712 \cvarg{status}{The optional output mask set by a robust method (\texttt{CV\_RANSAC} or \texttt{CV\_LMEDS}). \emph{Note that the input mask values are ignored.}}
713 \end{description}
714
715 The \cvCPy{function finds}\cvCpp{functions find and return} the perspective transformation $H$ between the source and the destination planes:
716
717 \[
718 s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}
719 \]
720
721 So that the back-projection error
722
723 \[
724 \sum_i
725 \left( x'_i-\frac{h_{11} x_i + h_{12} y_i + h_{13}}{h_{31} x_i + h_{32} y_i + h_{33}} \right)^2+
726 \left( y'_i-\frac{h_{21} x_i + h_{22} y_i + h_{23}}{h_{31} x_i + h_{32} y_i + h_{33}} \right)^2
727 \]
728
729 is minimized. If the parameter \texttt{method} is set to the default value 0, the function
730 uses all the point pairs to compute the initial homography estimate with a simple least-squares scheme.
731
732 However, if not all of the point pairs ($srcPoints_i$,
733 $dstPoints_i$) fit the rigid perspective transformation (i.e. there
734 are some outliers), this initial estimate will be poor.
735 In this case one can use one of the 2 robust methods. Both methods,
736 \texttt{RANSAC} and \texttt{LMeDS}, try many different random subsets
737 of the corresponding point pairs (of 4 pairs each), estimate
738 the homography matrix using this subset and a simple least-square
739 algorithm and then compute the quality/goodness of the computed homography
740 (which is the number of inliers for RANSAC or the median re-projection
741 error for LMeDs). The best subset is then used to produce the initial
742 estimate of the homography matrix and the mask of inliers/outliers.
743
744 Regardless of the method, robust or not, the computed homography
745 matrix is refined further (using inliers only in the case of a robust
746 method) with the Levenberg-Marquardt method in order to reduce the
747 re-projection error even more.
748
749 The method \texttt{RANSAC} can handle practically any ratio of outliers,
750 but it needs the threshold to distinguish inliers from outliers.
751 The method \texttt{LMeDS} does not need any threshold, but it works
752 correctly only when there are more than 50\% of inliers. Finally,
753 if you are sure in the computed features, where can be only some
754 small noise present, but no outliers, the default method could be the best
755 choice.
756
757 The function is used to find initial intrinsic and extrinsic matrices.
758 Homography matrix is determined up to a scale, thus it is normalized so that
759 $h_{33}=1$.
760
761 See also: \cvCross{GetAffineTransform}{getAffineTransform}, \cvCross{GetPerspectiveTransform}{getPerspectiveTransform}, \cvCross{EstimateRigidMotion}{estimateRigidMotion}, \cvCross{WarpPerspective}{warpPerspective}, \cvCross{PerspectiveTransform}{perspectiveTransform}
762
763 \ifCPy
764
765 \cvCPyFunc{FindStereoCorrespondenceBM}
766 Computes the disparity map using block matching algorithm.
767
768 \cvdefC{
769
770 void cvFindStereoCorrespondenceBM( \par const CvArr* left, \par const CvArr* right,
771                                    \par CvArr* disparity, \par CvStereoBMState* state );
772
773 }\cvdefPy{FindStereoCorrespondenceBM(left,right,disparity,state)-> None}
774
775 \begin{description}
776 \cvarg{left}{The left single-channel, 8-bit image.}
777 \cvarg{right}{The right image of the same size and the same type.}
778 \cvarg{disparity}{The output single-channel 16-bit signed, or 32-bit floating-point disparity map of the same size as input images. In the first case the computed disparities are represented as fixed-point numbers with 4 fractional bits (i.e. the computed disparity values are multiplied by 16 and rounded to integers).}
779 \cvarg{state}{Stereo correspondence structure.}
780 \end{description}
781
782 The function cvFindStereoCorrespondenceBM computes disparity map for the input rectified stereo pair. Invalid pixels (for which disparity can not be computed) are set to \texttt{state->minDisparity - 1} (or to \texttt{(state->minDisparity-1)*16} in the case of 16-bit fixed-point disparity map)
783
784 \cvCPyFunc{FindStereoCorrespondenceGC}
785 Computes the disparity map using graph cut-based algorithm.
786
787 \cvdefC{
788
789 void cvFindStereoCorrespondenceGC( \par const CvArr* left, \par const CvArr* right,
790                                    \par CvArr* dispLeft, \par CvArr* dispRight,
791                                    \par CvStereoGCState* state,
792                                    \par int useDisparityGuess = CV\_DEFAULT(0) );
793
794 }
795 \cvdefPy{FindStereoCorrespondenceGC( left, right, dispLeft, dispRight, state, useDisparityGuess=(0))-> None}
796
797 \begin{description}
798 \cvarg{left}{The left single-channel, 8-bit image.}
799 \cvarg{right}{The right image of the same size and the same type.}
800 \cvarg{dispLeft}{The optional output single-channel 16-bit signed left disparity map of the same size as input images.}
801 \cvarg{dispRight}{The optional output single-channel 16-bit signed right disparity map of the same size as input images.}
802 \cvarg{state}{Stereo correspondence structure.}
803 \cvarg{useDisparityGuess}{If the parameter is not zero, the algorithm will start with pre-defined disparity maps. Both dispLeft and dispRight should be valid disparity maps. Otherwise, the function starts with blank disparity maps (all pixels are marked as occlusions).}
804 \end{description}
805
806 The function computes disparity maps for the input rectified stereo pair. Note that the left disparity image will contain values in the following range: 
807
808 \[
809 -\texttt{state->numberOfDisparities}-\texttt{state->minDisparity}
810 < dispLeft(x,y) \le -\texttt{state->minDisparity},
811 \]
812
813 or
814 \[
815 dispLeft(x,y) == \texttt{CV\_STEREO\_GC\_OCCLUSION}
816 \]
817
818 and for the right disparity image the following will be true: 
819
820 \[
821 \texttt{state->minDisparity} \le dispRight(x,y) 
822 < \texttt{state->minDisparity} + \texttt{state->numberOfDisparities}
823 \]
824
825 or
826
827 \[
828 dispRight(x,y) == \texttt{CV\_STEREO\_GC\_OCCLUSION}
829 \]
830
831 that is, the range for the left disparity image will be inversed,
832 and the pixels for which no good match has been found, will be marked
833 as occlusions.
834
835 Here is how the function can be used:
836
837 \ifC
838 \begin{lstlisting}
839 // image_left and image_right are the input 8-bit single-channel images
840 // from the left and the right cameras, respectively
841 CvSize size = cvGetSize(image_left);
842 CvMat* disparity_left = cvCreateMat( size.height, size.width, CV_16S );
843 CvMat* disparity_right = cvCreateMat( size.height, size.width, CV_16S );
844 CvStereoGCState* state = cvCreateStereoGCState( 16, 2 );
845 cvFindStereoCorrespondenceGC( image_left, image_right,
846     disparity_left, disparity_right, state, 0 );
847 cvReleaseStereoGCState( &state );
848 // now process the computed disparity images as you want ...
849 \end{lstlisting}
850
851 CvMat* disparity_left_visual = cvCreateMat( size.height, size.width, CV_8U );
852 cvConvertScale( disparity_left, disparity_left_visual, -16 );
853 cvSave( "disparity.pgm", disparity_left_visual );
854 \end{lstlisting}
855 \else
856 \lstinputlisting{python_fragments/findstereocorrespondence.py}
857 \fi
858
859 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): 
860
861 \includegraphics{pics/disparity.png}
862
863 \fi
864
865 \ifCpp
866 \cvCppFunc{getDefaultNewCameraMatrix}
867 Returns the default new camera matrix
868
869 \cvdefCpp{Mat getDefaultNewCameraMatrix(\par
870                                const Mat\& cameraMatrix,\par
871                                Size imgSize=Size(),\par
872                                bool centerPrincipalPoint=false );}
873 \begin{description}
874 \cvarg{cameraMatrix}{The input camera matrix}
875 \cvarg{imageSize}{The camera view image size in pixels}
876 \cvarg{centerPrincipalPoint}{Indicates whether in the new camera matrix the principal point should be at the image center or not}
877 \end{description}
878
879 The function returns the camera matrix that is either an exact copy of the input \texttt{cameraMatrix} (when \texttt{centerPrinicipalPoint=false}), or the modified one (when \texttt{centerPrincipalPoint}=true).
880
881 In the latter case the new camera matrix will be:
882
883 \[\begin{bmatrix}
884 f_x && 0 && (\texttt{imgSize.width}-1)*0.5 \\
885 0 && f_y && (\texttt{imgSize.height}-1)*0.5 \\
886 0 && 0 && 1
887 \end{bmatrix},\]
888
889 where $f_x$ and $f_y$ are $(0,0)$ and $(1,1)$ elements of \texttt{cameraMatrix}, respectively.
890
891 By default, the undistortion functions in OpenCV (see \texttt{initUndistortRectifyMap}, \texttt{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.
892
893 \fi
894
895 \cvfunc{GetOptimalNewCameraMatrix}{getOptimalNewCameraMatrix}
896 Returns the new camera matrix based on the free scaling parameter
897
898 \cvdefC{void cvGetOptimalNewCameraMatrix(
899     \par const CvMat* cameraMatrix, const CvMat* distCoeffs,
900     \par CvSize imageSize, double alpha,
901     \par CvMat* newCameraMatrix,
902     \par CvSize newImageSize=cvSize(0,0),
903     \par CvRect* validPixROI=0 );}
904 \cvdefPy{GetOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, alpha, newCameraMatrix, newImageSize=(0,0), validPixROI=0) -> None}
905 \cvdefCpp{Mat getOptimalNewCameraMatrix(
906     \par const Mat\& cameraMatrix, const Mat\& distCoeffs,
907     \par Size imageSize, double alpha, Size newImageSize=Size(),
908     \par Rect* validPixROI=0);}
909     
910 \begin{description}
911 \cvarg{cameraMatrix}{The input camera matrix}
912 \cvarg{distCoeffs}{The input 4x1, 1x4, 5x1 or 1x5 vector of distortion coefficients $(k_1, k_2, p_1, p_2[, k_3])$}.
913 \cvarg{imageSize}{The original image size}
914 \cvarg{alpha}{The free scaling parameter between 0 (when all the pixels in the undistorted image will be valid) and 1 (when all the source image pixels will be retained in the undistorted image); see \cvCross{StereoRectify}{stereoRectify}}
915 \cvarg{newCameraMatrix}{The output new camera matrix.}
916 \cvarg{newImageSize}{The image size after rectification. By default it will be set to \texttt{imageSize}.}
917 \cvarg{validPixROI}{The optional output rectangle that will outline all-good-pixels region in the undistorted image. See \texttt{roi1, roi2} description in \cvCross{StereoRectify}{stereoRectify}}
918 \end{description}
919
920 The function computes \cvCpp{and returns} the optimal new camera matrix based on the free scaling parameter. By varying  this parameter the user may retrieve only sensible pixels \texttt{alpha=0}, keep all the original image pixels if there is valuable information in the corners \texttt{alpha=1}, or get something in between. When \texttt{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 \texttt{newImageSize} should be passed to \cvCross{InitUndistortRectifyMap}{initUndistortRectifyMap} to produce the maps for \cvCross{Remap}{remap}.
921
922 \cvfunc{InitIntrinsicParams2D}{initCameraMatrix2D}
923 Finds the initial camera matrix from the 3D-2D point correspondences
924
925 \cvdefC{void cvInitIntrinsicParams2D(\par const CvMat* objectPoints,
926                                      \par const CvMat* imagePoints,
927                                      \par const CvMat* npoints, CvSize imageSize,
928                                      \par CvMat* cameraMatrix,
929                                      \par double aspectRatio=1.);}                                     
930 \cvdefPy{InitIntrinsicParams2D(objectPoints, imagePoints, npoints, imageSize, cameraMatrix, aspectRatio=1.) -> None}
931 \cvdefCpp{Mat initCameraMatrix2D( const vector<vector<Point3f> >\& objectPoints,\par
932                         const vector<vector<Point2f> >\& imagePoints,\par
933                         Size imageSize, double aspectRatio=1.);}
934 \begin{description}
935 \ifCPy
936 \cvarg{objectPoints}{The joint array of object points; see \cvCross{CalibrateCamera2}{calibrateCamera}}
937 \cvarg{imagePoints}{The joint array of object point projections; see \cvCross{CalibrateCamera2}{calibrateCamera}}
938 \cvarg{npoints}{The array of point counts; see \cvCross{CalibrateCamera2}{calibrateCamera}}
939 \fi    
940 \ifCpp
941 \cvarg{objectPoints}{The vector of vectors of the object points. See \cvCppCross{calibrateCamera}}
942 \cvarg{imagePoints}{The vector of vectors of the corresponding image points. See \cvCppCross{calibrateCamera}}
943 \fi
944 \cvarg{imageSize}{The image size in pixels; used to initialize the principal point}
945 \cvCPy{\cvarg{cameraMatrix}{The output camera matrix $\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}$}}
946 \cvarg{aspectRatio}{If it is zero or negative, both $f_x$ and $f_y$ are estimated independently. Otherwise $f_x = f_y * \texttt{aspectRatio}$}
947 \end{description}
948
949 The function estimates and returns the initial camera matrix for camera calibration process.
950 Currently, the function only supports planar calibration patterns, i.e. patterns where each object point has z-coordinate =0.
951
952 \ifCPy
953 \cvfunc{InitUndistortMap}
954 Computes an undistortion map.
955
956 \cvdefC{void cvInitUndistortMap( \par const CvMat* cameraMatrix,\par const CvMat* distCoeffs,\par CvArr* map1,\par CvArr* map2 );}
957 \cvdefPy{InitUndistortMap(cameraMatrix,distCoeffs,map1,map2)-> None}
958
959 \begin{description}
960 \cvarg{cameraMatrix}{The input camera matrix $A = \vecthreethree{fx}{0}{cx}{0}{fy}{cy}{0}{0}{1} $}
961 \cvarg{distCoeffs}{The input 4x1, 1x4, 5x1 or 1x5 vector of distortion coefficients $(k_1, k_2, p_1, p_2[, k_3])$}.
962 \cvarg{map1}{The first output map \cvCPy{of type \texttt{CV\_32FC1} or \texttt{CV\_16SC2} - the second variant is more efficient}}
963 \cvarg{map2}{The second output map \cvCPy{of type \texttt{CV\_32FC1} or \texttt{CV\_16UC1} - the second variant is more efficient}}
964 \end{description}
965
966 The function is a simplified variant of \cvCross{InitUndistortRectifyMap}{initUndistortRectifyMap} where the rectification transformation \texttt{R} is identity matrix and \texttt{newCameraMatrix=cameraMatrix}.
967
968 \fi
969
970 \cvfunc{InitUndistortRectifyMap}{initUndistortRectifyMap}
971 Computes the undistortion and rectification transformation map.
972
973 \cvdefC{void cvInitUndistortRectifyMap( \par const CvMat* cameraMatrix,
974                                 \par const CvMat* distCoeffs,
975                                 \par const CvMat* R,
976                                 \par const CvMat* newCameraMatrix,
977                                 \par CvArr* map1, \par CvArr* map2 );}
978 \cvdefPy{InitUndistortRectifyMap(cameraMatrix,distCoeffs,R,newCameraMatrix,map1,map2)-> None}
979 \cvdefCpp{void initUndistortRectifyMap( const Mat\& cameraMatrix,\par
980                            const Mat\& distCoeffs, const Mat\& R,\par
981                            const Mat\& newCameraMatrix,\par
982                            Size size, int m1type,\par
983                            Mat\& map1, Mat\& map2 );}
984 \begin{description}
985 \cvarg{cameraMatrix}{The input camera matrix $A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}$}
986 \cvarg{distCoeffs}{The input 4x1, 1x4, 5x1 or 1x5 vector of distortion coefficients $(k_1, k_2, p_1, p_2[, k_3])$}.
987 \cvarg{R}{The optional rectification transformation in object space (3x3 matrix). \texttt{R1} or \texttt{R2}, computed by \cvCross{StereoRectify}{stereoRectify} can be passed here. If the matrix is \cvCPy{NULL}\cvCpp{empty}, the identity transformation is assumed}
988 \cvarg{newCameraMatrix}{The new camera matrix $A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}$}
989 \cvCpp{\cvarg{size}{The undistorted image size}
990 \cvarg{m1type}{The type of the first output map, can be \texttt{CV\_32FC1} or \texttt{CV\_16SC2}. See \cvCppCross{convertMaps}}}
991 \cvarg{map1}{The first output map \cvCPy{of type \texttt{CV\_32FC1} or \texttt{CV\_16SC2} - the second variant is more efficient}}
992 \cvarg{map2}{The second output map \cvCPy{of type \texttt{CV\_32FC1} or \texttt{CV\_16UC1} - the second variant is more efficient}}
993 \end{description}
994
995 The function computes the joint undistortion+rectification transformation and represents the result in the form of maps for \cvCross{Remap}{remap}. The undistorted image will look like the original, as if it was captured with a camera with camera matrix \texttt{=newCameraMatrix} and zero distortion. In the case of monocular camera \texttt{newCameraMatrix} is usually equal to \texttt{cameraMatrix}, or it can be computed by \cvCross{GetOptimalNewCameraMatrix}{getOptimalNewCameraMatrix} for a better control over scaling. In the case of stereo camera \texttt{newCameraMatrix} is normally set to \texttt{P1} or \texttt{P2} computed by \cvCross{StereoRectify}{stereoRectify}.
996
997 Also, this new camera will be oriented differently in the coordinate space, according to \texttt{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).
998
999 The function actually builds the maps for the inverse mapping algorithm that is used by \cvCross{Remap}{remap}. That is, for each pixel $(u, v)$ 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:
1000
1001 \[
1002 \begin{array}{l}
1003 x \leftarrow (u - {c'}_x)/{f'}_x \\
1004 y \leftarrow (v - {c'}_y)/{f'}_y \\
1005 {[X\,Y\,W]}^T \leftarrow R^{-1}*[x\,y\,1]^T \\
1006 x' \leftarrow X/W \\
1007 y' \leftarrow Y/W \\
1008 x" \leftarrow x' (1 + k_1 r^2 + k_2 r^4 + k_3 r^6) + 2p_1 x' y' + p_2(r^2 + 2 x'^2) \\
1009 y" \leftarrow y' (1 + k_1 r^2 + k_2 r^4 + k_3 r^6) + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' \\
1010 map_x(u,v) \leftarrow x" f_x + c_x \\
1011 map_y(u,v) \leftarrow y" f_y + c_y
1012 \end{array}
1013 \]
1014 where $(k_1, k_2, p_1, p_2[, k_3])$ are the distortion coefficients. 
1015  
1016 In the case of a stereo camera this function is called twice, once for each camera head, after \cvCross{StereoRectify}{stereoRectify}, which in its turn is called after \cvCross{StereoCalibrate}{stereoCalibrate}. But if the stereo camera was not calibrated, it is still possible to compute the rectification transformations directly from the fundamental matrix using \cvCross{StereoRectifyUncalibrated}{stereoRectifyUncalibrated}. For each camera the function computes homography \texttt{H} as the rectification transformation in pixel domain, not a rotation matrix \texttt{R} in 3D space. The \texttt{R} can be computed from \texttt{H} as 
1017
1018 \[ \texttt{R} = \texttt{cameraMatrix}^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix} \]
1019
1020 where the \texttt{cameraMatrix} can be chosen arbitrarily.
1021
1022 \ifCpp
1023
1024 \cvCppFunc{matMulDeriv}
1025 Computes partial derivatives of the matrix product w.r.t each multiplied matrix
1026
1027 \cvdefCpp{void matMulDeriv( const Mat\& A, const Mat\& B, Mat\& dABdA, Mat\& dABdB );}
1028 \begin{description}
1029 \cvarg{A}{The first multiplied matrix}
1030 \cvarg{B}{The second multiplied matrix}
1031 \cvarg{dABdA}{The first output derivative matrix \texttt{d(A*B)/dA} of size $\texttt{A.rows*B.cols} \times {A.rows*A.cols}$}
1032 \cvarg{dABdA}{The second output derivative matrix \texttt{d(A*B)/dB} of size $\texttt{A.rows*B.cols} \times {B.rows*B.cols}$}
1033 \end{description}
1034
1035 The function computes the partial derivatives of the elements of the matrix product $A*B$ w.r.t. the elements of each of the two input matrices. The function is used to compute Jacobian matrices in \cvCppCross{stereoCalibrate}, but can also be used in any other similar optimization function.
1036
1037 \fi
1038
1039 \ifCPy
1040
1041 \cvCPyFunc{POSIT}
1042 Implements the POSIT algorithm.
1043
1044 \cvdefC{
1045 void cvPOSIT( \par CvPOSITObject* posit\_object,\par CvPoint2D32f* imagePoints,\par double focal\_length,\par CvTermCriteria criteria,\par CvMatr32f rotationMatrix,\par CvVect32f translation\_vector );
1046 }
1047 \cvdefPy{POSIT(posit\_object,imagePoints,focal\_length,criteria)-> (rotationMatrix,translation\_vector)}
1048
1049 \begin{description}
1050 \cvarg{posit\_object}{Pointer to the object structure}
1051 \cvarg{imagePoints}{Pointer to the object points projections on the 2D image plane}
1052 \cvarg{focal\_length}{Focal length of the camera used}
1053 \cvarg{criteria}{Termination criteria of the iterative POSIT algorithm}
1054 \cvarg{rotationMatrix}{Matrix of rotations}
1055 \cvarg{translation\_vector}{Translation vector}
1056 \end{description}
1057
1058 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.
1059
1060 Difference norm between two projections is the maximal distance between corresponding points. The parameter \texttt{criteria.epsilon} serves to stop the algorithm if the difference is small.
1061
1062 \fi
1063
1064 \cvfunc{ProjectPoints2}{projectPoints}
1065 Project 3D points on to an image plane.
1066
1067 \cvdefC{void cvProjectPoints2( \par const CvMat* objectPoints,\par const CvMat* rvec,\par const CvMat* tvec,\par const CvMat* cameraMatrix,\par const CvMat* distCoeffs,\par CvMat* imagePoints,\par CvMat* dpdrot=NULL,\par CvMat* dpdt=NULL,\par CvMat* dpdf=NULL,\par CvMat* dpdc=NULL,\par CvMat* dpddist=NULL );}
1068
1069 \cvdefPy{ProjectPoints2(objectPoints,rvec,tvec,cameraMatrix,distCoeffs, imagePoints,dpdrot=NULL,dpdt=NULL,dpdf=NULL,dpdc=NULL,dpddist=NULL)-> None}
1070
1071
1072 \cvdefCpp{void projectPoints( const Mat\& objectPoints,\par
1073                     const Mat\& rvec, const Mat\& tvec,\par
1074                     const Mat\& cameraMatrix,\par
1075                     const Mat\& distCoeffs,\par
1076                     vector<Point2f>\& imagePoints );\newline
1077 void projectPoints( const Mat\& objectPoints,\par
1078                     const Mat\& rvec, const Mat\& tvec,\par
1079                     const Mat\& cameraMatrix,\par
1080                     const Mat\& distCoeffs,\par
1081                     vector<Point2f>\& imagePoints,\par
1082                     Mat\& dpdrot, Mat\& dpdt, Mat\& dpdf,\par
1083                     Mat\& dpdc, Mat\& dpddist,\par
1084                     double aspectRatio=0 );}
1085
1086 \begin{description}
1087 \cvarg{objectPoints}{The array of object points, 3xN or Nx3 1-channel or 1xN or Nx1 3-channel \cvCpp{(or \texttt{vector<Point3f>})}, where N is the number of points in the view}
1088 \cvarg{rvec}{The rotation vector, see \cvCross{Rodrigues2}{Rodrigues}}
1089 \cvarg{tvec}{The translation vector}
1090 \cvarg{cameraMatrix}{The camera matrix $A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1} $}
1091 \cvarg{distCoeffs}{The input 4x1, 1x4, 5x1 or 1x5 vector of distortion coefficients $(k_1, k_2, p_1, p_2[, k_3])$. If it is \cvC{NULL}\cvCpp{empty}\cvPy{None}, all of the distortion coefficients are considered 0's}
1092 \cvarg{imagePoints}{The output array of image points, 2xN or Nx2 1-channel or 1xN or Nx1 2-channel \cvCpp{(or \texttt{vector<Point2f>})}}
1093 \cvarg{dpdrot}{Optional 2Nx3 matrix of derivatives of image points with respect to components of the rotation vector}
1094 \cvarg{dpdt}{Optional 2Nx3 matrix of derivatives of image points with respect to components of the translation vector}
1095 \cvarg{dpdf}{Optional 2Nx2 matrix of derivatives of image points with respect to $f_x$ and $f_y$}
1096 \cvarg{dpdc}{Optional 2Nx2 matrix of derivatives of image points with respect to $c_x$ and $c_y$}
1097 \cvarg{dpddist}{Optional 2Nx4 matrix of derivatives of image points with respect to distortion coefficients}
1098 \end{description}
1099
1100 The function computes projections of 3D
1101 points to the image plane given intrinsic and extrinsic camera
1102 parameters. Optionally, the function computes jacobians - matrices
1103 of partial derivatives of image points coordinates (as functions of all the
1104 input parameters) with respect to the particular parameters, intrinsic and/or
1105 extrinsic. The jacobians are used during the global optimization
1106 in \cvCross{CalibrateCamera2}{calibrateCamera},
1107 \cvCross{FindExtrinsicCameraParams2}{solvePnP} and \cvCross{StereoCalibrate}{stereoCalibrate}. The
1108 function itself can also used to compute re-projection error given the
1109 current intrinsic and extrinsic parameters.
1110
1111 Note, that by setting \texttt{rvec=tvec=(0,0,0)}, or by setting \texttt{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.
1112
1113
1114 \cvfunc{ReprojectImageTo3D}{reprojectImageTo3D}
1115 Reprojects disparity image to 3D space.
1116
1117 \cvdefC{void cvReprojectImageTo3D( const CvArr* disparity,\par
1118                                    CvArr* \_3dImage, const CvMat* Q,\par
1119                                    int handleMissingValues=0);}
1120
1121 \cvdefPy{ReprojectImageTo3D(disparity, \_3dImage, Q, handleMissingValues=0) -> None}
1122
1123 \cvdefCpp{void reprojectImageTo3D( const Mat\& disparity,\par
1124                          Mat\& \_3dImage, const Mat\& Q,\par
1125                          bool handleMissingValues=false );}
1126 \begin{description}
1127 \cvarg{disparity}{The input single-channel 16-bit signed or 32-bit floating-point disparity image}
1128 \cvarg{\_3dImage}{The output 3-channel floating-point image of the same size as \texttt{disparity}.
1129  Each element of \texttt{\_3dImage(x,y)} will contain the 3D coordinates of the point \texttt{(x,y)}, computed from the disparity map.}
1130 \cvarg{Q}{The $4 \times 4$ perspective transformation matrix that can be obtained with \cvCross{StereoRectify}{stereoRectify}}
1131 \cvarg{handleMissingValues}{If true, when the pixels with the minimal disparity (that corresponds to the outliers; see \cvCross{FindStereoCorrespondenceBM}{StereoBM}) will be transformed to 3D points with some very large Z value (currently set to 10000)}
1132 \end{description}
1133  
1134 The function transforms 1-channel disparity map to 3-channel image representing a 3D surface. That is, for each pixel \texttt{(x,y)} and the corresponding disparity \texttt{d=disparity(x,y)} it computes: 
1135
1136 \[\begin{array}{l}
1137 [X\; Y\; Z\; W]^T = \texttt{Q}*[x\; y\; \texttt{disparity}(x,y)\; 1]^T \\
1138 \texttt{\_3dImage}(x,y) = (X/W,\; Y/W,\; Z/W)
1139 \end{array}\]
1140
1141 The matrix \texttt{Q} can be arbitrary $4 \times 4$ matrix, e.g. the one computed by \cvCross{StereoRectify}{stereoRectify}. To reproject a sparse set of points {(x,y,d),...} to 3D space, use \cvCross{PerspectiveTransform}{perspectiveTransform}.
1142
1143
1144 \cvfunc{RQDecomp3x3}{RQDecomp3x3}
1145 Computes the 'RQ' decomposition of 3x3 matrices.
1146
1147 \cvdefC{
1148 void cvRQDecomp3x3( \par const CvMat *M,\par CvMat *R,\par CvMat *Q,\par CvMat *Qx=NULL,\par CvMat *Qy=NULL,\par CvMat *Qz=NULL,\par CvPoint3D64f *eulerAngles=NULL);
1149 }
1150 \cvdefPy{RQDecomp3x3(M, R, Q, Qx = None, Qy = None, Qz = None) -> eulerAngles}
1151 \cvdefCpp{void RQDecomp3x3( const Mat\& M, Mat\& R, Mat\& Q );\newline
1152 Vec3d RQDecomp3x3( const Mat\& M, Mat\& R, Mat\& Q,\par
1153                    Mat\& Qx, Mat\& Qy, Mat\& Qz );}
1154
1155 \begin{description}
1156 \cvarg{M}{The 3x3 input matrix}
1157 \cvarg{R}{The output 3x3 upper-triangular matrix}
1158 \cvarg{Q}{The output 3x3 orthogonal matrix}
1159 \cvarg{Qx}{Optional 3x3 rotation matrix around x-axis}
1160 \cvarg{Qy}{Optional 3x3 rotation matrix around y-axis}
1161 \cvarg{Qz}{Optional 3x3 rotation matrix around z-axis}
1162 \cvCPy{\cvarg{eulerAngles}{Optional three Euler angles of rotation}}
1163 \end{description}
1164
1165 The function computes a RQ decomposition using the given rotations. This function is used in \cvCross{DecomposeProjectionMatrix}{decomposeProjectionMatrix} to decompose the left 3x3 submatrix of a projection matrix into a camera and a rotation matrix.
1166
1167 It optionally returns three rotation matrices, one for each axis, and the three Euler angles \cvCpp{(as the return value)} that could be used in OpenGL.
1168
1169 \ifC
1170
1171 \cvCPyFunc{ReleasePOSITObject}
1172 Deallocates a 3D object structure.
1173
1174 \cvdefC{
1175 void cvReleasePOSITObject( \par CvPOSITObject** posit\_object );
1176 }
1177
1178 \begin{description}
1179 \cvarg{posit\_object}{Double pointer to \texttt{CvPOSIT} structure}
1180 \end{description}
1181
1182 The function releases memory previously allocated by the function \cvCPyCross{CreatePOSITObject}.
1183
1184 \fi
1185
1186 \ifC
1187
1188 \cvCPyFunc{ReleaseStereoBMState}
1189 Releases block matching stereo correspondence structure.
1190
1191 \cvdefC{void cvReleaseStereoBMState( CvStereoBMState** state );}
1192 \cvdefPy{ReleaseStereoBMState(state)-> None}
1193
1194 \begin{description}
1195 \cvarg{state}{Double pointer to the released structure.}
1196 \end{description}
1197
1198 The function releases the stereo correspondence structure and all the associated internal buffers. 
1199
1200 \cvCPyFunc{ReleaseStereoGCState}
1201 Releases the state structure of the graph cut-based stereo correspondence algorithm.
1202
1203 \cvdefC{void cvReleaseStereoGCState( CvStereoGCState** state );}
1204 \cvdefPy{ReleaseStereoGCState(state)-> None}
1205
1206 \begin{description}
1207 \cvarg{state}{Double pointer to the released structure.}
1208 \end{description}
1209
1210 The function releases the stereo correspondence structure and all the associated internal buffers. 
1211
1212 \fi
1213
1214 \cvfunc{Rodrigues2}{Rodrigues}
1215 Converts a rotation matrix to a rotation vector or vice versa.
1216
1217 \cvdefC{int cvRodrigues2( \par const CvMat* src,\par CvMat* dst,\par CvMat* jacobian=0 );}
1218 \cvdefPy{Rodrigues2(src,dst,jacobian=0)-> None}
1219
1220 \cvdefCpp{void Rodrigues(const Mat\& src, Mat\& dst);\newline
1221 void Rodrigues(const Mat\& src, Mat\& dst, Mat\& jacobian);}
1222
1223 \begin{description}
1224 \cvarg{src}{The input rotation vector (3x1 or 1x3) or rotation matrix (3x3)}
1225 \cvarg{dst}{The output rotation matrix (3x3) or rotation vector (3x1 or 1x3), respectively}
1226 \cvarg{jacobian}{Optional output Jacobian matrix, 3x9 or 9x3 - partial derivatives of the output array components with respect to the input array components}
1227 \end{description}
1228
1229 \[
1230 \begin{array}{l}
1231 \theta \leftarrow norm(r)\\
1232 r \leftarrow r/\theta\\
1233 R = \cos{\theta} I + (1-\cos{\theta}) r r^T + \sin{\theta}
1234 \vecthreethree
1235 {0}{-r_z}{r_y}
1236 {r_z}{0}{-r_x}
1237 {-r_y}{r_x}{0}
1238 \end{array}
1239 \]
1240
1241 Inverse transformation can also be done easily, since
1242
1243 \[
1244 \sin(\theta)
1245 \vecthreethree
1246 {0}{-r_z}{r_y}
1247 {r_z}{0}{-r_x}
1248 {-r_y}{r_x}{0}
1249 =
1250 \frac{R - R^T}{2}
1251 \]
1252
1253 A rotation vector is a convenient and most-compact representation of a rotation matrix
1254 (since any rotation matrix has just 3 degrees of freedom). The representation is
1255 used in the global 3D geometry optimization procedures like \cvCross{CalibrateCamera2}{calibrateCamera},
1256 \cvCross{StereoCalibrate}{stereoCalibrate} or \cvCross{FindExtrinsicCameraParams2}{solvePnP}.
1257
1258
1259 \ifCpp
1260
1261 \cvclass{StereoBM}
1262 The class for computing stereo correspondence using block matching algorithm.
1263
1264 \begin{lstlisting}
1265 // Block matching stereo correspondence algorithm\par
1266 class StereoBM
1267 {
1268     enum { NORMALIZED_RESPONSE = CV_STEREO_BM_NORMALIZED_RESPONSE,
1269         BASIC_PRESET=CV_STEREO_BM_BASIC,
1270         FISH_EYE_PRESET=CV_STEREO_BM_FISH_EYE,
1271         NARROW_PRESET=CV_STEREO_BM_NARROW };
1272
1273     StereoBM();
1274     // the preset is one of ..._PRESET above.
1275     // ndisparities is the size of disparity range,
1276     // in which the optimal disparity at each pixel is searched for.
1277     // SADWindowSize is the size of averaging window used to match pixel blocks
1278     //    (larger values mean better robustness to noise, but yield blurry disparity maps)
1279     StereoBM(int preset, int ndisparities=0, int SADWindowSize=21);
1280     // separate initialization function
1281     void init(int preset, int ndisparities=0, int SADWindowSize=21);
1282     // computes the disparity for the two rectified 8-bit single-channel images.
1283     // the disparity will be 16-bit signed (fixed-point) or 32-bit floating-point image of the same size as left.
1284     void operator()( const Mat& left, const Mat& right, Mat& disparity, int disptype=CV_16S );
1285
1286     Ptr<CvStereoBMState> state;
1287 };
1288 \end{lstlisting}
1289
1290 \fi
1291
1292 \cvfunc{StereoCalibrate}{stereoCalibrate}
1293 Calibrates stereo camera.
1294
1295 \cvdefC{double cvStereoCalibrate( \par const CvMat* objectPoints, \par const CvMat* imagePoints1,
1296                         \par const CvMat* imagePoints2, \par const CvMat* pointCounts,
1297                         \par CvMat* cameraMatrix1, \par CvMat* distCoeffs1,
1298                         \par CvMat* cameraMatrix2, \par CvMat* distCoeffs2,
1299                        \par CvSize imageSize, \par CvMat* R, \par CvMat* T,
1300                         \par CvMat* E=0, \par CvMat* F=0,
1301                         \par CvTermCriteria term\_crit=cvTermCriteria(
1302                                \par CV\_TERMCRIT\_ITER+CV\_TERMCRIT\_EPS,30,1e-6),
1303                         \par int flags=CV\_CALIB\_FIX\_INTRINSIC );}
1304
1305 \cvdefPy{StereoCalibrate( objectPoints, imagePoints1, imagePoints2, pointCounts, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, imageSize, R, T, E=NULL, F=NULL, term\_crit=(CV\_TERMCRIT\_ITER+CV\_TERMCRIT\_EPS,30,1e-6), flags=CV\_CALIB\_FIX\_INTRINSIC)-> None}
1306
1307 \cvdefCpp{double stereoCalibrate( const vector<vector<Point3f> >\& objectPoints,\par
1308                       const vector<vector<Point2f> >\& imagePoints1,\par
1309                       const vector<vector<Point2f> >\& imagePoints2,\par
1310                       Mat\& cameraMatrix1, Mat\& distCoeffs1,\par
1311                       Mat\& cameraMatrix2, Mat\& distCoeffs2,\par
1312                       Size imageSize, Mat\& R, Mat\& T,\par
1313                       Mat\& E, Mat\& F,\par
1314                       TermCriteria term\_crit = TermCriteria(TermCriteria::COUNT+\par
1315                          TermCriteria::EPS, 30, 1e-6),\par
1316                       int flags=CALIB\_FIX\_INTRINSIC );}
1317
1318 \begin{description}
1319 \ifCPy
1320     \cvarg{objectPoints}{The joint matrix of object points - calibration pattern features in the model coordinate space. It is floating-point 3xN or Nx3 1-channel, or 1xN or Nx1 3-channel array, where N is the total number of points in all views.}
1321     \cvarg{imagePoints1}{The joint matrix of object points projections in the first camera views. It is floating-point 2xN or Nx2 1-channel, or 1xN or Nx1 2-channel array, where N is the total number of points in all views}
1322     \cvarg{imagePoints2}{The joint matrix of object points projections in the second camera views. It is floating-point 2xN or Nx2 1-channel, or 1xN or Nx1 2-channel array, where N is the total number of points in all views}
1323     \cvarg{pointCounts}{Integer 1xM or Mx1 vector (where M is the number of calibration pattern views) containing the number of points in each particular view. The sum of vector elements must match the size of \texttt{objectPoints} and \texttt{imagePoints*} (=N).}
1324 \fi
1325 \ifCpp
1326     \cvarg{objectPoints}{The vector of vectors of points on the calibration pattern in its coordinate system, one vector per view. If the same calibration pattern is shown in each view and it's fully visible then all the vectors will be the same, although it is possible to use partially occluded patterns, or even different patterns in different views - then the vectors will be different. The points are 3D, but since they are in the pattern coordinate system, then if the rig is planar, it may have sense to put the model to the XY coordinate plane, so that Z-coordinate of each input object point is 0}
1327     \cvarg{imagePoints1}{The vector of vectors of the object point projections on the calibration pattern views from the 1st camera, one vector per a view. The projections must be in the same order as the corresponding object points.}
1328     \cvarg{imagePoints2}{The vector of vectors of the object point projections on the calibration pattern views from the 2nd camera, one vector per a view. The projections must be in the same order as the corresponding object points.}
1329 \fi
1330     \cvarg{cameraMatrix1}{The input/output first camera matrix: $ \vecthreethree{f_x^{(j)}}{0}{c_x^{(j)}}{0}{f_y^{(j)}}{c_y^{(j)}}{0}{0}{1}$, $j = 0,\, 1$. If any of \texttt{CV\_CALIB\_USE\_INTRINSIC\_GUESS}, \newline \texttt{CV\_CALIB\_FIX\_ASPECT\_RATIO}, \texttt{CV\_CALIB\_FIX\_INTRINSIC} or \texttt{CV\_CALIB\_FIX\_FOCAL\_LENGTH} are specified, some or all of the matrices' components must be initialized; see the flags description}
1331     \cvarg{distCoeffs1}{The input/output lens distortion coefficients for the first camera, 4x1, 5x1, 1x4 or 1x5 floating-point vectors $(k_1^{(j)}, k_2^{(j)}, p_1^{(j)}, p_2^{(j)}[, k_3^{(j)}])$, $j = 0,\, 1$. If any of \texttt{CV\_CALIB\_FIX\_K1}, \texttt{CV\_CALIB\_FIX\_K2} or \texttt{CV\_CALIB\_FIX\_K3} is specified, then the corresponding elements of the distortion coefficients must be initialized.}    
1332     \cvarg{cameraMatrix2}{The input/output second camera matrix, as cameraMatrix1.}
1333     \cvarg{distCoeffs2}{The input/output lens distortion coefficients for the second camera, as distCoeffs1.}
1334 \cvarg{imageSize}{Size of the image, used only to initialize intrinsic camera matrix.} 
1335 \cvarg{R}{The output rotation matrix between the 1st and the 2nd cameras' coordinate systems.}
1336 \cvarg{T}{The output translation vector between the cameras' coordinate systems.}
1337 \cvarg{E}{The \cvCPy{optional} output essential matrix.}
1338 \cvarg{F}{The \cvCPy{optional} output fundamental matrix.}
1339 \cvarg{term\_crit}{The termination criteria for the iterative optimization algorithm.}
1340 \cvarg{flags}{Different flags, may be 0 or combination of the following values:
1341 \begin{description}
1342 \cvarg{CV\_CALIB\_FIX\_INTRINSIC}{If it is set, \texttt{cameraMatrix?}, as well as \texttt{distCoeffs?} are fixed, so that only \texttt{R, T, E} and \texttt{F} are estimated.}
1343 \cvarg{CV\_CALIB\_USE\_INTRINSIC\_GUESS}{The flag allows the function to optimize some or all of the intrinsic parameters, depending on the other flags, but the initial values are provided by the user.}
1344 \cvarg{CV\_CALIB\_FIX\_PRINCIPAL\_POINT}{The principal points are fixed during the optimization.}
1345 \cvarg{CV\_CALIB\_FIX\_FOCAL\_LENGTH}{$f^{(j)}_x$ and $f^{(j)}_y$ are fixed.}
1346 \cvarg{CV\_CALIB\_FIX\_ASPECT\_RATIO}{$f^{(j)}_y$ is optimized, but the ratio $f^{(j)}_x/f^{(j)}_y$ is fixed.}
1347 \cvarg{CV\_CALIB\_SAME\_FOCAL\_LENGTH}{Enforces $f^{(0)}_x=f^{(1)}_x$ and $f^{(0)}_y=f^{(1)}_y$} \cvarg{CV\_CALIB\_ZERO\_TANGENT\_DIST}{Tangential distortion coefficients for each camera are set to zeros and fixed there.}
1348 \cvarg{CV\_CALIB\_FIX\_K1, CV\_CALIB\_FIX\_K2, CV\_CALIB\_FIX\_K3}{Fixes the corresponding radial distortion coefficient (the coefficient must be passed to the function)}
1349 \end{description}}
1350 \end{description}
1351
1352 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 \cvCross{FindExtrinsicCameraParams2}{solvePnP}), obviously, those poses will relate to each other, i.e. given ($R_1$, $T_1$) it should be possible to compute ($R_2$, $T_2$) - 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 ($R$, $T$) such that:
1353
1354 \[
1355 R_2=R*R_1
1356 T_2=R*T_1 + T,
1357 \]
1358
1359 Optionally, it computes the essential matrix E:
1360
1361 \[
1362 E=
1363 \vecthreethree
1364 {0}{-T_2}{T_1}
1365 {T_2}{0}{-T_0}
1366 {-T_1}{T_0}{0}
1367 *R
1368 \]
1369
1370 where $T_i$ are components of the translation vector $T$: $T=[T_0, T_1, T_2]^T$. And also the function can compute the fundamental matrix F:
1371
1372 \[F = cameraMatrix2^{-T} E cameraMatrix1^{-1}\]
1373
1374 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 \cvCross{CalibrateCamera2}{calibrateCamera}), it is recommended to do so and then pass \texttt{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 \texttt{CV\_CALIB\_SAME\_FOCAL\_LENGTH} and \texttt{CV\_CALIB\_ZERO\_TANGENT\_DIST} flags, which are usually reasonable assumptions.
1375
1376 Similarly to \cvCross{CalibrateCamera2}{calibrateCamera}, the function minimizes the total re-projection error for all the points in all the available views from both cameras.
1377 \ifPy
1378 \else
1379 The function returns the final value of the re-projection error.
1380 \fi
1381
1382 \cvfunc{StereoRectify}{stereoRectify}
1383 Computes rectification transforms for each head of a calibrated stereo camera.
1384
1385 \cvdefC{void cvStereoRectify( \par const CvMat* cameraMatrix1, const CvMat* cameraMatrix2,
1386                       \par const CvMat* distCoeffs1, const CvMat* distCoeffs2,
1387                       \par CvSize imageSize, const CvMat* R, const CvMat* T,
1388                       \par CvMat* R1, CvMat* R2, CvMat* P1, CvMat* P2,
1389                       \par CvMat* Q=0, int flags=CV\_CALIB\_ZERO\_DISPARITY,
1390                       \par double alpha=-1, CvSize newImageSize=cvSize(0,0),
1391                       \par CvRect* roi1=0, CvRect* roi2=0);}
1392 \cvdefPy{StereoRectify( cameraMatrix1, cameraMatrix2, distCoeffs1, distCoeffs2, imageSize, R, T, R1, R2, P1, P2, Q=NULL, flags=CV\_CALIB\_ZERO\_DISPARITY, alpha=-1, newImageSize=(0,0))-> (roi1, roi2)}
1393
1394 \cvdefCpp{void stereoRectify( const Mat\& cameraMatrix1, const Mat\& distCoeffs1,\par
1395                     const Mat\& cameraMatrix2, const Mat\& distCoeffs2,\par
1396                     Size imageSize, const Mat\& R, const Mat\& T,\par
1397                     Mat\& R1, Mat\& R2, Mat\& P1, Mat\& P2, Mat\& Q,\par
1398                     int flags=CALIB\_ZERO\_DISPARITY );\newline
1399 void stereoRectify( const Mat\& cameraMatrix1, const Mat\& distCoeffs1,\par
1400                     const Mat\& cameraMatrix2, const Mat\& distCoeffs2,\par
1401                     Size imageSize, const Mat\& R, const Mat\& T,\par
1402                     Mat\& R1, Mat\& R2, Mat\& P1, Mat\& P2, Mat\& Q,\par
1403                     double alpha, Size newImageSize=Size(),\par
1404                     Rect* roi1=0, Rect* roi2=0,\par
1405                     int flags=CALIB\_ZERO\_DISPARITY );}
1406 \begin{description}
1407 \cvarg{cameraMatrix1, cameraMatrix2}{The camera matrices $\vecthreethree{f_x^{(j)}}{0}{c_x^{(j)}}{0}{f_y^{(j)}}{c_y^{(j)}}{0}{0}{1}$.}
1408 \cvarg{distCoeffs1, distCoeffs2}{The input distortion coefficients for each camera, ${k_1}^{(j)}, {k_2}^{(j)}, {p_1}^{(j)}, {p_2}^{(j)} [, {k_3}^{(j)}]$}
1409 \cvarg{imageSize}{Size of the image used for stereo calibration.}
1410 \cvarg{R}{The rotation matrix between the 1st and the 2nd cameras' coordinate systems.}
1411 \cvarg{T}{The translation vector between the cameras' coordinate systems.}
1412 \cvarg{R1, R2}{The output $3 \times 3$ rectification transforms (rotation matrices) for the first and the second cameras, respectively.}
1413 \cvarg{P1, P2}{The output $3 \times 4$ projection matrices in the new (rectified) coordinate systems.}
1414 \cvarg{Q}{The output $4 \times 4$ disparity-to-depth mapping matrix, see \cvCppCross{reprojectImageTo3D}.}
1415 \cvarg{flags}{The operation flags; may be 0 or \texttt{CV\_CALIB\_ZERO\_DISPARITY}. If the flag is set, the function makes the principal points of each camera have the same pixel coordinates in the rectified views. And if the flag is not set, the function may still shift the images in horizontal or vertical direction (depending on the orientation of epipolar lines) in order to maximize the useful image area.}
1416 \cvarg{alpha}{The free scaling parameter. If it is -1\cvCpp{ or absent}, the functions performs some default scaling. Otherwise the parameter should be between 0 and 1. \texttt{alpha=0} means that the rectified images will be zoomed and shifted so that only valid pixels are visible (i.e. there will be no black areas after rectification). \texttt{alpha=1} means that the rectified image will be decimated and shifted so that all the pixels from the original images from the cameras are retained in the rectified images, i.e. no source image pixels are lost. Obviously, any intermediate value yields some intermediate result between those two extreme cases.}
1417 \cvarg{newImageSize}{The new image resolution after rectification. The same size should be passed to \cvCross{InitUndistortRectifyMap}{initUndistortRectifyMap}, see the \texttt{stereo\_calib.cpp} sample in OpenCV samples directory. By default, i.e. when (0,0) is passed, it is set to the original \texttt{imageSize}. Setting it to larger value can help you to preserve details in the original image, especially when there is big radial distortion.}
1418 \cvarg{roi1, roi2}{The optional output rectangles inside the rectified images where all the pixels are valid. If \texttt{alpha=0}, the ROIs will cover the whole images, otherwise they likely be smaller, see the picture below}
1419 \end{description}
1420
1421 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 \cvCppCross{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: 
1422
1423 \begin{enumerate}
1424 \item 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: 
1425
1426 \[\texttt{P1}=
1427 \begin{bmatrix}
1428 f & 0 & cx_1 & 0\\
1429 0 & f & cy & 0\\
1430 0 & 0 & 1 & 0
1431 \end{bmatrix}
1432 \]
1433 \[\texttt{P2}=
1434 \begin{bmatrix}
1435 f & 0 & cx_2 & T_x*f\\
1436 0 & f & cy & 0\\
1437 0 & 0 & 1 & 0
1438 \end{bmatrix}
1439 ,
1440 \]
1441
1442 where $T_x$ is horizontal shift between the cameras and $cx_1=cx_2$ if \texttt{CV\_CALIB\_ZERO\_DISPARITY} is set.
1443 \item 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:
1444
1445 \[
1446 \texttt{P1}=
1447 \begin{bmatrix}
1448 f & 0 & cx & 0\\
1449 0 & f & cy_1 & 0\\
1450 0 & 0 & 1 & 0
1451 \end{bmatrix}
1452 \]
1453 \[
1454 \texttt{P2}=
1455 \begin{bmatrix}
1456 f & 0 & cx & 0\\
1457 0 & f & cy_2 & T_y*f\\
1458 0 & 0 & 1 & 0
1459 \end{bmatrix}
1460 ,
1461 \]
1462
1463 where $T_y$ is vertical shift between the cameras and $cy_1=cy_2$ if \texttt{CALIB\_ZERO\_DISPARITY} is set.
1464 \end{enumerate} 
1465
1466 As you can see, the first 3 columns of \texttt{P1} and \texttt{P2} will effectively be the new "rectified" camera matrices. 
1467 The matrices, together with \texttt{R1} and \texttt{R2}, can then be passed to \cvCross{InitUndistortRectifyMap}{initUndistortRectifyMap} to initialize the rectification map for each camera.
1468
1469 Below is the screenshot from \texttt{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 \texttt{roi1} and \texttt{roi2} - indeed, their interior are all valid pixels.
1470
1471 \includegraphics[width=0.8\textwidth]{pics/stereo_undistort.jpg}
1472
1473
1474 \cvfunc{StereoRectifyUncalibrated}{stereoRectifyUncalibrated}
1475 Computes rectification transform for uncalibrated stereo camera.
1476
1477 \cvdefC{void cvStereoRectifyUncalibrated( \par const CvMat* points1, \par const CvMat* points2,
1478                                   \par const CvMat* F, \par CvSize imageSize,
1479                                   \par CvMat* H1, \par CvMat* H2,
1480                                   \par double threshold=5 );}
1481 \cvdefPy{StereoRectifyUncalibrated(points1,points2,F,imageSize,H1,H2,threshold=5)-> None}
1482 \cvdefCpp{bool stereoRectifyUncalibrated( const Mat\& points1,\par
1483                                 const Mat\& points2,\par
1484                                 const Mat\& F, Size imgSize,\par
1485                                 Mat\& H1, Mat\& H2,\par
1486                                 double threshold=5 );}
1487 \begin{description}
1488 \cvarg{points1, points2}{The 2 arrays of corresponding 2D points. The same formats as in \cvCross{FindFundamentalMat}{findFundamentalMat} are supported}
1489 \cvarg{F}{The input fundamental matrix. It can be computed from the same set of point pairs using \cvCross{FindFundamentalMat}{findFundamentalMat}.}
1490 \cvarg{imageSize}{Size of the image.}
1491 \cvarg{H1, H2}{The output rectification homography matrices for the first and for the second images.}
1492 \cvarg{threshold}{The optional threshold used to filter out the outliers. If the parameter is greater than zero, then all the point pairs that do not comply the epipolar geometry well enough (that is, the points for which $|\texttt{points2[i]}^T*\texttt{F}*\texttt{points1[i]}|>\texttt{threshold}$) are rejected prior to computing the homographies.
1493 Otherwise all the points are considered inliers.}
1494 \end{description}
1495
1496 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 \cvCross{StereoRectify}{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 \texttt{H1} and \texttt{H2}. The function implements the algorithm \cite{Hartley99}. 
1497
1498 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 \cvCross{CalibrateCamera2}{calibrateCamera} and then the images can be corrected using \cvCross{Undistort2}{undistort}, or just the point coordinates can be corrected with \cvCross{UndistortPoints}{undistortPoints}.
1499
1500
1501 \cvfunc{Undistort2}{undistort}
1502 Transforms an image to compensate for lens distortion.
1503
1504 \cvdefC{void cvUndistort2( \par const CvArr* src,\par CvArr* dst,\par const CvMat* cameraMatrix,
1505     \par const CvMat* distCoeffs, \par const CvMat* newCameraMatrix=0 );}
1506 \cvdefPy{Undistort2(src,dst,cameraMatrix,distCoeffs)-> None}
1507
1508 \cvdefCpp{void undistort( const Mat\& src, Mat\& dst, const Mat\& cameraMatrix,\par
1509                 const Mat\& distCoeffs, const Mat\& newCameraMatrix=Mat() );}
1510 \begin{description}
1511 \cvarg{src}{The input (distorted) image}
1512 \cvarg{dst}{The output (corrected) image; will have the same size and the same type as \texttt{src}}
1513 \cvarg{cameraMatrix}{The input camera matrix $A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1} $}
1514 \cvarg{distCoeffs}{The vector of distortion coefficients, $(k_1^{(j)}, k_2^{(j)}, p_1^{(j)}, p_2^{(j)}[, k_3^{(j)}])$}
1515 \cvCpp{\cvarg{newCameraMatrix}{Camera matrix of the distorted image. By default it is the same as \texttt{cameraMatrix}, but you may additionally scale and shift the result by using some different matrix}}
1516 \end{description}
1517
1518 The function transforms the image to compensate radial and tangential lens distortion.
1519
1520 The function is simply a combination of \cvCross{InitUndistortRectifyMap}{initUndistortRectifyMap} (with unity \texttt{R}) and \cvCross{Remap}{remap} (with bilinear interpolation). See the former function for details of the transformation being performed.
1521
1522 Those pixels in the destination image, for which there is no correspondent pixels in the source image, are filled with 0's (black color).
1523
1524 The particular subset of the source image that will be visible in the corrected image can be regulated by \texttt{newCameraMatrix}. You can use \cvCross{GetOptimalNewCameraMatrix}{getOptimalNewCameraMatrix} to compute the appropriate \texttt{newCameraMatrix}, depending on your requirements.
1525
1526 The camera matrix and the distortion parameters can be determined using
1527 \cvCross{CalibrateCamera2}{calibrateCamera}. If the resolution of images is different from the used at the calibration stage, $f_x, f_y, c_x$ and $c_y$ need to be scaled accordingly, while the distortion coefficients remain the same.
1528
1529
1530 \cvfunc{UndistortPoints}{undistortPoints}
1531 Computes the ideal point coordinates from the observed point coordinates.
1532
1533 \cvdefC{void cvUndistortPoints( \par const CvMat* src, \par CvMat* dst,
1534                         \par const CvMat* cameraMatrix,
1535                         \par const CvMat* distCoeffs,
1536                         \par const CvMat* R=NULL,
1537                         \par const CvMat* P=NULL);}
1538 \cvdefPy{UndistortPoints(src,dst,cameraMatrix,distCoeffs,R=NULL,P=NULL)-> None}
1539
1540 \cvdefCpp{void undistortPoints( const Mat\& src, vector<Point2f>\& dst,\par
1541                       const Mat\& cameraMatrix, const Mat\& distCoeffs,\par
1542                       const Mat\& R=Mat(), const Mat\& P=Mat());\newline
1543 void undistortPoints( const Mat\& src, Mat\& dst,\par
1544                       const Mat\& cameraMatrix, const Mat\& distCoeffs,\par
1545                       const Mat\& R=Mat(), const Mat\& P=Mat());}
1546
1547 \begin{description}
1548 \cvarg{src}{The observed point coordinates, same format as \texttt{imagePoints} in \cvCross{ProjectPoints2}{projectPoints}}
1549 \cvarg{dst}{The output ideal point coordinates, after undistortion and reverse perspective transformation\cvCPy{, same format as \texttt{src}}.}
1550 \cvarg{cameraMatrix}{The camera matrix $\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}$}
1551 \cvarg{distCoeffs}{The vector of distortion coefficients, $(k_1^{(j)}, k_2^{(j)}, p_1^{(j)}, p_2^{(j)}[, k_3^{(j)}])$}
1552 \cvarg{R}{The rectification transformation in object space (3x3 matrix). \texttt{R1} or \texttt{R2}, computed by \cvCppCross{StereoRectify} can be passed here. If the matrix is empty, the identity transformation is used}
1553 \cvarg{P}{The new camera matrix (3x3) or the new projection matrix (3x4). \texttt{P1} or \texttt{P2}, computed by \cvCppCross{StereoRectify} can be passed here. If the matrix is empty, the identity new camera matrix is used}
1554 \end{description}
1555
1556 The function is similar to \cvCross{Undistort2}{undistort} and \cvCross{InitUndistortRectifyMap}{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 \cvCross{ProjectPoints2}{projectPoints} (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 \texttt{R} is specified).
1557
1558 \begin{lstlisting}
1559 // (u,v) is the input point, (u', v') is the output point
1560 // camera_matrix=[fx 0 cx; 0 fy cy; 0 0 1]
1561 // P=[fx' 0 cx' tx; 0 fy' cy' ty; 0 0 1 tz]
1562 x" = (u - cx)/fx
1563 y" = (v - cy)/fy
1564 (x',y') = undistort(x",y",dist_coeffs)
1565 [X,Y,W]T = R*[x' y' 1]T
1566 x = X/W, y = Y/W
1567 u' = x*fx' + cx'
1568 v' = y*fy' + cy',
1569 \end{lstlisting}
1570
1571 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).
1572
1573 The function can be used both for a stereo camera head or for monocular camera (when R is \cvC{NULL}\cvPy{None}\cvCpp{empty}).