Coverage Report

Created: 2026-03-31 07:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/install-coverage/include/opencv4/opencv2/calib3d.hpp
Line
Count
Source
1
/*M///////////////////////////////////////////////////////////////////////////////////////
2
//
3
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4
//
5
//  By downloading, copying, installing or using the software you agree to this license.
6
//  If you do not agree to this license, do not download, install,
7
//  copy or use the software.
8
//
9
//
10
//                          License Agreement
11
//                For Open Source Computer Vision Library
12
//
13
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
16
// Third party copyrights are property of their respective owners.
17
//
18
// Redistribution and use in source and binary forms, with or without modification,
19
// are permitted provided that the following conditions are met:
20
//
21
//   * Redistribution's of source code must retain the above copyright notice,
22
//     this list of conditions and the following disclaimer.
23
//
24
//   * Redistribution's in binary form must reproduce the above copyright notice,
25
//     this list of conditions and the following disclaimer in the documentation
26
//     and/or other materials provided with the distribution.
27
//
28
//   * The name of the copyright holders may not be used to endorse or promote products
29
//     derived from this software without specific prior written permission.
30
//
31
// This software is provided by the copyright holders and contributors "as is" and
32
// any express or implied warranties, including, but not limited to, the implied
33
// warranties of merchantability and fitness for a particular purpose are disclaimed.
34
// In no event shall the Intel Corporation or contributors be liable for any direct,
35
// indirect, incidental, special, exemplary, or consequential damages
36
// (including, but not limited to, procurement of substitute goods or services;
37
// loss of use, data, or profits; or business interruption) however caused
38
// and on any theory of liability, whether in contract, strict liability,
39
// or tort (including negligence or otherwise) arising in any way out of
40
// the use of this software, even if advised of the possibility of such damage.
41
//
42
//M*/
43
44
#ifndef OPENCV_CALIB3D_HPP
45
#define OPENCV_CALIB3D_HPP
46
47
#include "opencv2/core.hpp"
48
#include "opencv2/core/types.hpp"
49
#include "opencv2/features2d.hpp"
50
#include "opencv2/core/affine.hpp"
51
#include "opencv2/core/utils/logger.hpp"
52
53
/**
54
  @defgroup calib3d Camera Calibration and 3D Reconstruction
55
56
The functions in this section use a so-called pinhole camera model. The view of a scene
57
is obtained by projecting a scene's 3D point \f$P_w\f$ into the image plane using a perspective
58
transformation which forms the corresponding pixel \f$p\f$. Both \f$P_w\f$ and \f$p\f$ are
59
represented in homogeneous coordinates, i.e. as 3D and 2D homogeneous vector respectively. You will
60
find a brief introduction to projective geometry, homogeneous vectors and homogeneous
61
transformations at the end of this section's introduction. For more succinct notation, we often drop
62
the 'homogeneous' and say vector instead of homogeneous vector.
63
64
The distortion-free projective transformation given by a  pinhole camera model is shown below.
65
66
\f[s \; p = A \begin{bmatrix} R|t \end{bmatrix} P_w,\f]
67
68
where \f$P_w\f$ is a 3D point expressed with respect to the world coordinate system,
69
\f$p\f$ is a 2D pixel in the image plane, \f$A\f$ is the camera intrinsic matrix,
70
\f$R\f$ and \f$t\f$ are the rotation and translation that describe the change of coordinates from
71
world to camera coordinate systems (or camera frame) and \f$s\f$ is the projective transformation's
72
arbitrary scaling and not part of the camera model.
73
74
The camera intrinsic matrix \f$A\f$ (notation used as in @cite Zhang2000 and also generally notated
75
as \f$K\f$) projects 3D points given in the camera coordinate system to 2D pixel coordinates, i.e.
76
77
\f[p = A P_c.\f]
78
79
The camera intrinsic matrix \f$A\f$ is composed of the focal lengths \f$f_x\f$ and \f$f_y\f$, which are
80
expressed in pixel units, and the principal point \f$(c_x, c_y)\f$, that is usually close to the
81
image center:
82
83
\f[A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1},\f]
84
85
and thus
86
87
\f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1} \vecthree{X_c}{Y_c}{Z_c}.\f]
88
89
The matrix of intrinsic parameters does not depend on the scene viewed. So, once estimated, it can
90
be re-used as long as the focal length is fixed (in case of a zoom lens). Thus, if an image from the
91
camera is scaled by a factor, all of these parameters need to be scaled (multiplied/divided,
92
respectively) by the same factor.
93
94
The joint rotation-translation matrix \f$[R|t]\f$ is the matrix product of a projective
95
transformation and a homogeneous transformation. The 3-by-4 projective transformation maps 3D points
96
represented in camera coordinates to 2D points in the image plane and represented in normalized
97
camera coordinates \f$x' = X_c / Z_c\f$ and \f$y' = Y_c / Z_c\f$:
98
99
\f[Z_c \begin{bmatrix}
100
x' \\
101
y' \\
102
1
103
\end{bmatrix} = \begin{bmatrix}
104
1 & 0 & 0 & 0 \\
105
0 & 1 & 0 & 0 \\
106
0 & 0 & 1 & 0
107
\end{bmatrix}
108
\begin{bmatrix}
109
X_c \\
110
Y_c \\
111
Z_c \\
112
1
113
\end{bmatrix}.\f]
114
115
The homogeneous transformation is encoded by the extrinsic parameters \f$R\f$ and \f$t\f$ and
116
represents the change of basis from world coordinate system \f$w\f$ to the camera coordinate sytem
117
\f$c\f$. Thus, given the representation of the point \f$P\f$ in world coordinates, \f$P_w\f$, we
118
obtain \f$P\f$'s representation in the camera coordinate system, \f$P_c\f$, by
119
120
\f[P_c = \begin{bmatrix}
121
R & t \\
122
0 & 1
123
\end{bmatrix} P_w,\f]
124
125
This homogeneous transformation is composed out of \f$R\f$, a 3-by-3 rotation matrix, and \f$t\f$, a
126
3-by-1 translation vector:
127
128
\f[\begin{bmatrix}
129
R & t \\
130
0 & 1
131
\end{bmatrix} = \begin{bmatrix}
132
r_{11} & r_{12} & r_{13} & t_x \\
133
r_{21} & r_{22} & r_{23} & t_y \\
134
r_{31} & r_{32} & r_{33} & t_z \\
135
0 & 0 & 0 & 1
136
\end{bmatrix},
137
\f]
138
139
and therefore
140
141
\f[\begin{bmatrix}
142
X_c \\
143
Y_c \\
144
Z_c \\
145
1
146
\end{bmatrix} = \begin{bmatrix}
147
r_{11} & r_{12} & r_{13} & t_x \\
148
r_{21} & r_{22} & r_{23} & t_y \\
149
r_{31} & r_{32} & r_{33} & t_z \\
150
0 & 0 & 0 & 1
151
\end{bmatrix}
152
\begin{bmatrix}
153
X_w \\
154
Y_w \\
155
Z_w \\
156
1
157
\end{bmatrix}.\f]
158
159
Combining the projective transformation and the homogeneous transformation, we obtain the projective
160
transformation that maps 3D points in world coordinates into 2D points in the image plane and in
161
normalized camera coordinates:
162
163
\f[Z_c \begin{bmatrix}
164
x' \\
165
y' \\
166
1
167
\end{bmatrix} = \begin{bmatrix} R|t \end{bmatrix} \begin{bmatrix}
168
X_w \\
169
Y_w \\
170
Z_w \\
171
1
172
\end{bmatrix} = \begin{bmatrix}
173
r_{11} & r_{12} & r_{13} & t_x \\
174
r_{21} & r_{22} & r_{23} & t_y \\
175
r_{31} & r_{32} & r_{33} & t_z
176
\end{bmatrix}
177
\begin{bmatrix}
178
X_w \\
179
Y_w \\
180
Z_w \\
181
1
182
\end{bmatrix},\f]
183
184
with \f$x' = X_c / Z_c\f$ and \f$y' = Y_c / Z_c\f$. Putting the equations for instrincs and extrinsics together, we can write out
185
\f$s \; p = A \begin{bmatrix} R|t \end{bmatrix} P_w\f$ as
186
187
\f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}
188
\begin{bmatrix}
189
r_{11} & r_{12} & r_{13} & t_x \\
190
r_{21} & r_{22} & r_{23} & t_y \\
191
r_{31} & r_{32} & r_{33} & t_z
192
\end{bmatrix}
193
\begin{bmatrix}
194
X_w \\
195
Y_w \\
196
Z_w \\
197
1
198
\end{bmatrix}.\f]
199
200
If \f$Z_c \ne 0\f$, the transformation above is equivalent to the following,
201
202
\f[\begin{bmatrix}
203
u \\
204
v
205
\end{bmatrix} = \begin{bmatrix}
206
f_x X_c/Z_c + c_x \\
207
f_y Y_c/Z_c + c_y
208
\end{bmatrix}\f]
209
210
with
211
212
\f[\vecthree{X_c}{Y_c}{Z_c} = \begin{bmatrix}
213
R|t
214
\end{bmatrix} \begin{bmatrix}
215
X_w \\
216
Y_w \\
217
Z_w \\
218
1
219
\end{bmatrix}.\f]
220
221
The following figure illustrates the pinhole camera model.
222
223
![Pinhole camera model](pics/pinhole_camera_model.png) { width=70% }
224
225
Real lenses usually have some distortion, mostly radial distortion, and slight tangential distortion.
226
So, the above model is extended as:
227
228
\f[\begin{bmatrix}
229
u \\
230
v
231
\end{bmatrix} = \begin{bmatrix}
232
f_x x'' + c_x \\
233
f_y y'' + c_y
234
\end{bmatrix}\f]
235
236
where
237
238
\f[\begin{bmatrix}
239
x'' \\
240
y''
241
\end{bmatrix} = \begin{bmatrix}
242
x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + 2 p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4 \\
243
y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\
244
\end{bmatrix}\f]
245
246
with
247
248
\f[r^2 = x'^2 + y'^2\f]
249
250
and
251
252
\f[\begin{bmatrix}
253
x'\\
254
y'
255
\end{bmatrix} = \begin{bmatrix}
256
X_c/Z_c \\
257
Y_c/Z_c
258
\end{bmatrix},\f]
259
260
if \f$Z_c \ne 0\f$.
261
262
The distortion parameters are the radial coefficients \f$k_1\f$, \f$k_2\f$, \f$k_3\f$, \f$k_4\f$, \f$k_5\f$, and \f$k_6\f$
263
,\f$p_1\f$ and \f$p_2\f$ are the tangential distortion coefficients, and \f$s_1\f$, \f$s_2\f$, \f$s_3\f$, and \f$s_4\f$,
264
are the thin prism distortion coefficients. Higher-order coefficients are not considered in OpenCV.
265
266
The next figures show two common types of radial distortion: barrel distortion
267
(\f$ 1 + k_1 r^2 + k_2 r^4 + k_3 r^6 \f$ monotonically decreasing)
268
and pincushion distortion (\f$ 1 + k_1 r^2 + k_2 r^4 + k_3 r^6 \f$ monotonically increasing).
269
Radial distortion is always monotonic for real lenses,
270
and if the estimator produces a non-monotonic result,
271
this should be considered a calibration failure.
272
More generally, radial distortion must be monotonic and the distortion function must be bijective.
273
A failed estimation result may look deceptively good near the image center
274
but will work poorly in e.g. AR/SFM applications.
275
The optimization method used in OpenCV camera calibration does not include these constraints as
276
the framework does not support the required integer programming and polynomial inequalities.
277
See [issue #15992](https://github.com/opencv/opencv/issues/15992) for additional information.
278
279
![](pics/distortion_examples.png)
280
![](pics/distortion_examples2.png)
281
282
In some cases, the image sensor may be tilted in order to focus an oblique plane in front of the
283
camera (Scheimpflug principle). This can be useful for particle image velocimetry (PIV) or
284
triangulation with a laser fan. The tilt causes a perspective distortion of \f$x''\f$ and
285
\f$y''\f$. This distortion can be modeled in the following way, see e.g. @cite Louhichi07.
286
287
\f[\begin{bmatrix}
288
u \\
289
v
290
\end{bmatrix} = \begin{bmatrix}
291
f_x x''' + c_x \\
292
f_y y''' + c_y
293
\end{bmatrix},\f]
294
295
where
296
297
\f[s\vecthree{x'''}{y'''}{1} =
298
\vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}(\tau_x, \tau_y)}
299
{0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)}
300
{0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\f]
301
302
and the matrix \f$R(\tau_x, \tau_y)\f$ is defined by two rotations with angular parameter
303
\f$\tau_x\f$ and \f$\tau_y\f$, respectively,
304
305
\f[
306
R(\tau_x, \tau_y) =
307
\vecthreethree{\cos(\tau_y)}{0}{-\sin(\tau_y)}{0}{1}{0}{\sin(\tau_y)}{0}{\cos(\tau_y)}
308
\vecthreethree{1}{0}{0}{0}{\cos(\tau_x)}{\sin(\tau_x)}{0}{-\sin(\tau_x)}{\cos(\tau_x)} =
309
\vecthreethree{\cos(\tau_y)}{\sin(\tau_y)\sin(\tau_x)}{-\sin(\tau_y)\cos(\tau_x)}
310
{0}{\cos(\tau_x)}{\sin(\tau_x)}
311
{\sin(\tau_y)}{-\cos(\tau_y)\sin(\tau_x)}{\cos(\tau_y)\cos(\tau_x)}.
312
\f]
313
314
In the functions below the coefficients are passed or returned as
315
316
\f[(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f]
317
318
vector. That is, if the vector contains four elements, it means that \f$k_3=0\f$ . The distortion
319
coefficients do not depend on the scene viewed. Thus, they also belong to the intrinsic camera
320
parameters. And they remain the same regardless of the captured image resolution. If, for example, a
321
camera has been calibrated on images of 320 x 240 resolution, absolutely the same distortion
322
coefficients can be used for 640 x 480 images from the same camera while \f$f_x\f$, \f$f_y\f$,
323
\f$c_x\f$, and \f$c_y\f$ need to be scaled appropriately.
324
325
The functions below use the above model to do the following:
326
327
-   Project 3D points to the image plane given intrinsic and extrinsic parameters.
328
-   Compute extrinsic parameters given intrinsic parameters, a few 3D points, and their
329
projections.
330
-   Estimate intrinsic and extrinsic camera parameters from several views of a known calibration
331
pattern (every view is described by several 3D-2D point correspondences).
332
-   Estimate the relative position and orientation of the stereo camera "heads" and compute the
333
*rectification* transformation that makes the camera optical axes parallel.
334
335
<B> Homogeneous Coordinates </B><br>
336
Homogeneous Coordinates are a system of coordinates that are used in projective geometry. Their use
337
allows to represent points at infinity by finite coordinates and simplifies formulas when compared
338
to the cartesian counterparts, e.g. they have the advantage that affine transformations can be
339
expressed as linear homogeneous transformation.
340
341
One obtains the homogeneous vector \f$P_h\f$ by appending a 1 along an n-dimensional cartesian
342
vector \f$P\f$ e.g. for a 3D cartesian vector the mapping \f$P \rightarrow P_h\f$ is:
343
344
\f[\begin{bmatrix}
345
X \\
346
Y \\
347
Z
348
\end{bmatrix} \rightarrow \begin{bmatrix}
349
X \\
350
Y \\
351
Z \\
352
1
353
\end{bmatrix}.\f]
354
355
For the inverse mapping \f$P_h \rightarrow P\f$, one divides all elements of the homogeneous vector
356
by its last element, e.g. for a 3D homogeneous vector one gets its 2D cartesian counterpart by:
357
358
\f[\begin{bmatrix}
359
X \\
360
Y \\
361
W
362
\end{bmatrix} \rightarrow \begin{bmatrix}
363
X / W \\
364
Y / W
365
\end{bmatrix},\f]
366
367
if \f$W \ne 0\f$.
368
369
Due to this mapping, all multiples \f$k P_h\f$, for \f$k \ne 0\f$, of a homogeneous point represent
370
the same point \f$P_h\f$. An intuitive understanding of this property is that under a projective
371
transformation, all multiples of \f$P_h\f$ are mapped to the same point. This is the physical
372
observation one does for pinhole cameras, as all points along a ray through the camera's pinhole are
373
projected to the same image point, e.g. all points along the red ray in the image of the pinhole
374
camera model above would be mapped to the same image coordinate. This property is also the source
375
for the scale ambiguity s in the equation of the pinhole camera model.
376
377
As mentioned, by using homogeneous coordinates we can express any change of basis parameterized by
378
\f$R\f$ and \f$t\f$ as a linear transformation, e.g. for the change of basis from coordinate system
379
0 to coordinate system 1 becomes:
380
381
\f[P_1 = R P_0 + t \rightarrow P_{h_1} = \begin{bmatrix}
382
R & t \\
383
0 & 1
384
\end{bmatrix} P_{h_0}.\f]
385
386
<B> Homogeneous Transformations, Object frame / Camera frame </B><br>
387
Change of basis or computing the 3D coordinates from one frame to another frame can be achieved easily using
388
the following notation:
389
390
\f[
391
\mathbf{X}_c = \hspace{0.2em}
392
{}^{c}\mathbf{T}_o \hspace{0.2em} \mathbf{X}_o
393
\f]
394
395
\f[
396
\begin{bmatrix}
397
X_c \\
398
Y_c \\
399
Z_c \\
400
1
401
\end{bmatrix} =
402
\begin{bmatrix}
403
{}^{c}\mathbf{R}_o & {}^{c}\mathbf{t}_o \\
404
0_{1 \times 3} & 1
405
\end{bmatrix}
406
\begin{bmatrix}
407
X_o \\
408
Y_o \\
409
Z_o \\
410
1
411
\end{bmatrix}
412
\f]
413
414
For a 3D points (\f$ \mathbf{X}_o \f$) expressed in the object frame, the homogeneous transformation matrix
415
\f$ {}^{c}\mathbf{T}_o \f$ allows computing the corresponding coordinate (\f$ \mathbf{X}_c \f$) in the camera frame.
416
This transformation matrix is composed of a 3x3 rotation matrix \f$ {}^{c}\mathbf{R}_o \f$ and a 3x1 translation vector
417
\f$ {}^{c}\mathbf{t}_o \f$.
418
The 3x1 translation vector \f$ {}^{c}\mathbf{t}_o \f$ is the position of the object frame in the camera frame and the
419
3x3 rotation matrix \f$ {}^{c}\mathbf{R}_o \f$ the orientation of the object frame in the camera frame.
420
421
With this simple notation, it is easy to chain the transformations. For instance, to compute the 3D coordinates of a point
422
expressed in the object frame in the world frame can be done with:
423
424
\f[
425
\mathbf{X}_w = \hspace{0.2em}
426
{}^{w}\mathbf{T}_c \hspace{0.2em} {}^{c}\mathbf{T}_o \hspace{0.2em}
427
\mathbf{X}_o =
428
{}^{w}\mathbf{T}_o \hspace{0.2em} \mathbf{X}_o
429
\f]
430
431
Similarly, computing the inverse transformation can be done with:
432
433
\f[
434
\mathbf{X}_o = \hspace{0.2em}
435
{}^{o}\mathbf{T}_c \hspace{0.2em} \mathbf{X}_c =
436
\left( {}^{c}\mathbf{T}_o \right)^{-1} \hspace{0.2em} \mathbf{X}_c
437
\f]
438
439
The inverse of an homogeneous transformation matrix is then:
440
441
\f[
442
{}^{o}\mathbf{T}_c = \left( {}^{c}\mathbf{T}_o \right)^{-1} =
443
\begin{bmatrix}
444
{}^{c}\mathbf{R}^{\top}_o & - \hspace{0.2em} {}^{c}\mathbf{R}^{\top}_o \hspace{0.2em} {}^{c}\mathbf{t}_o \\
445
0_{1 \times 3} & 1
446
\end{bmatrix}
447
\f]
448
449
One can note that the inverse of a 3x3 rotation matrix is directly its matrix transpose.
450
451
![Perspective projection, from object to camera frame](pics/pinhole_homogeneous_transformation.jpg) { width=70% }
452
453
This figure summarizes the whole process. The object pose returned for instance by the @ref solvePnP function
454
or pose from fiducial marker detection is this \f$ {}^{c}\mathbf{T}_o \f$ transformation.
455
456
The camera intrinsic matrix \f$ \mathbf{K} \f$ allows projecting the 3D point expressed in the camera frame onto the image plane
457
assuming a perspective projection model (pinhole camera model). Image coordinates extracted from classical image processing functions
458
assume a (u,v) top-left coordinates frame.
459
460
\note
461
- for an online video course on this topic, see for instance:
462
  - ["3.3.1. Homogeneous Transformation Matrices", Modern Robotics, Kevin M. Lynch and Frank C. Park](https://modernrobotics.northwestern.edu/nu-gm-book-resource/3-3-1-homogeneous-transformation-matrices/)
463
- the 3x3 rotation matrix is composed of 9 values but describes a 3 dof transformation
464
- some additional properties of the 3x3 rotation matrix are:
465
  - \f$ \mathrm{det} \left( \mathbf{R} \right) = 1 \f$
466
  - \f$ \mathbf{R} \mathbf{R}^{\top} = \mathbf{R}^{\top} \mathbf{R} = \mathrm{I}_{3 \times 3} \f$
467
  - interpolating rotation can be done using the [Slerp (spherical linear interpolation)](https://en.wikipedia.org/wiki/Slerp) method
468
- quick conversions between the different rotation formalisms can be done using this [online tool](https://www.andre-gaschler.com/rotationconverter/)
469
470
<B> Intrinsic parameters from camera lens specifications </B><br>
471
When dealing with industrial cameras, the camera intrinsic matrix or more precisely \f$ \left(f_x, f_y \right) \f$
472
can be deduced, approximated from the camera specifications:
473
474
\f[
475
f_x = \frac{f_{\text{mm}}}{\text{pixel_size_in_mm}} = \frac{f_{\text{mm}}}{\text{sensor_size_in_mm} / \text{nb_pixels}}
476
\f]
477
478
In a same way, the physical focal length can be deduced from the angular field of view:
479
480
\f[
481
f_{\text{mm}} = \frac{\text{sensor_size_in_mm}}{2 \times \tan{\frac{\text{fov}}{2}}}
482
\f]
483
484
This latter conversion can be useful when using a rendering software to mimic a physical camera device.
485
486
@note
487
    -    See also #calibrationMatrixValues
488
489
<B> Additional references, notes </B><br>
490
@note
491
    -   Many functions in this module take a camera intrinsic matrix as an input parameter. Although all
492
        functions assume the same structure of this parameter, they may name it differently. The
493
        parameter's description, however, will be clear in that a camera intrinsic matrix with the structure
494
        shown above is required.
495
    -   A calibration sample for 3 cameras in a horizontal position can be found at
496
        opencv_source_code/samples/cpp/3calibration.cpp
497
    -   A calibration sample based on a sequence of images can be found at
498
        opencv_source_code/samples/cpp/calibration.cpp
499
    -   A calibration sample in order to do 3D reconstruction can be found at
500
        opencv_source_code/samples/cpp/build3dmodel.cpp
501
    -   A calibration example on stereo calibration can be found at
502
        opencv_source_code/samples/cpp/stereo_calib.cpp
503
    -   A calibration example on stereo matching can be found at
504
        opencv_source_code/samples/cpp/stereo_match.cpp
505
    -   (Python) A camera calibration sample can be found at
506
        opencv_source_code/samples/python/calibrate.py
507
508
  @{
509
    @defgroup calib3d_fisheye Fisheye camera model
510
511
    Definitions: Let P be a point in 3D of coordinates X in the world reference frame (stored in the
512
    matrix X) The coordinate vector of P in the camera reference frame is:
513
514
    \f[Xc = R X + T\f]
515
516
    where R is the rotation matrix corresponding to the rotation vector om: R = rodrigues(om); call x, y
517
    and z the 3 coordinates of Xc:
518
519
    \f[\begin{array}{l} x = Xc_1 \\ y = Xc_2 \\ z = Xc_3 \end{array} \f]
520
521
    The pinhole projection coordinates of P is [a; b] where
522
523
    \f[\begin{array}{l} a = x / z \ and \ b = y / z \\ r^2 = a^2 + b^2 \\ \theta = atan(r) \end{array} \f]
524
525
    Fisheye distortion:
526
527
    \f[\theta_d = \theta (1 + k_1 \theta^2 + k_2 \theta^4 + k_3 \theta^6 + k_4 \theta^8)\f]
528
529
    The distorted point coordinates are [x'; y'] where
530
531
    \f[\begin{array}{l} x' = (\theta_d / r) a \\ y' = (\theta_d / r) b \end{array} \f]
532
533
    Finally, conversion into pixel coordinates: The final pixel coordinates vector [u; v] where:
534
535
    \f[\begin{array}{l} u = f_x (x' + \alpha y') + c_x \\
536
    v = f_y y' + c_y \end{array} \f]
537
538
    Summary:
539
    Generic camera model @cite Kannala2006 with perspective projection and without distortion correction
540
541
  @}
542
 */
543
544
namespace cv
545
{
546
547
//! @addtogroup calib3d
548
//! @{
549
550
//! type of the robust estimation algorithm
551
enum { LMEDS  = 4,  //!< least-median of squares algorithm
552
       RANSAC = 8,  //!< RANSAC algorithm
553
       RHO    = 16, //!< RHO algorithm
554
       USAC_DEFAULT  = 32, //!< USAC algorithm, default settings
555
       USAC_PARALLEL = 33, //!< USAC, parallel version
556
       USAC_FM_8PTS = 34,  //!< USAC, fundamental matrix 8 points
557
       USAC_FAST = 35,     //!< USAC, fast settings
558
       USAC_ACCURATE = 36, //!< USAC, accurate settings
559
       USAC_PROSAC = 37,   //!< USAC, sorted points, runs PROSAC
560
       USAC_MAGSAC = 38    //!< USAC, runs MAGSAC++
561
     };
562
563
enum SolvePnPMethod {
564
    SOLVEPNP_ITERATIVE   = 0, //!< Pose refinement using non-linear Levenberg-Marquardt minimization scheme @cite Madsen04 @cite Eade13 \n
565
                              //!< Initial solution for non-planar "objectPoints" needs at least 6 points and uses the DLT algorithm. \n
566
                              //!< Initial solution for planar "objectPoints" needs at least 4 points and uses pose from homography decomposition.
567
    SOLVEPNP_EPNP        = 1, //!< EPnP: Efficient Perspective-n-Point Camera Pose Estimation @cite lepetit2009epnp
568
    SOLVEPNP_P3P         = 2, //!< Revisiting the P3P Problem @cite ding2023revisiting
569
    SOLVEPNP_DLS         = 3, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n
570
                              //!< A Direct Least-Squares (DLS) Method for PnP @cite hesch2011direct
571
    SOLVEPNP_UPNP        = 4, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n
572
                              //!< Exhaustive Linearization for Robust Camera Pose and Focal Length Estimation @cite penate2013exhaustive
573
    SOLVEPNP_AP3P        = 5, //!< An Efficient Algebraic Solution to the Perspective-Three-Point Problem @cite Ke17
574
    SOLVEPNP_IPPE        = 6, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n
575
                              //!< Object points must be coplanar.
576
    SOLVEPNP_IPPE_SQUARE = 7, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n
577
                              //!< This is a special case suitable for marker pose estimation.\n
578
                              //!< 4 coplanar object points must be defined in the following order:
579
                              //!<   - point 0: [-squareLength / 2,  squareLength / 2, 0]
580
                              //!<   - point 1: [ squareLength / 2,  squareLength / 2, 0]
581
                              //!<   - point 2: [ squareLength / 2, -squareLength / 2, 0]
582
                              //!<   - point 3: [-squareLength / 2, -squareLength / 2, 0]
583
    SOLVEPNP_SQPNP       = 8, //!< SQPnP: A Consistently Fast and Globally OptimalSolution to the Perspective-n-Point Problem @cite Terzakis2020SQPnP
584
#ifndef CV_DOXYGEN
585
    SOLVEPNP_MAX_COUNT        //!< Used for count
586
#endif
587
};
588
589
enum { CALIB_CB_ADAPTIVE_THRESH = 1,
590
       CALIB_CB_NORMALIZE_IMAGE = 2,
591
       CALIB_CB_FILTER_QUADS    = 4,
592
       CALIB_CB_FAST_CHECK      = 8,
593
       CALIB_CB_EXHAUSTIVE      = 16,
594
       CALIB_CB_ACCURACY        = 32,
595
       CALIB_CB_LARGER          = 64,
596
       CALIB_CB_MARKER          = 128,
597
       CALIB_CB_PLAIN           = 256
598
     };
599
600
enum { CALIB_CB_SYMMETRIC_GRID  = 1,
601
       CALIB_CB_ASYMMETRIC_GRID = 2,
602
       CALIB_CB_CLUSTERING      = 4
603
     };
604
605
enum { CALIB_NINTRINSIC          = 18,
606
       CALIB_USE_INTRINSIC_GUESS = 0x00001,
607
       CALIB_FIX_ASPECT_RATIO    = 0x00002,
608
       CALIB_FIX_PRINCIPAL_POINT = 0x00004,
609
       CALIB_ZERO_TANGENT_DIST   = 0x00008,
610
       CALIB_FIX_FOCAL_LENGTH    = 0x00010,
611
       CALIB_FIX_K1              = 0x00020,
612
       CALIB_FIX_K2              = 0x00040,
613
       CALIB_FIX_K3              = 0x00080,
614
       CALIB_FIX_K4              = 0x00800,
615
       CALIB_FIX_K5              = 0x01000,
616
       CALIB_FIX_K6              = 0x02000,
617
       CALIB_RATIONAL_MODEL      = 0x04000,
618
       CALIB_THIN_PRISM_MODEL    = 0x08000,
619
       CALIB_FIX_S1_S2_S3_S4     = 0x10000,
620
       CALIB_TILTED_MODEL        = 0x40000,
621
       CALIB_FIX_TAUX_TAUY       = 0x80000,
622
       CALIB_USE_QR              = 0x100000, //!< use QR instead of SVD decomposition for solving. Faster but potentially less precise
623
       CALIB_FIX_TANGENT_DIST    = 0x200000,
624
       // only for stereo
625
       CALIB_FIX_INTRINSIC       = 0x00100,
626
       CALIB_SAME_FOCAL_LENGTH   = 0x00200,
627
       // for stereo rectification
628
       CALIB_ZERO_DISPARITY      = 0x00400,
629
       CALIB_USE_LU              = (1 << 17), //!< use LU instead of SVD decomposition for solving. much faster but potentially less precise
630
       CALIB_USE_EXTRINSIC_GUESS = (1 << 22), //!< for stereoCalibrate
631
       CALIB_DISABLE_SCHUR_COMPLEMENT = (1 << 23)  //!< disable Schur complement (use Bouguet calibration engine)
632
     };
633
634
//! the algorithm for finding fundamental matrix
635
enum { FM_7POINT = 1, //!< 7-point algorithm
636
       FM_8POINT = 2, //!< 8-point algorithm
637
       FM_LMEDS  = 4, //!< least-median algorithm. 7-point algorithm is used.
638
       FM_RANSAC = 8  //!< RANSAC algorithm. It needs at least 15 points. 7-point algorithm is used.
639
     };
640
641
enum HandEyeCalibrationMethod
642
{
643
    CALIB_HAND_EYE_TSAI         = 0, //!< A New Technique for Fully Autonomous and Efficient 3D Robotics Hand/Eye Calibration @cite Tsai89
644
    CALIB_HAND_EYE_PARK         = 1, //!< Robot Sensor Calibration: Solving AX = XB on the Euclidean Group @cite Park94
645
    CALIB_HAND_EYE_HORAUD       = 2, //!< Hand-eye Calibration @cite Horaud95
646
    CALIB_HAND_EYE_ANDREFF      = 3, //!< On-line Hand-Eye Calibration @cite Andreff99
647
    CALIB_HAND_EYE_DANIILIDIS   = 4  //!< Hand-Eye Calibration Using Dual Quaternions @cite Daniilidis98
648
};
649
650
enum RobotWorldHandEyeCalibrationMethod
651
{
652
    CALIB_ROBOT_WORLD_HAND_EYE_SHAH = 0, //!< Solving the robot-world/hand-eye calibration problem using the kronecker product @cite Shah2013SolvingTR
653
    CALIB_ROBOT_WORLD_HAND_EYE_LI   = 1  //!< Simultaneous robot-world and hand-eye calibration using dual-quaternions and kronecker product @cite Li2010SimultaneousRA
654
};
655
656
enum SamplingMethod { SAMPLING_UNIFORM=0, SAMPLING_PROGRESSIVE_NAPSAC=1, SAMPLING_NAPSAC=2,
657
        SAMPLING_PROSAC=3 };
658
enum LocalOptimMethod {LOCAL_OPTIM_NULL=0, LOCAL_OPTIM_INNER_LO=1, LOCAL_OPTIM_INNER_AND_ITER_LO=2,
659
        LOCAL_OPTIM_GC=3, LOCAL_OPTIM_SIGMA=4};
660
enum ScoreMethod {SCORE_METHOD_RANSAC=0, SCORE_METHOD_MSAC=1, SCORE_METHOD_MAGSAC=2, SCORE_METHOD_LMEDS=3};
661
enum NeighborSearchMethod { NEIGH_FLANN_KNN=0, NEIGH_GRID=1, NEIGH_FLANN_RADIUS=2 };
662
enum PolishingMethod { NONE_POLISHER=0, LSQ_POLISHER=1, MAGSAC=2, COV_POLISHER=3 };
663
664
struct CV_EXPORTS_W_SIMPLE UsacParams
665
{ // in alphabetical order
666
    CV_WRAP UsacParams();
667
    CV_PROP_RW double confidence;
668
    CV_PROP_RW bool isParallel;
669
    CV_PROP_RW int loIterations;
670
    CV_PROP_RW LocalOptimMethod loMethod;
671
    CV_PROP_RW int loSampleSize;
672
    CV_PROP_RW int maxIterations;
673
    CV_PROP_RW NeighborSearchMethod neighborsSearch;
674
    CV_PROP_RW int randomGeneratorState;
675
    CV_PROP_RW SamplingMethod sampler;
676
    CV_PROP_RW ScoreMethod score;
677
    CV_PROP_RW double threshold;
678
    CV_PROP_RW PolishingMethod final_polisher;
679
    CV_PROP_RW int final_polisher_iterations;
680
};
681
682
/** @brief Converts a rotation matrix to a rotation vector or vice versa.
683
684
@param src Input rotation vector (3x1 or 1x3) or rotation matrix (3x3).
685
@param dst Output rotation matrix (3x3) or rotation vector (3x1 or 1x3), respectively.
686
@param jacobian Optional output Jacobian matrix, 3x9 or 9x3, which is a matrix of partial
687
derivatives of the output array components with respect to the input array components.
688
689
\f[\begin{array}{l} \theta \leftarrow norm(r) \\ r  \leftarrow r/ \theta \\ R =  \cos(\theta) I + (1- \cos{\theta} ) r r^T +  \sin(\theta) \vecthreethree{0}{-r_z}{r_y}{r_z}{0}{-r_x}{-r_y}{r_x}{0} \end{array}\f]
690
691
Inverse transformation can be also done easily, since
692
693
\f[\sin ( \theta ) \vecthreethree{0}{-r_z}{r_y}{r_z}{0}{-r_x}{-r_y}{r_x}{0} = \frac{R - R^T}{2}\f]
694
695
A rotation vector is a convenient and most compact representation of a rotation matrix (since any
696
rotation matrix has just 3 degrees of freedom). The representation is used in the global 3D geometry
697
optimization procedures like @ref calibrateCamera, @ref stereoCalibrate, or @ref solvePnP .
698
699
@note More information about the computation of the derivative of a 3D rotation matrix with respect to its exponential coordinate
700
can be found in:
701
    - A Compact Formula for the Derivative of a 3-D Rotation in Exponential Coordinates, Guillermo Gallego, Anthony J. Yezzi @cite Gallego2014ACF
702
703
@note Useful information on SE(3) and Lie Groups can be found in:
704
    - A tutorial on SE(3) transformation parameterizations and on-manifold optimization, Jose-Luis Blanco @cite blanco2010tutorial
705
    - Lie Groups for 2D and 3D Transformation, Ethan Eade @cite Eade17
706
    - A micro Lie theory for state estimation in robotics, Joan Solà, Jérémie Deray, Dinesh Atchuthan @cite Sol2018AML
707
 */
708
CV_EXPORTS_W void Rodrigues( InputArray src, OutputArray dst, OutputArray jacobian = noArray() );
709
710
711
712
/** Levenberg-Marquardt solver. Starting with the specified vector of parameters it
713
    optimizes the target vector criteria "err"
714
    (finds local minima of each target vector component absolute value).
715
716
    When needed, it calls user-provided callback.
717
*/
718
class CV_EXPORTS LMSolver : public Algorithm
719
{
720
public:
721
    class CV_EXPORTS Callback
722
    {
723
    public:
724
0
        virtual ~Callback() {}
725
        /**
726
         computes error and Jacobian for the specified vector of parameters
727
728
         @param param the current vector of parameters
729
         @param err output vector of errors: err_i = actual_f_i - ideal_f_i
730
         @param J output Jacobian: J_ij = d(ideal_f_i)/d(param_j)
731
732
         when J=noArray(), it means that it does not need to be computed.
733
         Dimensionality of error vector and param vector can be different.
734
         The callback should explicitly allocate (with "create" method) each output array
735
         (unless it's noArray()).
736
        */
737
        virtual bool compute(InputArray param, OutputArray err, OutputArray J) const = 0;
738
    };
739
740
    /**
741
       Runs Levenberg-Marquardt algorithm using the passed vector of parameters as the start point.
742
       The final vector of parameters (whether the algorithm converged or not) is stored at the same
743
       vector. The method returns the number of iterations used. If it's equal to the previously specified
744
       maxIters, there is a big chance the algorithm did not converge.
745
746
       @param param initial/final vector of parameters.
747
748
       Note that the dimensionality of parameter space is defined by the size of param vector,
749
       and the dimensionality of optimized criteria is defined by the size of err vector
750
       computed by the callback.
751
    */
752
    virtual int run(InputOutputArray param) const = 0;
753
754
    /**
755
       Sets the maximum number of iterations
756
       @param maxIters the number of iterations
757
    */
758
    virtual void setMaxIters(int maxIters) = 0;
759
    /**
760
       Retrieves the current maximum number of iterations
761
    */
762
    virtual int getMaxIters() const = 0;
763
764
    /**
765
       Creates Levenberg-Marquard solver
766
767
       @param cb callback
768
       @param maxIters maximum number of iterations that can be further
769
         modified using setMaxIters() method.
770
    */
771
    static Ptr<LMSolver> create(const Ptr<LMSolver::Callback>& cb, int maxIters);
772
    static Ptr<LMSolver> create(const Ptr<LMSolver::Callback>& cb, int maxIters, double eps);
773
};
774
775
776
777
/** @example samples/cpp/tutorial_code/features2D/Homography/pose_from_homography.cpp
778
An example program about pose estimation from coplanar points
779
780
Check @ref tutorial_homography "the corresponding tutorial" for more details
781
*/
782
783
/** @brief Finds a perspective transformation between two planes.
784
785
@param srcPoints Coordinates of the points in the original plane, a matrix of the type CV_32FC2
786
or vector\<Point2f\> .
787
@param dstPoints Coordinates of the points in the target plane, a matrix of the type CV_32FC2 or
788
a vector\<Point2f\> .
789
@param method Method used to compute a homography matrix. The following methods are possible:
790
-   **0** - a regular method using all the points, i.e., the least squares method
791
-   @ref RANSAC - RANSAC-based robust method
792
-   @ref LMEDS - Least-Median robust method
793
-   @ref RHO - PROSAC-based robust method
794
@param ransacReprojThreshold Maximum allowed reprojection error to treat a point pair as an inlier
795
(used in the RANSAC and RHO methods only). That is, if
796
\f[\| \texttt{dstPoints} _i -  \texttt{convertPointsHomogeneous} ( \texttt{H} \cdot \texttt{srcPoints} _i) \|_2  >  \texttt{ransacReprojThreshold}\f]
797
then the point \f$i\f$ is considered as an outlier. If srcPoints and dstPoints are measured in pixels,
798
it usually makes sense to set this parameter somewhere in the range of 1 to 10.
799
@param mask Optional output mask set by a robust method ( RANSAC or LMeDS ). Note that the input
800
mask values are ignored.
801
@param maxIters The maximum number of RANSAC iterations.
802
@param confidence Confidence level, between 0 and 1.
803
804
The function finds and returns the perspective transformation \f$H\f$ between the source and the
805
destination planes:
806
807
\f[s_i  \vecthree{x'_i}{y'_i}{1} \sim H  \vecthree{x_i}{y_i}{1}\f]
808
809
so that the back-projection error
810
811
\f[\sum _i \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+ \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\f]
812
813
is minimized. If the parameter method is set to the default value 0, the function uses all the point
814
pairs to compute an initial homography estimate with a simple least-squares scheme.
815
816
However, if not all of the point pairs ( \f$srcPoints_i\f$, \f$dstPoints_i\f$ ) fit the rigid perspective
817
transformation (that is, there are some outliers), this initial estimate will be poor. In this case,
818
you can use one of the three robust methods. The methods RANSAC, LMeDS and RHO try many different
819
random subsets of the corresponding point pairs (of four pairs each, collinear pairs are discarded), estimate the homography matrix
820
using this subset and a simple least-squares algorithm, and then compute the quality/goodness of the
821
computed homography (which is the number of inliers for RANSAC or the least median re-projection error for
822
LMeDS). The best subset is then used to produce the initial estimate of the homography matrix and
823
the mask of inliers/outliers.
824
825
Regardless of the method, robust or not, the computed homography matrix is refined further (using
826
inliers only in case of a robust method) with the Levenberg-Marquardt method to reduce the
827
re-projection error even more.
828
829
The methods RANSAC and RHO can handle practically any ratio of outliers but need a threshold to
830
distinguish inliers from outliers. The method LMeDS does not need any threshold but it works
831
correctly only when there are more than 50% of inliers. Finally, if there are no outliers and the
832
noise is rather small, use the default method (method=0).
833
834
The function is used to find initial intrinsic and extrinsic matrices. Homography matrix is
835
determined up to a scale. If \f$h_{33}\f$ is non-zero, the matrix is normalized so that \f$h_{33}=1\f$.
836
@note Whenever an \f$H\f$ matrix cannot be estimated, an empty one will be returned.
837
838
@sa
839
getAffineTransform, estimateAffine2D, estimateAffinePartial2D, getPerspectiveTransform, warpPerspective,
840
perspectiveTransform
841
 */
842
CV_EXPORTS_W Mat findHomography( InputArray srcPoints, InputArray dstPoints,
843
                                 int method = 0, double ransacReprojThreshold = 3,
844
                                 OutputArray mask=noArray(), const int maxIters = 2000,
845
                                 const double confidence = 0.995);
846
847
/** @overload */
848
CV_EXPORTS Mat findHomography( InputArray srcPoints, InputArray dstPoints,
849
                               OutputArray mask, int method = 0, double ransacReprojThreshold = 3 );
850
851
852
CV_EXPORTS_W Mat findHomography(InputArray srcPoints, InputArray dstPoints, OutputArray mask,
853
                   const UsacParams &params);
854
855
/** @brief Computes an RQ decomposition of 3x3 matrices.
856
857
@param src 3x3 input matrix.
858
@param mtxR Output 3x3 upper-triangular matrix.
859
@param mtxQ Output 3x3 orthogonal matrix.
860
@param Qx Optional output 3x3 rotation matrix around x-axis.
861
@param Qy Optional output 3x3 rotation matrix around y-axis.
862
@param Qz Optional output 3x3 rotation matrix around z-axis.
863
864
The function computes a RQ decomposition using the given rotations. This function is used in
865
#decomposeProjectionMatrix to decompose the left 3x3 submatrix of a projection matrix into a camera
866
and a rotation matrix.
867
868
It optionally returns three rotation matrices, one for each axis, and the three Euler angles in
869
degrees (as the return value) that could be used in OpenGL. Note, there is always more than one
870
sequence of rotations about the three principal axes that results in the same orientation of an
871
object, e.g. see @cite Slabaugh . Returned three rotation matrices and corresponding three Euler angles
872
are only one of the possible solutions.
873
 */
874
CV_EXPORTS_W Vec3d RQDecomp3x3( InputArray src, OutputArray mtxR, OutputArray mtxQ,
875
                                OutputArray Qx = noArray(),
876
                                OutputArray Qy = noArray(),
877
                                OutputArray Qz = noArray());
878
879
/** @brief Decomposes a projection matrix into a rotation matrix and a camera intrinsic matrix.
880
881
@param projMatrix 3x4 input projection matrix P.
882
@param cameraMatrix Output 3x3 camera intrinsic matrix \f$\cameramatrix{A}\f$.
883
@param rotMatrix Output 3x3 external rotation matrix R.
884
@param transVect Output 4x1 translation vector T.
885
@param rotMatrixX Optional 3x3 rotation matrix around x-axis.
886
@param rotMatrixY Optional 3x3 rotation matrix around y-axis.
887
@param rotMatrixZ Optional 3x3 rotation matrix around z-axis.
888
@param eulerAngles Optional three-element vector containing three Euler angles of rotation in
889
degrees.
890
891
The function computes a decomposition of a projection matrix into a calibration and a rotation
892
matrix and the position of a camera.
893
894
It optionally returns three rotation matrices, one for each axis, and three Euler angles that could
895
be used in OpenGL. Note, there is always more than one sequence of rotations about the three
896
principal axes that results in the same orientation of an object, e.g. see @cite Slabaugh . Returned
897
three rotation matrices and corresponding three Euler angles are only one of the possible solutions.
898
899
The function is based on #RQDecomp3x3 .
900
 */
901
CV_EXPORTS_W void decomposeProjectionMatrix( InputArray projMatrix, OutputArray cameraMatrix,
902
                                             OutputArray rotMatrix, OutputArray transVect,
903
                                             OutputArray rotMatrixX = noArray(),
904
                                             OutputArray rotMatrixY = noArray(),
905
                                             OutputArray rotMatrixZ = noArray(),
906
                                             OutputArray eulerAngles =noArray() );
907
908
/** @brief Computes partial derivatives of the matrix product for each multiplied matrix.
909
910
@param A First multiplied matrix.
911
@param B Second multiplied matrix.
912
@param dABdA First output derivative matrix d(A\*B)/dA of size
913
\f$\texttt{A.rows*B.cols} \times {A.rows*A.cols}\f$ .
914
@param dABdB Second output derivative matrix d(A\*B)/dB of size
915
\f$\texttt{A.rows*B.cols} \times {B.rows*B.cols}\f$ .
916
917
The function computes partial derivatives of the elements of the matrix product \f$A*B\f$ with regard to
918
the elements of each of the two input matrices. The function is used to compute the Jacobian
919
matrices in #stereoCalibrate but can also be used in any other similar optimization function.
920
 */
921
CV_EXPORTS_W void matMulDeriv( InputArray A, InputArray B, OutputArray dABdA, OutputArray dABdB );
922
923
/** @brief Combines two rotation-and-shift transformations.
924
925
@param rvec1 First rotation vector.
926
@param tvec1 First translation vector.
927
@param rvec2 Second rotation vector.
928
@param tvec2 Second translation vector.
929
@param rvec3 Output rotation vector of the superposition.
930
@param tvec3 Output translation vector of the superposition.
931
@param dr3dr1 Optional output derivative of rvec3 with regard to rvec1
932
@param dr3dt1 Optional output derivative of rvec3 with regard to tvec1
933
@param dr3dr2 Optional output derivative of rvec3 with regard to rvec2
934
@param dr3dt2 Optional output derivative of rvec3 with regard to tvec2
935
@param dt3dr1 Optional output derivative of tvec3 with regard to rvec1
936
@param dt3dt1 Optional output derivative of tvec3 with regard to tvec1
937
@param dt3dr2 Optional output derivative of tvec3 with regard to rvec2
938
@param dt3dt2 Optional output derivative of tvec3 with regard to tvec2
939
940
The functions compute:
941
942
\f[\begin{array}{l} \texttt{rvec3} =  \mathrm{rodrigues} ^{-1} \left ( \mathrm{rodrigues} ( \texttt{rvec2} )  \cdot \mathrm{rodrigues} ( \texttt{rvec1} ) \right )  \\ \texttt{tvec3} =  \mathrm{rodrigues} ( \texttt{rvec2} )  \cdot \texttt{tvec1} +  \texttt{tvec2} \end{array} ,\f]
943
944
where \f$\mathrm{rodrigues}\f$ denotes a rotation vector to a rotation matrix transformation, and
945
\f$\mathrm{rodrigues}^{-1}\f$ denotes the inverse transformation. See #Rodrigues for details.
946
947
Also, the functions can compute the derivatives of the output vectors with regards to the input
948
vectors (see #matMulDeriv ). The functions are used inside #stereoCalibrate but can also be used in
949
your own code where Levenberg-Marquardt or another gradient-based solver is used to optimize a
950
function that contains a matrix multiplication.
951
 */
952
CV_EXPORTS_W void composeRT( InputArray rvec1, InputArray tvec1,
953
                             InputArray rvec2, InputArray tvec2,
954
                             OutputArray rvec3, OutputArray tvec3,
955
                             OutputArray dr3dr1 = noArray(), OutputArray dr3dt1 = noArray(),
956
                             OutputArray dr3dr2 = noArray(), OutputArray dr3dt2 = noArray(),
957
                             OutputArray dt3dr1 = noArray(), OutputArray dt3dt1 = noArray(),
958
                             OutputArray dt3dr2 = noArray(), OutputArray dt3dt2 = noArray() );
959
960
/** @brief Projects 3D points to an image plane.
961
962
The function computes the 2D projections of 3D points to the image plane, given intrinsic and
963
extrinsic camera parameters. Optionally, the function computes Jacobians -matrices of partial
964
derivatives of image points coordinates (as functions of all the input parameters) with respect to
965
the particular parameters, intrinsic and/or extrinsic. The Jacobians are used during the global
966
optimization in @ref calibrateCamera, @ref solvePnP, and @ref stereoCalibrate. The function itself
967
can also be used to compute a re-projection error, given the current intrinsic and extrinsic
968
parameters.
969
970
@note **Coordinate Systems:**
971
- **Input (`objectPoints`)**: 3D points in the **world coordinate frame**.
972
- **Output (`imagePoints`)**: 2D projections in **pixel coordinates** of the image plane, with distortion applied.
973
  The coordinates \f$(u, v)\f$ are measured in pixels from the top-left corner of the image.
974
975
The transformation chain is: World coordinates → Camera coordinates (via rvec/tvec) → Normalized camera coordinates
976
→ Distortion applied → Pixel coordinates (via cameraMatrix).
977
978
@param objectPoints Array of object points expressed wrt. the world coordinate frame. A 3xN/Nx3
979
1-channel or 1xN/Nx1 3-channel (or vector\<Point3f\> ), where N is the number of points in the view.
980
@param rvec The rotation vector (@ref Rodrigues) that, together with tvec, performs a change of
981
basis from world to camera coordinate system, see @ref calibrateCamera for details.
982
@param tvec The translation vector, see parameter description above.
983
@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
984
@param distCoeffs Input vector of distortion coefficients
985
\f$\distcoeffs\f$ . If the vector is empty, the zero distortion coefficients are assumed.
986
@param imagePoints Output array of image points in **pixel coordinates**, 1xN/Nx1 2-channel, or
987
vector\<Point2f\> .
988
@param jacobian Optional output 2Nx(10+\<numDistCoeffs\>) jacobian matrix of derivatives of image
989
points with respect to components of the rotation vector, translation vector, focal lengths,
990
coordinates of the principal point and the distortion coefficients. In the old interface different
991
components of the jacobian are returned via different output parameters.
992
@param aspectRatio Optional "fixed aspect ratio" parameter. If the parameter is not 0, the
993
function assumes that the aspect ratio (\f$f_x / f_y\f$) is fixed and correspondingly adjusts the
994
jacobian matrix.
995
996
@note By setting rvec = tvec = \f$[0, 0, 0]\f$, or by setting cameraMatrix to a 3x3 identity matrix,
997
or by passing zero distortion coefficients, one can get various useful partial cases of the
998
function. This means, one can compute the distorted coordinates for a sparse set of points or apply
999
a perspective transformation (and also compute the derivatives) in the ideal zero-distortion setup.
1000
 */
1001
CV_EXPORTS_W void projectPoints( InputArray objectPoints,
1002
                                 InputArray rvec, InputArray tvec,
1003
                                 InputArray cameraMatrix, InputArray distCoeffs,
1004
                                 OutputArray imagePoints,
1005
                                 OutputArray jacobian = noArray(),
1006
                                 double aspectRatio = 0 );
1007
1008
/** @example samples/cpp/tutorial_code/features2D/Homography/homography_from_camera_displacement.cpp
1009
An example program about homography from the camera displacement
1010
1011
Check @ref tutorial_homography "the corresponding tutorial" for more details
1012
*/
1013
1014
/** @brief Finds an object pose \f$ {}^{c}\mathbf{T}_o \f$ from 3D-2D point correspondences:
1015
1016
![Perspective projection, from object to camera frame](pics/pinhole_homogeneous_transformation.jpg){ width=50% }
1017
1018
@see @ref calib3d_solvePnP
1019
1020
This function returns the rotation and the translation vectors that transform a 3D point expressed in the object
1021
coordinate frame to the camera coordinate frame, using different methods:
1022
- P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): need 4 input points to return a unique solution.
1023
- @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar.
1024
- @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation.
1025
Number of input points must be 4. Object points must be defined in the following order:
1026
  - point 0: [-squareLength / 2,  squareLength / 2, 0]
1027
  - point 1: [ squareLength / 2,  squareLength / 2, 0]
1028
  - point 2: [ squareLength / 2, -squareLength / 2, 0]
1029
  - point 3: [-squareLength / 2, -squareLength / 2, 0]
1030
- for all the other flags, number of input points must be >= 4 and object points can be in any configuration.
1031
1032
@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or
1033
1xN/Nx1 3-channel, where N is the number of points. vector\<Point3d\> can be also passed here.
1034
@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
1035
where N is the number of points. vector\<Point2d\> can be also passed here.
1036
@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
1037
@param distCoeffs Input vector of distortion coefficients
1038
\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
1039
assumed.
1040
@param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
1041
the model coordinate system to the camera coordinate system.
1042
@param tvec Output translation vector.
1043
@param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses
1044
the provided rvec and tvec values as initial approximations of the rotation and translation
1045
vectors, respectively, and further optimizes them.
1046
@param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags
1047
1048
More information about Perspective-n-Points is described in @ref calib3d_solvePnP
1049
1050
@note
1051
   -   An example of how to use solvePnP for planar augmented reality can be found at
1052
        opencv_source_code/samples/python/plane_ar.py
1053
   -   If you are using Python:
1054
        - Numpy array slices won't work as input because solvePnP requires contiguous
1055
        arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of
1056
        modules/calib3d/src/solvepnp.cpp version 2.4.9)
1057
        - The P3P algorithm requires image points to be in an array of shape (N,1,2) due
1058
        to its calling of #undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9)
1059
        which requires 2-channel information.
1060
        - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of
1061
        it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints =
1062
        np.ascontiguousarray(D[:,:2]).reshape((N,1,2))
1063
   -   The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are
1064
       unstable and sometimes give completely wrong results. If you pass one of these two
1065
       flags, @ref SOLVEPNP_EPNP method will be used instead.
1066
   -   The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P
1067
       methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions
1068
       of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error).
1069
   -   With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points
1070
       are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the
1071
       global solution to converge. The function returns true if some solution is found. User code is responsible for
1072
       solution quality assessment.
1073
   -   With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar.
1074
   -   With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation.
1075
       Number of input points must be 4. Object points must be defined in the following order:
1076
         - point 0: [-squareLength / 2,  squareLength / 2, 0]
1077
         - point 1: [ squareLength / 2,  squareLength / 2, 0]
1078
         - point 2: [ squareLength / 2, -squareLength / 2, 0]
1079
         - point 3: [-squareLength / 2, -squareLength / 2, 0]
1080
   -   With @ref SOLVEPNP_SQPNP input points must be >= 3
1081
 */
1082
CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints,
1083
                            InputArray cameraMatrix, InputArray distCoeffs,
1084
                            OutputArray rvec, OutputArray tvec,
1085
                            bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE );
1086
1087
/** @brief Finds an object pose \f$ {}^{c}\mathbf{T}_o \f$ from 3D-2D point correspondences using the RANSAC scheme to deal with bad matches.
1088
1089
![Perspective projection, from object to camera frame](pics/pinhole_homogeneous_transformation.jpg){ width=50% }
1090
1091
@see @ref calib3d_solvePnP
1092
1093
@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or
1094
1xN/Nx1 3-channel, where N is the number of points. vector\<Point3d\> can be also passed here.
1095
@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
1096
where N is the number of points. vector\<Point2d\> can be also passed here.
1097
@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
1098
@param distCoeffs Input vector of distortion coefficients
1099
\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
1100
assumed.
1101
@param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
1102
the model coordinate system to the camera coordinate system.
1103
@param tvec Output translation vector.
1104
@param useExtrinsicGuess Parameter used for @ref SOLVEPNP_ITERATIVE. If true (1), the function uses
1105
the provided rvec and tvec values as initial approximations of the rotation and translation
1106
vectors, respectively, and further optimizes them.
1107
@param iterationsCount Number of iterations.
1108
@param reprojectionError Inlier threshold value used by the RANSAC procedure. The parameter value
1109
is the maximum allowed distance between the observed and computed point projections to consider it
1110
an inlier.
1111
@param confidence The probability that the algorithm produces a useful result.
1112
@param inliers Output vector that contains indices of inliers in objectPoints and imagePoints .
1113
@param flags Method for solving a PnP problem (see @ref solvePnP ).
1114
1115
The function estimates an object pose given a set of object points, their corresponding image
1116
projections, as well as the camera intrinsic matrix and the distortion coefficients. This function finds such
1117
a pose that minimizes reprojection error, that is, the sum of squared distances between the observed
1118
projections imagePoints and the projected (using @ref projectPoints ) objectPoints. The use of RANSAC
1119
makes the function resistant to outliers.
1120
1121
@note
1122
   -   An example of how to use solvePnPRansac for object detection can be found at
1123
        @ref tutorial_real_time_pose
1124
   -   The default method used to estimate the camera pose for the Minimal Sample Sets step
1125
       is #SOLVEPNP_EPNP. Exceptions are:
1126
         - if you choose #SOLVEPNP_P3P or #SOLVEPNP_AP3P, these methods will be used.
1127
         - if the number of input points is equal to 4, #SOLVEPNP_P3P is used.
1128
   -   The method used to estimate the camera pose using all the inliers is defined by the
1129
       flags parameters unless it is equal to #SOLVEPNP_P3P or #SOLVEPNP_AP3P. In this case,
1130
       the method #SOLVEPNP_EPNP will be used instead.
1131
 */
1132
CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints,
1133
                                  InputArray cameraMatrix, InputArray distCoeffs,
1134
                                  OutputArray rvec, OutputArray tvec,
1135
                                  bool useExtrinsicGuess = false, int iterationsCount = 100,
1136
                                  float reprojectionError = 8.0, double confidence = 0.99,
1137
                                  OutputArray inliers = noArray(), int flags = SOLVEPNP_ITERATIVE );
1138
1139
1140
/*
1141
Finds rotation and translation vector.
1142
If cameraMatrix is given then run P3P. Otherwise run linear P6P and output cameraMatrix too.
1143
*/
1144
CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints,
1145
                     InputOutputArray cameraMatrix, InputArray distCoeffs,
1146
                     OutputArray rvec, OutputArray tvec, OutputArray inliers,
1147
                     const UsacParams &params=UsacParams());
1148
1149
/** @brief Finds an object pose \f$ {}^{c}\mathbf{T}_o \f$ from **3** 3D-2D point correspondences.
1150
1151
![Perspective projection, from object to camera frame](pics/pinhole_homogeneous_transformation.jpg){ width=50% }
1152
1153
@see @ref calib3d_solvePnP
1154
1155
@param objectPoints Array of object points in the object coordinate space, 3x3 1-channel or
1156
1x3/3x1 3-channel. vector\<Point3f\> can be also passed here.
1157
@param imagePoints Array of corresponding image points, 3x2 1-channel or 1x3/3x1 2-channel.
1158
 vector\<Point2f\> can be also passed here.
1159
@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
1160
@param distCoeffs Input vector of distortion coefficients
1161
\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
1162
assumed.
1163
@param rvecs Output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from
1164
the model coordinate system to the camera coordinate system. A P3P problem has up to 4 solutions.
1165
@param tvecs Output translation vectors.
1166
@param flags Method for solving a P3P problem:
1167
-   @ref SOLVEPNP_P3P Method is based on the paper of Ding, Y., Yang, J., Larsson, V., Olsson, C., & â„«strom, K.
1168
"Revisiting the P3P Problem" (@cite ding2023revisiting).
1169
-   @ref SOLVEPNP_AP3P Method is based on the paper of T. Ke and S. Roumeliotis.
1170
"An Efficient Algebraic Solution to the Perspective-Three-Point Problem" (@cite Ke17).
1171
1172
The function estimates the object pose given 3 object points, their corresponding image
1173
projections, as well as the camera intrinsic matrix and the distortion coefficients.
1174
1175
@note
1176
The solutions are sorted by reprojection errors (lowest to highest).
1177
 */
1178
CV_EXPORTS_W int solveP3P( InputArray objectPoints, InputArray imagePoints,
1179
                           InputArray cameraMatrix, InputArray distCoeffs,
1180
                           OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
1181
                           int flags );
1182
1183
/** @brief Refine a pose (the translation and the rotation that transform a 3D point expressed in the object coordinate frame
1184
to the camera coordinate frame) from a 3D-2D point correspondences and starting from an initial solution.
1185
1186
@see @ref calib3d_solvePnP
1187
1188
@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or 1xN/Nx1 3-channel,
1189
where N is the number of points. vector\<Point3d\> can also be passed here.
1190
@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
1191
where N is the number of points. vector\<Point2d\> can also be passed here.
1192
@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
1193
@param distCoeffs Input vector of distortion coefficients
1194
\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
1195
assumed.
1196
@param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
1197
the model coordinate system to the camera coordinate system. Input values are used as an initial solution.
1198
@param tvec Input/Output translation vector. Input values are used as an initial solution.
1199
@param criteria Criteria when to stop the Levenberg-Marquard iterative algorithm.
1200
1201
The function refines the object pose given at least 3 object points, their corresponding image
1202
projections, an initial solution for the rotation and translation vector,
1203
as well as the camera intrinsic matrix and the distortion coefficients.
1204
The function minimizes the projection error with respect to the rotation and the translation vectors, according
1205
to a Levenberg-Marquardt iterative minimization @cite Madsen04 @cite Eade13 process.
1206
 */
1207
CV_EXPORTS_W void solvePnPRefineLM( InputArray objectPoints, InputArray imagePoints,
1208
                                    InputArray cameraMatrix, InputArray distCoeffs,
1209
                                    InputOutputArray rvec, InputOutputArray tvec,
1210
                                    TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 20, FLT_EPSILON));
1211
1212
/** @brief Refine a pose (the translation and the rotation that transform a 3D point expressed in the object coordinate frame
1213
to the camera coordinate frame) from a 3D-2D point correspondences and starting from an initial solution.
1214
1215
@see @ref calib3d_solvePnP
1216
1217
@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or 1xN/Nx1 3-channel,
1218
where N is the number of points. vector\<Point3d\> can also be passed here.
1219
@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
1220
where N is the number of points. vector\<Point2d\> can also be passed here.
1221
@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
1222
@param distCoeffs Input vector of distortion coefficients
1223
\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
1224
assumed.
1225
@param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
1226
the model coordinate system to the camera coordinate system. Input values are used as an initial solution.
1227
@param tvec Input/Output translation vector. Input values are used as an initial solution.
1228
@param criteria Criteria when to stop the Levenberg-Marquard iterative algorithm.
1229
@param VVSlambda Gain for the virtual visual servoing control law, equivalent to the \f$\alpha\f$
1230
gain in the Damped Gauss-Newton formulation.
1231
1232
The function refines the object pose given at least 3 object points, their corresponding image
1233
projections, an initial solution for the rotation and translation vector,
1234
as well as the camera intrinsic matrix and the distortion coefficients.
1235
The function minimizes the projection error with respect to the rotation and the translation vectors, using a
1236
virtual visual servoing (VVS) @cite Chaumette06 @cite Marchand16 scheme.
1237
 */
1238
CV_EXPORTS_W void solvePnPRefineVVS( InputArray objectPoints, InputArray imagePoints,
1239
                                     InputArray cameraMatrix, InputArray distCoeffs,
1240
                                     InputOutputArray rvec, InputOutputArray tvec,
1241
                                     TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 20, FLT_EPSILON),
1242
                                     double VVSlambda = 1);
1243
1244
/** @brief Finds an object pose \f$ {}^{c}\mathbf{T}_o \f$ from 3D-2D point correspondences.
1245
1246
![Perspective projection, from object to camera frame](pics/pinhole_homogeneous_transformation.jpg){ width=50% }
1247
1248
@see @ref calib3d_solvePnP
1249
1250
This function returns a list of all the possible solutions (a solution is a <rotation vector, translation vector>
1251
couple), depending on the number of input points and the chosen method:
1252
- P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): 3 or 4 input points. Number of returned solutions can be between 0 and 4 with 3 input points.
1253
- @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. Returns 2 solutions.
1254
- @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation.
1255
Number of input points must be 4 and 2 solutions are returned. Object points must be defined in the following order:
1256
  - point 0: [-squareLength / 2,  squareLength / 2, 0]
1257
  - point 1: [ squareLength / 2,  squareLength / 2, 0]
1258
  - point 2: [ squareLength / 2, -squareLength / 2, 0]
1259
  - point 3: [-squareLength / 2, -squareLength / 2, 0]
1260
- for all the other flags, number of input points must be >= 4 and object points can be in any configuration.
1261
Only 1 solution is returned.
1262
1263
@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or
1264
1xN/Nx1 3-channel, where N is the number of points. vector\<Point3d\> can be also passed here.
1265
@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
1266
where N is the number of points. vector\<Point2d\> can be also passed here.
1267
@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
1268
@param distCoeffs Input vector of distortion coefficients
1269
\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
1270
assumed.
1271
@param rvecs Vector of output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from
1272
the model coordinate system to the camera coordinate system.
1273
@param tvecs Vector of output translation vectors.
1274
@param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses
1275
the provided rvec and tvec values as initial approximations of the rotation and translation
1276
vectors, respectively, and further optimizes them.
1277
@param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags
1278
@param rvec Rotation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE
1279
and useExtrinsicGuess is set to true.
1280
@param tvec Translation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE
1281
and useExtrinsicGuess is set to true.
1282
@param reprojectionError Optional vector of reprojection error, that is the RMS error
1283
(\f$ \text{RMSE} = \sqrt{\frac{\sum_{i}^{N} \left ( \hat{y_i} - y_i \right )^2}{N}} \f$) between the input image points
1284
and the 3D object points projected with the estimated pose.
1285
1286
More information is described in @ref calib3d_solvePnP
1287
1288
@note
1289
   -   An example of how to use solvePnP for planar augmented reality can be found at
1290
        opencv_source_code/samples/python/plane_ar.py
1291
   -   If you are using Python:
1292
        - Numpy array slices won't work as input because solvePnP requires contiguous
1293
        arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of
1294
        modules/calib3d/src/solvepnp.cpp version 2.4.9)
1295
        - The P3P algorithm requires image points to be in an array of shape (N,1,2) due
1296
        to its calling of #undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9)
1297
        which requires 2-channel information.
1298
        - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of
1299
        it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints =
1300
        np.ascontiguousarray(D[:,:2]).reshape((N,1,2))
1301
   -   The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are
1302
       unstable and sometimes give completely wrong results. If you pass one of these two
1303
       flags, @ref SOLVEPNP_EPNP method will be used instead.
1304
   -   The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P
1305
       methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions
1306
       of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error).
1307
   -   With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points
1308
       are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the
1309
       global solution to converge.
1310
   -   With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar.
1311
   -   With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation.
1312
       Number of input points must be 4. Object points must be defined in the following order:
1313
         - point 0: [-squareLength / 2,  squareLength / 2, 0]
1314
         - point 1: [ squareLength / 2,  squareLength / 2, 0]
1315
         - point 2: [ squareLength / 2, -squareLength / 2, 0]
1316
         - point 3: [-squareLength / 2, -squareLength / 2, 0]
1317
   -   With @ref SOLVEPNP_SQPNP input points must be >= 3
1318
 */
1319
CV_EXPORTS_W int solvePnPGeneric( InputArray objectPoints, InputArray imagePoints,
1320
                                  InputArray cameraMatrix, InputArray distCoeffs,
1321
                                  OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
1322
                                  bool useExtrinsicGuess = false, SolvePnPMethod flags = SOLVEPNP_ITERATIVE,
1323
                                  InputArray rvec = noArray(), InputArray tvec = noArray(),
1324
                                  OutputArray reprojectionError = noArray() );
1325
1326
/** @brief Finds an initial camera intrinsic matrix from 3D-2D point correspondences.
1327
1328
@param objectPoints Vector of vectors of the calibration pattern points in the calibration pattern
1329
coordinate space. In the old interface all the per-view vectors are concatenated. See
1330
#calibrateCamera for details.
1331
@param imagePoints Vector of vectors of the projections of the calibration pattern points. In the
1332
old interface all the per-view vectors are concatenated.
1333
@param imageSize Image size in pixels used to initialize the principal point.
1334
@param aspectRatio If it is zero or negative, both \f$f_x\f$ and \f$f_y\f$ are estimated independently.
1335
Otherwise, \f$f_x = f_y \cdot \texttt{aspectRatio}\f$ .
1336
1337
The function estimates and returns an initial camera intrinsic matrix for the camera calibration process.
1338
Currently, the function only supports planar calibration patterns, which are patterns where each
1339
object point has z-coordinate =0.
1340
 */
1341
CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints,
1342
                                     InputArrayOfArrays imagePoints,
1343
                                     Size imageSize, double aspectRatio = 1.0 );
1344
1345
/** @brief Finds the positions of internal corners of the chessboard.
1346
1347
@param image Source chessboard view. It must be an 8-bit grayscale or color image.
1348
@param patternSize Number of inner corners per a chessboard row and column
1349
( patternSize = cv::Size(points_per_row,points_per_column) = cv::Size(columns,rows) ).
1350
@param corners Output array of detected corners.
1351
@param flags Various operation flags that can be zero or a combination of the following values:
1352
-   @ref CALIB_CB_ADAPTIVE_THRESH Use adaptive thresholding to convert the image to black
1353
and white, rather than a fixed threshold level (computed from the average image brightness).
1354
-   @ref CALIB_CB_NORMALIZE_IMAGE Normalize the image gamma with #equalizeHist before
1355
applying fixed or adaptive thresholding.
1356
-   @ref CALIB_CB_FILTER_QUADS Use additional criteria (like contour area, perimeter,
1357
square-like shape) to filter out false quads extracted at the contour retrieval stage.
1358
-   @ref CALIB_CB_FAST_CHECK Run a fast check on the image that looks for chessboard corners,
1359
and shortcut the call if none is found. This can drastically speed up the call in the
1360
degenerate condition when no chessboard is observed.
1361
-   @ref CALIB_CB_PLAIN All other flags are ignored. The input image is taken as is.
1362
No image processing is done to improve to find the checkerboard. This has the effect of speeding up the
1363
execution of the function but could lead to not recognizing the checkerboard if the image
1364
is not previously binarized in the appropriate manner.
1365
1366
The function attempts to determine whether the input image is a view of the chessboard pattern and
1367
locate the internal chessboard corners. The function returns a non-zero value if all of the corners
1368
are found and they are placed in a certain order (row by row, left to right in every row).
1369
Otherwise, if the function fails to find all the corners or reorder them, it returns 0. For example,
1370
a regular chessboard has 8 x 8 squares and 7 x 7 internal corners, that is, points where the black
1371
squares touch each other. The detected coordinates are approximate, and to determine their positions
1372
more accurately, the function calls #cornerSubPix. You also may use the function #cornerSubPix with
1373
different parameters if returned coordinates are not accurate enough.
1374
1375
Sample usage of detecting and drawing chessboard corners: :
1376
@code
1377
    Size patternsize(8,6); //interior number of corners
1378
    Mat gray = ....; //source image
1379
    vector<Point2f> corners; //this will be filled by the detected corners
1380
1381
    //CALIB_CB_FAST_CHECK saves a lot of time on images
1382
    //that do not contain any chessboard corners
1383
    bool patternfound = findChessboardCorners(gray, patternsize, corners,
1384
            CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE
1385
            + CALIB_CB_FAST_CHECK);
1386
1387
    if(patternfound)
1388
      cornerSubPix(gray, corners, Size(11, 11), Size(-1, -1),
1389
        TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1));
1390
1391
    drawChessboardCorners(img, patternsize, Mat(corners), patternfound);
1392
@endcode
1393
@note The function requires white space (like a square-thick border, the wider the better) around
1394
the board to make the detection more robust in various environments. Otherwise, if there is no
1395
border and the background is dark, the outer black squares cannot be segmented properly and so the
1396
square grouping and ordering algorithm fails.
1397
1398
Use the `generate_pattern.py` Python script (@ref tutorial_camera_calibration_pattern)
1399
to create the desired checkerboard pattern.
1400
 */
1401
CV_EXPORTS_W bool findChessboardCorners( InputArray image, Size patternSize, OutputArray corners,
1402
                                         int flags = CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE );
1403
1404
/*
1405
   Checks whether the image contains chessboard of the specific size or not.
1406
   If yes, nonzero value is returned.
1407
*/
1408
CV_EXPORTS_W bool checkChessboard(InputArray img, Size size);
1409
1410
/** @brief Finds the positions of internal corners of the chessboard using a sector based approach.
1411
1412
@param image Source chessboard view. It must be an 8-bit grayscale or color image.
1413
@param patternSize Number of inner corners per a chessboard row and column
1414
( patternSize = cv::Size(points_per_row,points_per_column) = cv::Size(columns,rows) ).
1415
@param corners Output array of detected corners.
1416
@param flags Various operation flags that can be zero or a combination of the following values:
1417
-   @ref CALIB_CB_NORMALIZE_IMAGE Normalize the image gamma with equalizeHist before detection.
1418
-   @ref CALIB_CB_EXHAUSTIVE Run an exhaustive search to improve detection rate.
1419
-   @ref CALIB_CB_ACCURACY Up sample input image to improve sub-pixel accuracy due to aliasing effects.
1420
-   @ref CALIB_CB_LARGER The detected pattern is allowed to be larger than patternSize (see description).
1421
-   @ref CALIB_CB_MARKER The detected pattern must have a marker (see description).
1422
This should be used if an accurate camera calibration is required.
1423
@param meta Optional output array of detected corners (CV_8UC1 and size = cv::Size(columns,rows)).
1424
Each entry stands for one corner of the pattern and can have one of the following values:
1425
-   0 = no meta data attached
1426
-   1 = left-top corner of a black cell
1427
-   2 = left-top corner of a white cell
1428
-   3 = left-top corner of a black cell with a white marker dot
1429
-   4 = left-top corner of a white cell with a black marker dot (pattern origin in case of markers otherwise first corner)
1430
1431
The function is analog to #findChessboardCorners but uses a localized radon
1432
transformation approximated by box filters being more robust to all sort of
1433
noise, faster on larger images and is able to directly return the sub-pixel
1434
position of the internal chessboard corners. The Method is based on the paper
1435
@cite duda2018 "Accurate Detection and Localization of Checkerboard Corners for
1436
Calibration" demonstrating that the returned sub-pixel positions are more
1437
accurate than the one returned by cornerSubPix allowing a precise camera
1438
calibration for demanding applications.
1439
1440
In the case, the flags @ref CALIB_CB_LARGER or @ref CALIB_CB_MARKER are given,
1441
the result can be recovered from the optional meta array. Both flags are
1442
helpful to use calibration patterns exceeding the field of view of the camera.
1443
These oversized patterns allow more accurate calibrations as corners can be
1444
utilized, which are as close as possible to the image borders.  For a
1445
consistent coordinate system across all images, the optional marker (see image
1446
below) can be used to move the origin of the board to the location where the
1447
black circle is located.
1448
1449
@note The function requires a white boarder with roughly the same width as one
1450
of the checkerboard fields around the whole board to improve the detection in
1451
various environments. In addition, because of the localized radon
1452
transformation it is beneficial to use round corners for the field corners
1453
which are located on the outside of the board. The following figure illustrates
1454
a sample checkerboard optimized for the detection. However, any other checkerboard
1455
can be used as well.
1456
1457
Use the `generate_pattern.py` Python script (@ref tutorial_camera_calibration_pattern)
1458
to create the corresponding checkerboard pattern:
1459
\image html pics/checkerboard_radon.png width=60%
1460
 */
1461
CV_EXPORTS_AS(findChessboardCornersSBWithMeta)
1462
bool findChessboardCornersSB(InputArray image,Size patternSize, OutputArray corners,
1463
                             int flags,OutputArray meta);
1464
/** @overload */
1465
CV_EXPORTS_W inline
1466
bool findChessboardCornersSB(InputArray image, Size patternSize, OutputArray corners,
1467
                             int flags = 0)
1468
0
{
1469
0
    return findChessboardCornersSB(image, patternSize, corners, flags, noArray());
1470
0
}
1471
1472
/** @brief Estimates the sharpness of a detected chessboard.
1473
1474
Image sharpness, as well as brightness, are a critical parameter for accuracte
1475
camera calibration. For accessing these parameters for filtering out
1476
problematic calibraiton images, this method calculates edge profiles by traveling from
1477
black to white chessboard cell centers. Based on this, the number of pixels is
1478
calculated required to transit from black to white. This width of the
1479
transition area is a good indication of how sharp the chessboard is imaged
1480
and should be below ~3.0 pixels.
1481
1482
@param image Gray image used to find chessboard corners
1483
@param patternSize Size of a found chessboard pattern
1484
@param corners Corners found by #findChessboardCornersSB
1485
@param rise_distance Rise distance 0.8 means 10% ... 90% of the final signal strength
1486
@param vertical By default edge responses for horizontal lines are calculated
1487
@param sharpness Optional output array with a sharpness value for calculated edge responses (see description)
1488
1489
The optional sharpness array is of type CV_32FC1 and has for each calculated
1490
profile one row with the following five entries:
1491
* 0 = x coordinate of the underlying edge in the image
1492
* 1 = y coordinate of the underlying edge in the image
1493
* 2 = width of the transition area (sharpness)
1494
* 3 = signal strength in the black cell (min brightness)
1495
* 4 = signal strength in the white cell (max brightness)
1496
1497
@return Scalar(average sharpness, average min brightness, average max brightness,0)
1498
*/
1499
CV_EXPORTS_W Scalar estimateChessboardSharpness(InputArray image, Size patternSize, InputArray corners,
1500
                                                float rise_distance=0.8F,bool vertical=false,
1501
                                                OutputArray sharpness=noArray());
1502
1503
1504
//! finds subpixel-accurate positions of the chessboard corners
1505
CV_EXPORTS_W bool find4QuadCornerSubpix( InputArray img, InputOutputArray corners, Size region_size );
1506
1507
/** @brief Renders the detected chessboard corners.
1508
1509
@param image Destination image. It must be an 8-bit color image.
1510
@param patternSize Number of inner corners per a chessboard row and column
1511
(patternSize = cv::Size(points_per_row,points_per_column)).
1512
@param corners Array of detected corners, the output of #findChessboardCorners.
1513
@param patternWasFound Parameter indicating whether the complete board was found or not. The
1514
return value of #findChessboardCorners should be passed here.
1515
1516
The function draws individual chessboard corners detected either as red circles if the board was not
1517
found, or as colored corners connected with lines if the board was found.
1518
 */
1519
CV_EXPORTS_W void drawChessboardCorners( InputOutputArray image, Size patternSize,
1520
                                         InputArray corners, bool patternWasFound );
1521
1522
/** @brief Draw axes of the world/object coordinate system from pose estimation. @sa solvePnP
1523
1524
@param image Input/output image. It must have 1 or 3 channels. The number of channels is not altered.
1525
@param cameraMatrix Input 3x3 floating-point matrix of camera intrinsic parameters.
1526
\f$\cameramatrix{A}\f$
1527
@param distCoeffs Input vector of distortion coefficients
1528
\f$\distcoeffs\f$. If the vector is empty, the zero distortion coefficients are assumed.
1529
@param rvec Rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
1530
the model coordinate system to the camera coordinate system.
1531
@param tvec Translation vector.
1532
@param length Length of the painted axes in the same unit than tvec (usually in meters).
1533
@param thickness Line thickness of the painted axes.
1534
1535
This function draws the axes of the world/object coordinate system w.r.t. to the camera frame.
1536
OX is drawn in red, OY in green and OZ in blue.
1537
 */
1538
CV_EXPORTS_W void drawFrameAxes(InputOutputArray image, InputArray cameraMatrix, InputArray distCoeffs,
1539
                                InputArray rvec, InputArray tvec, float length, int thickness=3);
1540
1541
struct CV_EXPORTS_W_SIMPLE CirclesGridFinderParameters
1542
{
1543
    CV_WRAP CirclesGridFinderParameters();
1544
    CV_PROP_RW cv::Size2f densityNeighborhoodSize;
1545
    CV_PROP_RW float minDensity;
1546
    CV_PROP_RW int kmeansAttempts;
1547
    CV_PROP_RW int minDistanceToAddKeypoint;
1548
    CV_PROP_RW int keypointScale;
1549
    CV_PROP_RW float minGraphConfidence;
1550
    CV_PROP_RW float vertexGain;
1551
    CV_PROP_RW float vertexPenalty;
1552
    CV_PROP_RW float existingVertexGain;
1553
    CV_PROP_RW float edgeGain;
1554
    CV_PROP_RW float edgePenalty;
1555
    CV_PROP_RW float convexHullFactor;
1556
    CV_PROP_RW float minRNGEdgeSwitchDist;
1557
1558
    enum GridType
1559
    {
1560
      SYMMETRIC_GRID, ASYMMETRIC_GRID
1561
    };
1562
    CV_PROP_RW GridType gridType;
1563
1564
    CV_PROP_RW float squareSize; //!< Distance between two adjacent points. Used by CALIB_CB_CLUSTERING.
1565
    CV_PROP_RW float maxRectifiedDistance; //!< Max deviation from prediction. Used by CALIB_CB_CLUSTERING.
1566
};
1567
1568
#ifndef DISABLE_OPENCV_3_COMPATIBILITY
1569
typedef CirclesGridFinderParameters CirclesGridFinderParameters2;
1570
#endif
1571
1572
/** @brief Finds centers in the grid of circles.
1573
1574
@param image grid view of input circles; it must be an 8-bit grayscale or color image.
1575
@param patternSize number of circles per row and column
1576
( patternSize = Size(points_per_row, points_per_column) ).
1577
@param centers output array of detected centers.
1578
@param flags various operation flags that can be one of the following values:
1579
-   @ref CALIB_CB_SYMMETRIC_GRID uses symmetric pattern of circles.
1580
-   @ref CALIB_CB_ASYMMETRIC_GRID uses asymmetric pattern of circles.
1581
-   @ref CALIB_CB_CLUSTERING uses a special algorithm for grid detection. It is more robust to
1582
perspective distortions but much more sensitive to background clutter.
1583
@param blobDetector feature detector that finds blobs like dark circles on light background.
1584
                    If `blobDetector` is NULL then `image` represents Point2f array of candidates.
1585
@param parameters struct for finding circles in a grid pattern.
1586
1587
The function attempts to determine whether the input image contains a grid of circles. If it is, the
1588
function locates centers of the circles. The function returns a non-zero value if all of the centers
1589
have been found and they have been placed in a certain order (row by row, left to right in every
1590
row). Otherwise, if the function fails to find all the corners or reorder them, it returns 0.
1591
1592
Sample usage of detecting and drawing the centers of circles: :
1593
@code
1594
    Size patternsize(7,7); //number of centers
1595
    Mat gray = ...; //source image
1596
    vector<Point2f> centers; //this will be filled by the detected centers
1597
1598
    bool patternfound = findCirclesGrid(gray, patternsize, centers);
1599
1600
    drawChessboardCorners(img, patternsize, Mat(centers), patternfound);
1601
@endcode
1602
@note The function requires white space (like a square-thick border, the wider the better) around
1603
the board to make the detection more robust in various environments.
1604
 */
1605
CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize,
1606
                                   OutputArray centers, int flags,
1607
                                   const Ptr<FeatureDetector> &blobDetector,
1608
                                   const CirclesGridFinderParameters& parameters);
1609
1610
/** @overload */
1611
CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize,
1612
                                   OutputArray centers, int flags = CALIB_CB_SYMMETRIC_GRID,
1613
                                   const Ptr<FeatureDetector> &blobDetector = SimpleBlobDetector::create());
1614
1615
/** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration
1616
pattern.
1617
1618
@param objectPoints In the new interface it is a vector of vectors of calibration pattern points in
1619
the calibration pattern coordinate space (e.g. std::vector<std::vector<cv::Vec3f>>). The outer
1620
vector contains as many elements as the number of pattern views. If the same calibration pattern
1621
is shown in each view and it is fully visible, all the vectors will be the same. Although, it is
1622
possible to use partially occluded patterns or even different patterns in different views. Then,
1623
the vectors will be different. Although the points are 3D, they all lie in the calibration pattern's
1624
XY coordinate plane (thus 0 in the Z-coordinate), if the used calibration pattern is a planar rig.
1625
In the old interface all the vectors of object points from different views are concatenated
1626
together.
1627
@param imagePoints In the new interface it is a vector of vectors of the projections of calibration
1628
pattern points (e.g. std::vector<std::vector<cv::Vec2f>>). imagePoints.size() and
1629
objectPoints.size(), and imagePoints[i].size() and objectPoints[i].size() for each i, must be equal,
1630
respectively. In the old interface all the vectors of object points from different views are
1631
concatenated together.
1632
@param imageSize Size of the image used only to initialize the camera intrinsic matrix.
1633
@param cameraMatrix Input/output 3x3 floating-point camera intrinsic matrix
1634
\f$\cameramatrix{A}\f$ . If @ref CALIB_USE_INTRINSIC_GUESS
1635
and/or @ref CALIB_FIX_ASPECT_RATIO, @ref CALIB_FIX_PRINCIPAL_POINT or @ref CALIB_FIX_FOCAL_LENGTH
1636
are specified, some or all of fx, fy, cx, cy must be initialized before calling the function.
1637
@param distCoeffs Input/output vector of distortion coefficients
1638
\f$\distcoeffs\f$.
1639
@param rvecs Output vector of rotation vectors (@ref Rodrigues ) estimated for each pattern view
1640
(e.g. std::vector<cv::Mat>>). That is, each i-th rotation vector together with the corresponding
1641
i-th translation vector (see the next output parameter description) brings the calibration pattern
1642
from the object coordinate space (in which object points are specified) to the camera coordinate
1643
space. In more technical terms, the tuple of the i-th rotation and translation vector performs
1644
a change of basis from object coordinate space to camera coordinate space. Due to its duality, this
1645
tuple is equivalent to the position of the calibration pattern with respect to the camera coordinate
1646
space.
1647
@param tvecs Output vector of translation vectors estimated for each pattern view, see parameter
1648
describtion above.
1649
@param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic
1650
parameters. Order of deviations values:
1651
\f$(f_x, f_y, c_x, c_y, k_1, k_2, p_1, p_2, k_3, k_4, k_5, k_6 , s_1, s_2, s_3,
1652
 s_4, \tau_x, \tau_y)\f$ If one of parameters is not estimated, it's deviation is equals to zero.
1653
@param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic
1654
parameters. Order of deviations values: \f$(R_0, T_0, \dotsc , R_{M - 1}, T_{M - 1})\f$ where M is
1655
the number of pattern views. \f$R_i, T_i\f$ are concatenated 1x3 vectors.
1656
 @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view.
1657
@param flags Different flags that may be zero or a combination of the following values:
1658
-   @ref CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of
1659
fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image
1660
center ( imageSize is used), and focal distances are computed in a least-squares fashion.
1661
Note, that if intrinsic parameters are known, there is no need to use this function just to
1662
estimate extrinsic parameters. Use @ref solvePnP instead.
1663
-   @ref CALIB_DISABLE_SCHUR_COMPLEMENT Disable Schur complement and use the Bouguet calibration engine (@cite Zhang2000, @cite BouguetMCT).
1664
-   @ref CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global
1665
optimization. It stays at the center or at a different location specified when
1666
 @ref CALIB_USE_INTRINSIC_GUESS is set too.
1667
-   @ref CALIB_FIX_ASPECT_RATIO The functions consider only fy as a free parameter. The
1668
ratio fx/fy stays the same as in the input cameraMatrix . When
1669
 @ref CALIB_USE_INTRINSIC_GUESS is not set, the actual input values of fx and fy are
1670
ignored, only their ratio is computed and used further.
1671
-   @ref CALIB_ZERO_TANGENT_DIST Tangential distortion coefficients \f$(p_1, p_2)\f$ are set
1672
to zeros and stay zero.
1673
-   @ref CALIB_FIX_FOCAL_LENGTH The focal length is not changed during the global optimization if
1674
 @ref CALIB_USE_INTRINSIC_GUESS is set.
1675
-   @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 The corresponding radial distortion
1676
coefficient is not changed during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is
1677
set, the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0.
1678
-   @ref CALIB_RATIONAL_MODEL Coefficients k4, k5, and k6 are enabled. To provide the
1679
backward compatibility, this extra flag should be explicitly specified to make the
1680
calibration function use the rational model and return 8 coefficients or more.
1681
-   @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the
1682
backward compatibility, this extra flag should be explicitly specified to make the
1683
calibration function use the thin prism model and return 12 coefficients or more.
1684
-   @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during
1685
the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
1686
supplied distCoeffs matrix is used. Otherwise, it is set to 0.
1687
-   @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the
1688
backward compatibility, this extra flag should be explicitly specified to make the
1689
calibration function use the tilted sensor model and return 14 coefficients.
1690
-   @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during
1691
the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
1692
supplied distCoeffs matrix is used. Otherwise, it is set to 0.
1693
@param criteria Termination criteria for the iterative optimization algorithm.
1694
1695
@return the overall RMS re-projection error.
1696
1697
The function estimates the intrinsic camera parameters and extrinsic parameters for each of the
1698
views. By default, the optimization follows a sparse bundle adjustment formulation with Schur
1699
complement; see @cite Triggs2000_bundle_adjustment and @cite Lourakis2009_sba for background. Use
1700
@ref CALIB_DISABLE_SCHUR_COMPLEMENT to switch to the Bouguet calibration engine. The coordinates of 3D object
1701
points and their corresponding 2D projections in each view must be specified. That may be achieved
1702
by using an object with known geometry and easily detectable feature points. Such an object is
1703
called a calibration rig or calibration pattern, and OpenCV has built-in support for a chessboard as
1704
a calibration rig (see @ref findChessboardCorners). Currently, initialization of intrinsic
1705
parameters (when @ref CALIB_USE_INTRINSIC_GUESS is not set) is only implemented for planar calibration
1706
patterns (where Z-coordinates of the object points must be all zeros). 3D calibration rigs can also
1707
be used as long as initial cameraMatrix is provided.
1708
1709
The algorithm performs the following steps:
1710
1711
-   Compute the initial intrinsic parameters (the option only available for planar calibration
1712
    patterns) or read them from the input parameters. The distortion coefficients are all set to
1713
    zeros initially unless some of CALIB_FIX_K? are specified.
1714
1715
-   Estimate the initial camera pose as if the intrinsic parameters have been already known. This is
1716
    done using @ref solvePnP .
1717
1718
-   Run the global Levenberg-Marquardt optimization algorithm to minimize the reprojection error,
1719
    that is, the total sum of squared distances between the observed feature points imagePoints and
1720
    the projected (using the current estimates for camera parameters and the poses) object points
1721
    objectPoints. See @ref projectPoints for details.
1722
1723
-   In practice, robust acquisition is essential for stable results: use multiple board poses with
1724
    significant tilt, avoid collecting all views at a single working distance, span the expected
1725
    working-distance range (a larger board with larger squares can help for longer distances).
1726
1727
@note
1728
    If you use a non-square (i.e. non-N-by-N) grid and @ref findChessboardCorners for calibration,
1729
    and @ref calibrateCamera returns bad values (zero distortion coefficients, \f$c_x\f$ and
1730
    \f$c_y\f$ very far from the image center, and/or large differences between \f$f_x\f$ and
1731
    \f$f_y\f$ (ratios of 10:1 or more)), then you are probably using patternSize=cvSize(rows,cols)
1732
    instead of using patternSize=cvSize(cols,rows) in @ref findChessboardCorners.
1733
1734
@note
1735
    The function may throw exceptions, if unsupported combination of parameters is provided or
1736
    the system is underconstrained.
1737
1738
@sa
1739
   calibrateCameraRO, findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate,
1740
   undistort
1741
 */
1742
CV_EXPORTS_AS(calibrateCameraExtended) double calibrateCamera( InputArrayOfArrays objectPoints,
1743
                                     InputArrayOfArrays imagePoints, Size imageSize,
1744
                                     InputOutputArray cameraMatrix, InputOutputArray distCoeffs,
1745
                                     OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
1746
                                     OutputArray stdDeviationsIntrinsics,
1747
                                     OutputArray stdDeviationsExtrinsics,
1748
                                     OutputArray perViewErrors,
1749
                                     int flags = 0, TermCriteria criteria = TermCriteria(
1750
                                        TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) );
1751
1752
/** @overload */
1753
CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints,
1754
                                     InputArrayOfArrays imagePoints, Size imageSize,
1755
                                     InputOutputArray cameraMatrix, InputOutputArray distCoeffs,
1756
                                     OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
1757
                                     int flags = 0, TermCriteria criteria = TermCriteria(
1758
                                        TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) );
1759
1760
/** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration pattern.
1761
1762
This function is an extension of #calibrateCamera with the method of releasing object which was
1763
proposed in @cite strobl2011iccv. In many common cases with inaccurate, unmeasured, roughly planar
1764
targets (calibration plates), this method can dramatically improve the precision of the estimated
1765
camera parameters. Both the object-releasing method and standard method are supported by this
1766
function. Use the parameter **iFixedPoint** for method selection. In the internal implementation,
1767
#calibrateCamera is a wrapper for this function.
1768
1769
@param objectPoints Vector of vectors of calibration pattern points in the calibration pattern
1770
coordinate space. See #calibrateCamera for details. If the method of releasing object to be used,
1771
the identical calibration board must be used in each view and it must be fully visible, and all
1772
objectPoints[i] must be the same and all points should be roughly close to a plane. **The calibration
1773
target has to be rigid, or at least static if the camera (rather than the calibration target) is
1774
shifted for grabbing images.**
1775
@param imagePoints Vector of vectors of the projections of calibration pattern points. See
1776
#calibrateCamera for details.
1777
@param imageSize Size of the image used only to initialize the intrinsic camera matrix.
1778
@param iFixedPoint The index of the 3D object point in objectPoints[0] to be fixed. It also acts as
1779
a switch for calibration method selection. If object-releasing method to be used, pass in the
1780
parameter in the range of [1, objectPoints[0].size()-2], otherwise a value out of this range will
1781
make standard calibration method selected. Usually the top-right corner point of the calibration
1782
board grid is recommended to be fixed when object-releasing method being utilized. According to
1783
\cite strobl2011iccv, two other points are also fixed. In this implementation, objectPoints[0].front
1784
and objectPoints[0].back.z are used. With object-releasing method, accurate rvecs, tvecs and
1785
newObjPoints are only possible if coordinates of these three fixed points are accurate enough.
1786
@param cameraMatrix Output 3x3 floating-point camera matrix. See #calibrateCamera for details.
1787
@param distCoeffs Output vector of distortion coefficients. See #calibrateCamera for details.
1788
@param rvecs Output vector of rotation vectors estimated for each pattern view. See #calibrateCamera
1789
for details.
1790
@param tvecs Output vector of translation vectors estimated for each pattern view.
1791
@param newObjPoints The updated output vector of calibration pattern points. The coordinates might
1792
be scaled based on three fixed points. The returned coordinates are accurate only if the above
1793
mentioned three fixed points are accurate. If not needed, noArray() can be passed in. This parameter
1794
is ignored with standard calibration method.
1795
@param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic parameters.
1796
See #calibrateCamera for details.
1797
@param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic parameters.
1798
See #calibrateCamera for details.
1799
@param stdDeviationsObjPoints Output vector of standard deviations estimated for refined coordinates
1800
of calibration pattern points. It has the same size and order as objectPoints[0] vector. This
1801
parameter is ignored with standard calibration method.
1802
 @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view.
1803
@param flags Different flags that may be zero or a combination of some predefined values. See
1804
#calibrateCamera for details. If the method of releasing object is used, the calibration time may
1805
be much longer. CALIB_USE_QR or CALIB_USE_LU could be used for faster calibration with potentially
1806
less precise and less stable in some rare cases.
1807
@param criteria Termination criteria for the iterative optimization algorithm.
1808
1809
@return the overall RMS re-projection error.
1810
1811
The function estimates the intrinsic camera parameters and extrinsic parameters for each of the
1812
views. The object-releasing extension follows @cite strobl2011iccv and uses the same optimization
1813
core as #calibrateCamera. See #calibrateCamera for other detailed explanations.
1814
@sa
1815
   calibrateCamera, findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, undistort
1816
 */
1817
CV_EXPORTS_AS(calibrateCameraROExtended) double calibrateCameraRO( InputArrayOfArrays objectPoints,
1818
                                     InputArrayOfArrays imagePoints, Size imageSize, int iFixedPoint,
1819
                                     InputOutputArray cameraMatrix, InputOutputArray distCoeffs,
1820
                                     OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
1821
                                     OutputArray newObjPoints,
1822
                                     OutputArray stdDeviationsIntrinsics,
1823
                                     OutputArray stdDeviationsExtrinsics,
1824
                                     OutputArray stdDeviationsObjPoints,
1825
                                     OutputArray perViewErrors,
1826
                                     int flags = 0, TermCriteria criteria = TermCriteria(
1827
                                        TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) );
1828
1829
/** @overload */
1830
CV_EXPORTS_W double calibrateCameraRO( InputArrayOfArrays objectPoints,
1831
                                     InputArrayOfArrays imagePoints, Size imageSize, int iFixedPoint,
1832
                                     InputOutputArray cameraMatrix, InputOutputArray distCoeffs,
1833
                                     OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
1834
                                     OutputArray newObjPoints,
1835
                                     int flags = 0, TermCriteria criteria = TermCriteria(
1836
                                        TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) );
1837
1838
/** @brief Computes useful camera characteristics from the camera intrinsic matrix.
1839
1840
@param cameraMatrix Input camera intrinsic matrix that can be estimated by #calibrateCamera or
1841
#stereoCalibrate .
1842
@param imageSize Input image size in pixels.
1843
@param apertureWidth Physical width in mm of the sensor.
1844
@param apertureHeight Physical height in mm of the sensor.
1845
@param fovx Output field of view in degrees along the horizontal sensor axis.
1846
@param fovy Output field of view in degrees along the vertical sensor axis.
1847
@param focalLength Focal length of the lens in mm.
1848
@param principalPoint Principal point in mm.
1849
@param aspectRatio \f$f_y/f_x\f$
1850
1851
The function computes various useful camera characteristics from the previously estimated camera
1852
matrix.
1853
1854
@note
1855
   Do keep in mind that the unity measure 'mm' stands for whatever unit of measure one chooses for
1856
    the chessboard pitch (it can thus be any value).
1857
 */
1858
CV_EXPORTS_W void calibrationMatrixValues( InputArray cameraMatrix, Size imageSize,
1859
                                           double apertureWidth, double apertureHeight,
1860
                                           CV_OUT double& fovx, CV_OUT double& fovy,
1861
                                           CV_OUT double& focalLength, CV_OUT Point2d& principalPoint,
1862
                                           CV_OUT double& aspectRatio );
1863
1864
/** @brief Calibrates a stereo camera set up. This function finds the intrinsic parameters
1865
for each of the two cameras and the extrinsic parameters between the two cameras.
1866
1867
@param objectPoints Vector of vectors of the calibration pattern points. The same structure as
1868
in @ref calibrateCamera. For each pattern view, both cameras need to see the same object
1869
points. Therefore, objectPoints.size(), imagePoints1.size(), and imagePoints2.size() need to be
1870
equal as well as objectPoints[i].size(), imagePoints1[i].size(), and imagePoints2[i].size() need to
1871
be equal for each i.
1872
@param imagePoints1 Vector of vectors of the projections of the calibration pattern points,
1873
observed by the first camera. The same structure as in @ref calibrateCamera.
1874
@param imagePoints2 Vector of vectors of the projections of the calibration pattern points,
1875
observed by the second camera. The same structure as in @ref calibrateCamera.
1876
@param cameraMatrix1 Input/output camera intrinsic matrix for the first camera, the same as in
1877
@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below.
1878
@param distCoeffs1 Input/output vector of distortion coefficients, the same as in
1879
@ref calibrateCamera.
1880
@param cameraMatrix2 Input/output second camera intrinsic matrix for the second camera. See description for
1881
cameraMatrix1.
1882
@param distCoeffs2 Input/output lens distortion coefficients for the second camera. See
1883
description for distCoeffs1.
1884
@param imageSize Size of the image used only to initialize the camera intrinsic matrices.
1885
@param R Output rotation matrix. Together with the translation vector T, this matrix brings
1886
points given in the first camera's coordinate system to points in the second camera's
1887
coordinate system. In more technical terms, the tuple of R and T performs a change of basis
1888
from the first camera's coordinate system to the second camera's coordinate system. Due to its
1889
duality, this tuple is equivalent to the position of the first camera with respect to the
1890
second camera coordinate system.
1891
@param T Output translation vector, see description above.
1892
@param E Output essential matrix.
1893
@param F Output fundamental matrix.
1894
@param rvecs Output vector of rotation vectors ( @ref Rodrigues ) estimated for each pattern view in the
1895
coordinate system of the first camera of the stereo pair (e.g. std::vector<cv::Mat>). More in detail, each
1896
i-th rotation vector together with the corresponding i-th translation vector (see the next output parameter
1897
description) brings the calibration pattern from the object coordinate space (in which object points are
1898
specified) to the camera coordinate space of the first camera of the stereo pair. In more technical terms,
1899
the tuple of the i-th rotation and translation vector performs a change of basis from object coordinate space
1900
to camera coordinate space of the first camera of the stereo pair.
1901
@param tvecs Output vector of translation vectors estimated for each pattern view, see parameter description
1902
of previous output parameter ( rvecs ).
1903
@param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view.
1904
@param flags Different flags that may be zero or a combination of the following values:
1905
-   @ref CALIB_FIX_INTRINSIC Fix cameraMatrix? and distCoeffs? so that only R, T, E, and F
1906
matrices are estimated.
1907
-   @ref CALIB_USE_INTRINSIC_GUESS Optimize some or all of the intrinsic parameters
1908
according to the specified flags. Initial values are provided by the user.
1909
-   @ref CALIB_USE_EXTRINSIC_GUESS R and T contain valid initial values that are optimized further.
1910
Otherwise R and T are initialized to the median value of the pattern views (each dimension separately).
1911
-   @ref CALIB_FIX_PRINCIPAL_POINT Fix the principal points during the optimization.
1912
-   @ref CALIB_FIX_FOCAL_LENGTH Fix \f$f^{(j)}_x\f$ and \f$f^{(j)}_y\f$ .
1913
-   @ref CALIB_FIX_ASPECT_RATIO Optimize \f$f^{(j)}_y\f$ . Fix the ratio \f$f^{(j)}_x/f^{(j)}_y\f$
1914
.
1915
-   @ref CALIB_SAME_FOCAL_LENGTH Enforce \f$f^{(0)}_x=f^{(1)}_x\f$ and \f$f^{(0)}_y=f^{(1)}_y\f$ .
1916
-   @ref CALIB_ZERO_TANGENT_DIST Set tangential distortion coefficients for each camera to
1917
zeros and fix there.
1918
-   @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 Do not change the corresponding radial
1919
distortion coefficient during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set,
1920
the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0.
1921
-   @ref CALIB_RATIONAL_MODEL Enable coefficients k4, k5, and k6. To provide the backward
1922
compatibility, this extra flag should be explicitly specified to make the calibration
1923
function use the rational model and return 8 coefficients. If the flag is not set, the
1924
function computes and returns only 5 distortion coefficients.
1925
-   @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the
1926
backward compatibility, this extra flag should be explicitly specified to make the
1927
calibration function use the thin prism model and return 12 coefficients. If the flag is not
1928
set, the function computes and returns only 5 distortion coefficients.
1929
-   @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during
1930
the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
1931
supplied distCoeffs matrix is used. Otherwise, it is set to 0.
1932
-   @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the
1933
backward compatibility, this extra flag should be explicitly specified to make the
1934
calibration function use the tilted sensor model and return 14 coefficients. If the flag is not
1935
set, the function computes and returns only 5 distortion coefficients.
1936
-   @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during
1937
the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
1938
supplied distCoeffs matrix is used. Otherwise, it is set to 0.
1939
@param criteria Termination criteria for the iterative optimization algorithm.
1940
1941
The function estimates the transformation between two cameras making a stereo pair. If one computes
1942
the poses of an object relative to the first camera and to the second camera,
1943
( \f$R_1\f$,\f$T_1\f$ ) and (\f$R_2\f$,\f$T_2\f$), respectively, for a stereo camera where the
1944
relative position and orientation between the two cameras are fixed, then those poses definitely
1945
relate to each other. This means, if the relative position and orientation (\f$R\f$,\f$T\f$) of the
1946
two cameras is known, it is possible to compute (\f$R_2\f$,\f$T_2\f$) when (\f$R_1\f$,\f$T_1\f$) is
1947
given. This is what the described function does. It computes (\f$R\f$,\f$T\f$) such that:
1948
1949
\f[R_2=R R_1\f]
1950
\f[T_2=R T_1 + T.\f]
1951
1952
Therefore, one can compute the coordinate representation of a 3D point for the second camera's
1953
coordinate system when given the point's coordinate representation in the first camera's coordinate
1954
system:
1955
1956
\f[\begin{bmatrix}
1957
X_2 \\
1958
Y_2 \\
1959
Z_2 \\
1960
1
1961
\end{bmatrix} = \begin{bmatrix}
1962
R & T \\
1963
0 & 1
1964
\end{bmatrix} \begin{bmatrix}
1965
X_1 \\
1966
Y_1 \\
1967
Z_1 \\
1968
1
1969
\end{bmatrix}.\f]
1970
1971
1972
Optionally, it computes the essential matrix E:
1973
1974
\f[E= \vecthreethree{0}{-T_2}{T_1}{T_2}{0}{-T_0}{-T_1}{T_0}{0} R\f]
1975
1976
where \f$T_i\f$ are components of the translation vector \f$T\f$ : \f$T=[T_0, T_1, T_2]^T\f$ .
1977
And the function can also compute the fundamental matrix F:
1978
1979
\f[F = cameraMatrix2^{-T}\cdot E \cdot cameraMatrix1^{-1}\f]
1980
1981
Besides the stereo-related information, the function can also perform a full calibration of each of
1982
the two cameras. However, due to the high dimensionality of the parameter space and noise in the
1983
input data, the function can diverge from the correct solution. If the intrinsic parameters can be
1984
estimated with high accuracy for each of the cameras individually (for example, using
1985
#calibrateCamera ), you are recommended to do so and then pass @ref CALIB_FIX_INTRINSIC flag to the
1986
function along with the computed intrinsic parameters. Otherwise, if all the parameters are
1987
estimated at once, it makes sense to restrict some parameters, for example, pass
1988
 @ref CALIB_SAME_FOCAL_LENGTH and @ref CALIB_ZERO_TANGENT_DIST flags, which is usually a
1989
reasonable assumption.
1990
1991
Similarly to #calibrateCamera, the function minimizes the total re-projection error for all the
1992
points in all the available views from both cameras. The function returns the final value of the
1993
re-projection error.
1994
 */
1995
CV_EXPORTS_AS(stereoCalibrateExtended) double stereoCalibrate( InputArrayOfArrays objectPoints,
1996
                                     InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
1997
                                     InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1,
1998
                                     InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2,
1999
                                     Size imageSize, InputOutputArray R, InputOutputArray T, OutputArray E, OutputArray F,
2000
                                     OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, OutputArray perViewErrors, int flags = CALIB_FIX_INTRINSIC,
2001
                                     TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) );
2002
2003
/// @overload
2004
CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints,
2005
                                     InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
2006
                                     InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1,
2007
                                     InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2,
2008
                                     Size imageSize, OutputArray R,OutputArray T, OutputArray E, OutputArray F,
2009
                                     int flags = CALIB_FIX_INTRINSIC,
2010
                                     TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) );
2011
2012
/// @overload
2013
CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints,
2014
                                     InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
2015
                                     InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1,
2016
                                     InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2,
2017
                                     Size imageSize, InputOutputArray R, InputOutputArray T, OutputArray E, OutputArray F,
2018
                                     OutputArray perViewErrors, int flags = CALIB_FIX_INTRINSIC,
2019
                                     TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) );
2020
2021
/** @brief Computes rectification transforms for each head of a calibrated stereo camera.
2022
2023
@param cameraMatrix1 First camera intrinsic matrix.
2024
@param distCoeffs1 First camera distortion parameters.
2025
@param cameraMatrix2 Second camera intrinsic matrix.
2026
@param distCoeffs2 Second camera distortion parameters.
2027
@param imageSize Size of the image used for stereo calibration.
2028
@param R Rotation matrix from the coordinate system of the first camera to the second camera,
2029
see @ref stereoCalibrate.
2030
@param T Translation vector from the coordinate system of the first camera to the second camera,
2031
see @ref stereoCalibrate.
2032
@param R1 Output 3x3 rectification transform (rotation matrix) for the first camera. This matrix
2033
brings points given in the unrectified first camera's coordinate system to points in the rectified
2034
first camera's coordinate system. In more technical terms, it performs a change of basis from the
2035
unrectified first camera's coordinate system to the rectified first camera's coordinate system.
2036
@param R2 Output 3x3 rectification transform (rotation matrix) for the second camera. This matrix
2037
brings points given in the unrectified second camera's coordinate system to points in the rectified
2038
second camera's coordinate system. In more technical terms, it performs a change of basis from the
2039
unrectified second camera's coordinate system to the rectified second camera's coordinate system.
2040
@param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first
2041
camera, i.e. it projects points given in the rectified first camera coordinate system into the
2042
rectified first camera's image.
2043
@param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second
2044
camera, i.e. it projects points given in the rectified first camera coordinate system into the
2045
rectified second camera's image.
2046
@param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see @ref reprojectImageTo3D).
2047
@param flags Operation flags that may be zero or @ref CALIB_ZERO_DISPARITY . If the flag is set,
2048
the function makes the principal points of each camera have the same pixel coordinates in the
2049
rectified views. And if the flag is not set, the function may still shift the images in the
2050
horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the
2051
useful image area.
2052
@param alpha Free scaling parameter. If it is -1 or absent, the function performs the default
2053
scaling. Otherwise, the parameter should be between 0 and 1. alpha=0 means that the rectified
2054
images are zoomed and shifted so that only valid pixels are visible (no black areas after
2055
rectification). alpha=1 means that the rectified image is decimated and shifted so that all the
2056
pixels from the original images from the cameras are retained in the rectified images (no source
2057
image pixels are lost). Any intermediate value yields an intermediate result between
2058
those two extreme cases.
2059
@param newImageSize New image resolution after rectification. The same size should be passed to
2060
#initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0)
2061
is passed (default), it is set to the original imageSize . Setting it to a larger value can help you
2062
preserve details in the original image, especially when there is a big radial distortion.
2063
@param validPixROI1 Optional output rectangles inside the rectified images where all the pixels
2064
are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller
2065
(see the picture below).
2066
@param validPixROI2 Optional output rectangles inside the rectified images where all the pixels
2067
are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller
2068
(see the picture below).
2069
2070
The function computes the rotation matrices for each camera that (virtually) make both camera image
2071
planes the same plane. Consequently, this makes all the epipolar lines parallel and thus simplifies
2072
the dense stereo correspondence problem. The function takes the matrices computed by #stereoCalibrate
2073
as input. As output, it provides two rotation matrices and also two projection matrices in the new
2074
coordinates. The function distinguishes the following two cases:
2075
2076
-   **Horizontal stereo**: the first and the second camera views are shifted relative to each other
2077
    mainly along the x-axis (with possible small vertical shift). In the rectified images, the
2078
    corresponding epipolar lines in the left and right cameras are horizontal and have the same
2079
    y-coordinate. P1 and P2 look like:
2080
2081
    \f[\texttt{P1} = \begin{bmatrix}
2082
                        f & 0 & cx_1 & 0 \\
2083
                        0 & f & cy & 0 \\
2084
                        0 & 0 & 1 & 0
2085
                     \end{bmatrix}\f]
2086
2087
    \f[\texttt{P2} = \begin{bmatrix}
2088
                        f & 0 & cx_2 & T_x \cdot f \\
2089
                        0 & f & cy & 0 \\
2090
                        0 & 0 & 1 & 0
2091
                     \end{bmatrix} ,\f]
2092
2093
    \f[\texttt{Q} = \begin{bmatrix}
2094
                        1 & 0 & 0 & -cx_1 \\
2095
                        0 & 1 & 0 & -cy \\
2096
                        0 & 0 & 0 & f \\
2097
                        0 & 0 & -\frac{1}{T_x} & \frac{cx_1 - cx_2}{T_x}
2098
                    \end{bmatrix} \f]
2099
2100
    where \f$T_x\f$ is a horizontal shift between the cameras and \f$cx_1=cx_2\f$ if
2101
    @ref CALIB_ZERO_DISPARITY is set.
2102
2103
-   **Vertical stereo**: the first and the second camera views are shifted relative to each other
2104
    mainly in the vertical direction (and probably a bit in the horizontal direction too). The epipolar
2105
    lines in the rectified images are vertical and have the same x-coordinate. P1 and P2 look like:
2106
2107
    \f[\texttt{P1} = \begin{bmatrix}
2108
                        f & 0 & cx & 0 \\
2109
                        0 & f & cy_1 & 0 \\
2110
                        0 & 0 & 1 & 0
2111
                     \end{bmatrix}\f]
2112
2113
    \f[\texttt{P2} = \begin{bmatrix}
2114
                        f & 0 & cx & 0 \\
2115
                        0 & f & cy_2 & T_y \cdot f \\
2116
                        0 & 0 & 1 & 0
2117
                     \end{bmatrix},\f]
2118
2119
    \f[\texttt{Q} = \begin{bmatrix}
2120
                        1 & 0 & 0 & -cx \\
2121
                        0 & 1 & 0 & -cy_1 \\
2122
                        0 & 0 & 0 & f \\
2123
                        0 & 0 & -\frac{1}{T_y} & \frac{cy_1 - cy_2}{T_y}
2124
                    \end{bmatrix} \f]
2125
2126
    where \f$T_y\f$ is a vertical shift between the cameras and \f$cy_1=cy_2\f$ if
2127
    @ref CALIB_ZERO_DISPARITY is set.
2128
2129
As you can see, the first three columns of P1 and P2 will effectively be the new "rectified" camera
2130
matrices. The matrices, together with R1 and R2 , can then be passed to #initUndistortRectifyMap to
2131
initialize the rectification map for each camera.
2132
2133
See below the screenshot from the stereo_calib.cpp sample. Some red horizontal lines pass through
2134
the corresponding image regions. This means that the images are well rectified, which is what most
2135
stereo correspondence algorithms rely on. The green rectangles are roi1 and roi2 . You see that
2136
their interiors are all valid pixels.
2137
2138
![image](pics/stereo_undistort.jpg)
2139
 */
2140
CV_EXPORTS_W void stereoRectify( InputArray cameraMatrix1, InputArray distCoeffs1,
2141
                                 InputArray cameraMatrix2, InputArray distCoeffs2,
2142
                                 Size imageSize, InputArray R, InputArray T,
2143
                                 OutputArray R1, OutputArray R2,
2144
                                 OutputArray P1, OutputArray P2,
2145
                                 OutputArray Q, int flags = CALIB_ZERO_DISPARITY,
2146
                                 double alpha = -1, Size newImageSize = Size(),
2147
                                 CV_OUT Rect* validPixROI1 = 0, CV_OUT Rect* validPixROI2 = 0 );
2148
2149
/** @brief Computes a rectification transform for an uncalibrated stereo camera.
2150
2151
@param points1 Array of feature points in the first image.
2152
@param points2 The corresponding points in the second image. The same formats as in
2153
#findFundamentalMat are supported.
2154
@param F Input fundamental matrix. It can be computed from the same set of point pairs using
2155
#findFundamentalMat .
2156
@param imgSize Size of the image.
2157
@param H1 Output rectification homography matrix for the first image.
2158
@param H2 Output rectification homography matrix for the second image.
2159
@param threshold Optional threshold used to filter out the outliers. If the parameter is greater
2160
than zero, all the point pairs that do not comply with the epipolar geometry (that is, the points
2161
for which \f$|\texttt{points2[i]}^T \cdot \texttt{F} \cdot \texttt{points1[i]}|>\texttt{threshold}\f$ )
2162
are rejected prior to computing the homographies. Otherwise, all the points are considered inliers.
2163
2164
The function computes the rectification transformations without knowing intrinsic parameters of the
2165
cameras and their relative position in the space, which explains the suffix "uncalibrated". Another
2166
related difference from #stereoRectify is that the function outputs not the rectification
2167
transformations in the object (3D) space, but the planar perspective transformations encoded by the
2168
homography matrices H1 and H2 . The function implements the algorithm @cite Hartley99 .
2169
2170
@note
2171
   While the algorithm does not need to know the intrinsic parameters of the cameras, it heavily
2172
    depends on the epipolar geometry. Therefore, if the camera lenses have a significant distortion,
2173
    it would be better to correct it before computing the fundamental matrix and calling this
2174
    function. For example, distortion coefficients can be estimated for each head of stereo camera
2175
    separately by using #calibrateCamera . Then, the images can be corrected using #undistort , or
2176
    just the point coordinates can be corrected with #undistortPoints .
2177
 */
2178
CV_EXPORTS_W bool stereoRectifyUncalibrated( InputArray points1, InputArray points2,
2179
                                             InputArray F, Size imgSize,
2180
                                             OutputArray H1, OutputArray H2,
2181
                                             double threshold = 5 );
2182
2183
//! computes the rectification transformations for 3-head camera, where all the heads are on the same line.
2184
CV_EXPORTS_W float rectify3Collinear( InputArray cameraMatrix1, InputArray distCoeffs1,
2185
                                      InputArray cameraMatrix2, InputArray distCoeffs2,
2186
                                      InputArray cameraMatrix3, InputArray distCoeffs3,
2187
                                      InputArrayOfArrays imgpt1, InputArrayOfArrays imgpt3,
2188
                                      Size imageSize, InputArray R12, InputArray T12,
2189
                                      InputArray R13, InputArray T13,
2190
                                      OutputArray R1, OutputArray R2, OutputArray R3,
2191
                                      OutputArray P1, OutputArray P2, OutputArray P3,
2192
                                      OutputArray Q, double alpha, Size newImgSize,
2193
                                      CV_OUT Rect* roi1, CV_OUT Rect* roi2, int flags );
2194
2195
/** @brief Returns the new camera intrinsic matrix based on the free scaling parameter.
2196
2197
@param cameraMatrix Input camera intrinsic matrix.
2198
@param distCoeffs Input vector of distortion coefficients
2199
\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
2200
assumed.
2201
@param imageSize Original image size.
2202
@param alpha Free scaling parameter between 0 (when all the pixels in the undistorted image are
2203
valid) and 1 (when all the source image pixels are retained in the undistorted image). See
2204
#stereoRectify for details.
2205
@param newImgSize Image size after rectification. By default, it is set to imageSize .
2206
@param validPixROI Optional output rectangle that outlines all-good-pixels region in the
2207
undistorted image. See roi1, roi2 description in #stereoRectify .
2208
@param centerPrincipalPoint Optional flag that indicates whether in the new camera intrinsic matrix the
2209
principal point should be at the image center or not. By default, the principal point is chosen to
2210
best fit a subset of the source image (determined by alpha) to the corrected image.
2211
@return new_camera_matrix Output new camera intrinsic matrix.
2212
2213
The function computes and returns the optimal new camera intrinsic matrix based on the free scaling parameter.
2214
By varying this parameter, you may retrieve only sensible pixels alpha=0 , keep all the original
2215
image pixels if there is valuable information in the corners alpha=1 , or get something in between.
2216
When alpha\>0 , the undistorted result is likely to have some black pixels corresponding to
2217
"virtual" pixels outside of the captured distorted image. The original camera intrinsic matrix, distortion
2218
coefficients, the computed new camera intrinsic matrix, and newImageSize should be passed to
2219
#initUndistortRectifyMap to produce the maps for #remap .
2220
 */
2221
CV_EXPORTS_W Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs,
2222
                                            Size imageSize, double alpha, Size newImgSize = Size(),
2223
                                            CV_OUT Rect* validPixROI = 0,
2224
                                            bool centerPrincipalPoint = false);
2225
2226
/** @brief Computes Hand-Eye calibration: \f$_{}^{g}\textrm{T}_c\f$
2227
2228
@param[in] R_gripper2base Rotation part extracted from the homogeneous matrix that transforms a point
2229
expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$).
2230
This is a vector (`vector<Mat>`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors,
2231
for all the transformations from gripper frame to robot base frame.
2232
@param[in] t_gripper2base Translation part extracted from the homogeneous matrix that transforms a point
2233
expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$).
2234
This is a vector (`vector<Mat>`) that contains the `(3x1)` translation vectors for all the transformations
2235
from gripper frame to robot base frame.
2236
@param[in] R_target2cam Rotation part extracted from the homogeneous matrix that transforms a point
2237
expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$).
2238
This is a vector (`vector<Mat>`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors,
2239
for all the transformations from calibration target frame to camera frame.
2240
@param[in] t_target2cam Rotation part extracted from the homogeneous matrix that transforms a point
2241
expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$).
2242
This is a vector (`vector<Mat>`) that contains the `(3x1)` translation vectors for all the transformations
2243
from calibration target frame to camera frame.
2244
@param[out] R_cam2gripper Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point
2245
expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$).
2246
@param[out] t_cam2gripper Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point
2247
expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$).
2248
@param[in] method One of the implemented Hand-Eye calibration method, see cv::HandEyeCalibrationMethod
2249
2250
The function performs the Hand-Eye calibration using various methods. One approach consists in estimating the
2251
rotation then the translation (separable solutions) and the following methods are implemented:
2252
  - R. Tsai, R. Lenz A New Technique for Fully Autonomous and Efficient 3D Robotics Hand/EyeCalibration \cite Tsai89
2253
  - F. Park, B. Martin Robot Sensor Calibration: Solving AX = XB on the Euclidean Group \cite Park94
2254
  - R. Horaud, F. Dornaika Hand-Eye Calibration \cite Horaud95
2255
2256
Another approach consists in estimating simultaneously the rotation and the translation (simultaneous solutions),
2257
with the following implemented methods:
2258
  - N. Andreff, R. Horaud, B. Espiau On-line Hand-Eye Calibration \cite Andreff99
2259
  - K. Daniilidis Hand-Eye Calibration Using Dual Quaternions \cite Daniilidis98
2260
2261
The following picture describes the Hand-Eye calibration problem where the transformation between a camera ("eye")
2262
mounted on a robot gripper ("hand") has to be estimated. This configuration is called eye-in-hand.
2263
2264
The eye-to-hand configuration consists in a static camera observing a calibration pattern mounted on the robot
2265
end-effector. The transformation from the camera to the robot base frame can then be estimated by inputting
2266
the suitable transformations to the function, see below.
2267
2268
![](pics/hand-eye_figure.png)
2269
2270
The calibration procedure is the following:
2271
  - a static calibration pattern is used to estimate the transformation between the target frame
2272
  and the camera frame
2273
  - the robot gripper is moved in order to acquire several poses
2274
  - for each pose, the homogeneous transformation between the gripper frame and the robot base frame is recorded using for
2275
  instance the robot kinematics
2276
\f[
2277
    \begin{bmatrix}
2278
    X_b\\
2279
    Y_b\\
2280
    Z_b\\
2281
    1
2282
    \end{bmatrix}
2283
    =
2284
    \begin{bmatrix}
2285
    _{}^{b}\textrm{R}_g & _{}^{b}\textrm{t}_g \\
2286
    0_{1 \times 3} & 1
2287
    \end{bmatrix}
2288
    \begin{bmatrix}
2289
    X_g\\
2290
    Y_g\\
2291
    Z_g\\
2292
    1
2293
    \end{bmatrix}
2294
\f]
2295
  - for each pose, the homogeneous transformation between the calibration target frame and the camera frame is recorded using
2296
  for instance a pose estimation method (PnP) from 2D-3D point correspondences
2297
\f[
2298
    \begin{bmatrix}
2299
    X_c\\
2300
    Y_c\\
2301
    Z_c\\
2302
    1
2303
    \end{bmatrix}
2304
    =
2305
    \begin{bmatrix}
2306
    _{}^{c}\textrm{R}_t & _{}^{c}\textrm{t}_t \\
2307
    0_{1 \times 3} & 1
2308
    \end{bmatrix}
2309
    \begin{bmatrix}
2310
    X_t\\
2311
    Y_t\\
2312
    Z_t\\
2313
    1
2314
    \end{bmatrix}
2315
\f]
2316
2317
The Hand-Eye calibration procedure returns the following homogeneous transformation
2318
\f[
2319
    \begin{bmatrix}
2320
    X_g\\
2321
    Y_g\\
2322
    Z_g\\
2323
    1
2324
    \end{bmatrix}
2325
    =
2326
    \begin{bmatrix}
2327
    _{}^{g}\textrm{R}_c & _{}^{g}\textrm{t}_c \\
2328
    0_{1 \times 3} & 1
2329
    \end{bmatrix}
2330
    \begin{bmatrix}
2331
    X_c\\
2332
    Y_c\\
2333
    Z_c\\
2334
    1
2335
    \end{bmatrix}
2336
\f]
2337
2338
This problem is also known as solving the \f$\mathbf{A}\mathbf{X}=\mathbf{X}\mathbf{B}\f$ equation:
2339
  - for an eye-in-hand configuration
2340
\f[
2341
    \begin{align*}
2342
    ^{b}{\textrm{T}_g}^{(1)} \hspace{0.2em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(1)} &=
2343
    \hspace{0.1em} ^{b}{\textrm{T}_g}^{(2)} \hspace{0.2em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} \\
2344
2345
    (^{b}{\textrm{T}_g}^{(2)})^{-1} \hspace{0.2em} ^{b}{\textrm{T}_g}^{(1)} \hspace{0.2em} ^{g}\textrm{T}_c &=
2346
    \hspace{0.1em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} (^{c}{\textrm{T}_t}^{(1)})^{-1} \\
2347
2348
    \textrm{A}_i \textrm{X} &= \textrm{X} \textrm{B}_i \\
2349
    \end{align*}
2350
\f]
2351
2352
  - for an eye-to-hand configuration
2353
\f[
2354
    \begin{align*}
2355
    ^{g}{\textrm{T}_b}^{(1)} \hspace{0.2em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(1)} &=
2356
    \hspace{0.1em} ^{g}{\textrm{T}_b}^{(2)} \hspace{0.2em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} \\
2357
2358
    (^{g}{\textrm{T}_b}^{(2)})^{-1} \hspace{0.2em} ^{g}{\textrm{T}_b}^{(1)} \hspace{0.2em} ^{b}\textrm{T}_c &=
2359
    \hspace{0.1em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} (^{c}{\textrm{T}_t}^{(1)})^{-1} \\
2360
2361
    \textrm{A}_i \textrm{X} &= \textrm{X} \textrm{B}_i \\
2362
    \end{align*}
2363
\f]
2364
2365
\note
2366
Additional information can be found on this [website](http://campar.in.tum.de/Chair/HandEyeCalibration).
2367
\note
2368
A minimum of 2 motions with non parallel rotation axes are necessary to determine the hand-eye transformation.
2369
So at least 3 different poses are required, but it is strongly recommended to use many more poses.
2370
2371
 */
2372
CV_EXPORTS_W void calibrateHandEye( InputArrayOfArrays R_gripper2base, InputArrayOfArrays t_gripper2base,
2373
                                    InputArrayOfArrays R_target2cam, InputArrayOfArrays t_target2cam,
2374
                                    OutputArray R_cam2gripper, OutputArray t_cam2gripper,
2375
                                    HandEyeCalibrationMethod method=CALIB_HAND_EYE_TSAI );
2376
2377
/** @brief Computes Robot-World/Hand-Eye calibration: \f$_{}^{w}\textrm{T}_b\f$ and \f$_{}^{c}\textrm{T}_g\f$
2378
2379
@param[in] R_world2cam Rotation part extracted from the homogeneous matrix that transforms a point
2380
expressed in the world frame to the camera frame (\f$_{}^{c}\textrm{T}_w\f$).
2381
This is a vector (`vector<Mat>`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors,
2382
for all the transformations from world frame to the camera frame.
2383
@param[in] t_world2cam Translation part extracted from the homogeneous matrix that transforms a point
2384
expressed in the world frame to the camera frame (\f$_{}^{c}\textrm{T}_w\f$).
2385
This is a vector (`vector<Mat>`) that contains the `(3x1)` translation vectors for all the transformations
2386
from world frame to the camera frame.
2387
@param[in] R_base2gripper Rotation part extracted from the homogeneous matrix that transforms a point
2388
expressed in the robot base frame to the gripper frame (\f$_{}^{g}\textrm{T}_b\f$).
2389
This is a vector (`vector<Mat>`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors,
2390
for all the transformations from robot base frame to the gripper frame.
2391
@param[in] t_base2gripper Rotation part extracted from the homogeneous matrix that transforms a point
2392
expressed in the robot base frame to the gripper frame (\f$_{}^{g}\textrm{T}_b\f$).
2393
This is a vector (`vector<Mat>`) that contains the `(3x1)` translation vectors for all the transformations
2394
from robot base frame to the gripper frame.
2395
@param[out] R_base2world Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point
2396
expressed in the robot base frame to the world frame (\f$_{}^{w}\textrm{T}_b\f$).
2397
@param[out] t_base2world Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point
2398
expressed in the robot base frame to the world frame (\f$_{}^{w}\textrm{T}_b\f$).
2399
@param[out] R_gripper2cam Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point
2400
expressed in the gripper frame to the camera frame (\f$_{}^{c}\textrm{T}_g\f$).
2401
@param[out] t_gripper2cam Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point
2402
expressed in the gripper frame to the camera frame (\f$_{}^{c}\textrm{T}_g\f$).
2403
@param[in] method One of the implemented Robot-World/Hand-Eye calibration method, see cv::RobotWorldHandEyeCalibrationMethod
2404
2405
The function performs the Robot-World/Hand-Eye calibration using various methods. One approach consists in estimating the
2406
rotation then the translation (separable solutions):
2407
  - M. Shah, Solving the robot-world/hand-eye calibration problem using the kronecker product \cite Shah2013SolvingTR
2408
2409
Another approach consists in estimating simultaneously the rotation and the translation (simultaneous solutions),
2410
with the following implemented method:
2411
  - A. Li, L. Wang, and D. Wu, Simultaneous robot-world and hand-eye calibration using dual-quaternions and kronecker product \cite Li2010SimultaneousRA
2412
2413
The following picture describes the Robot-World/Hand-Eye calibration problem where the transformations between a robot and a world frame
2414
and between a robot gripper ("hand") and a camera ("eye") mounted at the robot end-effector have to be estimated.
2415
2416
![](pics/robot-world_hand-eye_figure.png)
2417
2418
The calibration procedure is the following:
2419
  - a static calibration pattern is used to estimate the transformation between the target frame
2420
  and the camera frame
2421
  - the robot gripper is moved in order to acquire several poses
2422
  - for each pose, the homogeneous transformation between the gripper frame and the robot base frame is recorded using for
2423
  instance the robot kinematics
2424
\f[
2425
    \begin{bmatrix}
2426
    X_g\\
2427
    Y_g\\
2428
    Z_g\\
2429
    1
2430
    \end{bmatrix}
2431
    =
2432
    \begin{bmatrix}
2433
    _{}^{g}\textrm{R}_b & _{}^{g}\textrm{t}_b \\
2434
    0_{1 \times 3} & 1
2435
    \end{bmatrix}
2436
    \begin{bmatrix}
2437
    X_b\\
2438
    Y_b\\
2439
    Z_b\\
2440
    1
2441
    \end{bmatrix}
2442
\f]
2443
  - for each pose, the homogeneous transformation between the calibration target frame (the world frame) and the camera frame is recorded using
2444
  for instance a pose estimation method (PnP) from 2D-3D point correspondences
2445
\f[
2446
    \begin{bmatrix}
2447
    X_c\\
2448
    Y_c\\
2449
    Z_c\\
2450
    1
2451
    \end{bmatrix}
2452
    =
2453
    \begin{bmatrix}
2454
    _{}^{c}\textrm{R}_w & _{}^{c}\textrm{t}_w \\
2455
    0_{1 \times 3} & 1
2456
    \end{bmatrix}
2457
    \begin{bmatrix}
2458
    X_w\\
2459
    Y_w\\
2460
    Z_w\\
2461
    1
2462
    \end{bmatrix}
2463
\f]
2464
2465
The Robot-World/Hand-Eye calibration procedure returns the following homogeneous transformations
2466
\f[
2467
    \begin{bmatrix}
2468
    X_w\\
2469
    Y_w\\
2470
    Z_w\\
2471
    1
2472
    \end{bmatrix}
2473
    =
2474
    \begin{bmatrix}
2475
    _{}^{w}\textrm{R}_b & _{}^{w}\textrm{t}_b \\
2476
    0_{1 \times 3} & 1
2477
    \end{bmatrix}
2478
    \begin{bmatrix}
2479
    X_b\\
2480
    Y_b\\
2481
    Z_b\\
2482
    1
2483
    \end{bmatrix}
2484
\f]
2485
\f[
2486
    \begin{bmatrix}
2487
    X_c\\
2488
    Y_c\\
2489
    Z_c\\
2490
    1
2491
    \end{bmatrix}
2492
    =
2493
    \begin{bmatrix}
2494
    _{}^{c}\textrm{R}_g & _{}^{c}\textrm{t}_g \\
2495
    0_{1 \times 3} & 1
2496
    \end{bmatrix}
2497
    \begin{bmatrix}
2498
    X_g\\
2499
    Y_g\\
2500
    Z_g\\
2501
    1
2502
    \end{bmatrix}
2503
\f]
2504
2505
This problem is also known as solving the \f$\mathbf{A}\mathbf{X}=\mathbf{Z}\mathbf{B}\f$ equation, with:
2506
  - \f$\mathbf{A} \Leftrightarrow \hspace{0.1em} _{}^{c}\textrm{T}_w\f$
2507
  - \f$\mathbf{X} \Leftrightarrow \hspace{0.1em} _{}^{w}\textrm{T}_b\f$
2508
  - \f$\mathbf{Z} \Leftrightarrow \hspace{0.1em} _{}^{c}\textrm{T}_g\f$
2509
  - \f$\mathbf{B} \Leftrightarrow \hspace{0.1em} _{}^{g}\textrm{T}_b\f$
2510
2511
\note
2512
At least 3 measurements are required (input vectors size must be greater or equal to 3).
2513
2514
 */
2515
CV_EXPORTS_W void calibrateRobotWorldHandEye( InputArrayOfArrays R_world2cam, InputArrayOfArrays t_world2cam,
2516
                                              InputArrayOfArrays R_base2gripper, InputArrayOfArrays t_base2gripper,
2517
                                              OutputArray R_base2world, OutputArray t_base2world,
2518
                                              OutputArray R_gripper2cam, OutputArray t_gripper2cam,
2519
                                              RobotWorldHandEyeCalibrationMethod method=CALIB_ROBOT_WORLD_HAND_EYE_SHAH );
2520
2521
/** @brief Converts points from Euclidean to homogeneous space.
2522
2523
@param src Input vector of N-dimensional points.
2524
@param dst Output vector of N+1-dimensional points.
2525
2526
The function converts points from Euclidean to homogeneous space by appending 1's to the tuple of
2527
point coordinates. That is, each point (x1, x2, ..., xn) is converted to (x1, x2, ..., xn, 1).
2528
 */
2529
CV_EXPORTS_W void convertPointsToHomogeneous( InputArray src, OutputArray dst );
2530
2531
/** @brief Converts points from homogeneous to Euclidean space.
2532
2533
@param src Input vector of N-dimensional points.
2534
@param dst Output vector of N-1-dimensional points.
2535
2536
The function converts points homogeneous to Euclidean space using perspective projection. That is,
2537
each point (x1, x2, ... x(n-1), xn) is converted to (x1/xn, x2/xn, ..., x(n-1)/xn). When xn=0, the
2538
output point coordinates will be (0,0,0,...).
2539
 */
2540
CV_EXPORTS_W void convertPointsFromHomogeneous( InputArray src, OutputArray dst );
2541
2542
/** @brief Converts points to/from homogeneous coordinates.
2543
2544
@param src Input array or vector of 2D, 3D, or 4D points.
2545
@param dst Output vector of 2D, 3D, or 4D points.
2546
2547
The function converts 2D or 3D points from/to homogeneous coordinates by calling either
2548
#convertPointsToHomogeneous or #convertPointsFromHomogeneous.
2549
2550
@note The function is obsolete. Use one of the previous two functions instead.
2551
 */
2552
CV_EXPORTS void convertPointsHomogeneous( InputArray src, OutputArray dst );
2553
2554
/** @brief Calculates a fundamental matrix from the corresponding points in two images.
2555
2556
@param points1 Array of N points from the first image. The point coordinates should be
2557
floating-point (single or double precision).
2558
@param points2 Array of the second image points of the same size and format as points1 .
2559
@param method Method for computing a fundamental matrix.
2560
-   @ref FM_7POINT for a 7-point algorithm. \f$N = 7\f$
2561
-   @ref FM_8POINT for an 8-point algorithm. \f$N \ge 8\f$
2562
-   @ref FM_RANSAC for the RANSAC algorithm. \f$N \ge 8\f$
2563
-   @ref FM_LMEDS for the LMedS algorithm. \f$N \ge 8\f$
2564
@param ransacReprojThreshold Parameter used only for RANSAC. It is the maximum distance from a point to an epipolar
2565
line in pixels, beyond which the point is considered an outlier and is not used for computing the
2566
final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
2567
point localization, image resolution, and the image noise.
2568
@param confidence Parameter used for the RANSAC and LMedS methods only. It specifies a desirable level
2569
of confidence (probability) that the estimated matrix is correct.
2570
@param[out] mask optional output mask
2571
@param maxIters The maximum number of robust method iterations.
2572
2573
The epipolar geometry is described by the following equation:
2574
2575
\f[[p_2; 1]^T F [p_1; 1] = 0\f]
2576
2577
where \f$F\f$ is a fundamental matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the
2578
second images, respectively.
2579
2580
The function calculates the fundamental matrix using one of four methods listed above and returns
2581
the found fundamental matrix. Normally just one matrix is found. But in case of the 7-point
2582
algorithm, the function may return up to 3 solutions ( \f$9 \times 3\f$ matrix that stores all 3
2583
matrices sequentially).
2584
2585
The calculated fundamental matrix may be passed further to #computeCorrespondEpilines that finds the
2586
epipolar lines corresponding to the specified points. It can also be passed to
2587
#stereoRectifyUncalibrated to compute the rectification transformation. :
2588
@code
2589
    // Example. Estimation of fundamental matrix using the RANSAC algorithm
2590
    int point_count = 100;
2591
    vector<Point2f> points1(point_count);
2592
    vector<Point2f> points2(point_count);
2593
2594
    // initialize the points here ...
2595
    for( int i = 0; i < point_count; i++ )
2596
    {
2597
        points1[i] = ...;
2598
        points2[i] = ...;
2599
    }
2600
2601
    Mat fundamental_matrix =
2602
     findFundamentalMat(points1, points2, FM_RANSAC, 3, 0.99);
2603
@endcode
2604
 */
2605
CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2,
2606
                                     int method, double ransacReprojThreshold, double confidence,
2607
                                     int maxIters, OutputArray mask = noArray() );
2608
2609
/** @overload */
2610
CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2,
2611
                                     int method = FM_RANSAC,
2612
                                     double ransacReprojThreshold = 3., double confidence = 0.99,
2613
                                     OutputArray mask = noArray() );
2614
2615
/** @overload */
2616
CV_EXPORTS Mat findFundamentalMat( InputArray points1, InputArray points2,
2617
                                   OutputArray mask, int method = FM_RANSAC,
2618
                                   double ransacReprojThreshold = 3., double confidence = 0.99 );
2619
2620
2621
CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2,
2622
                        OutputArray mask, const UsacParams &params);
2623
2624
/** @brief Calculates an essential matrix from the corresponding points in two images.
2625
2626
@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should
2627
be floating-point (single or double precision).
2628
@param points2 Array of the second image points of the same size and format as points1.
2629
@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
2630
Note that this function assumes that points1 and points2 are feature points from cameras with the
2631
same camera intrinsic matrix. If this assumption does not hold for your use case, use another
2632
function overload or #undistortPoints with `P = cv::NoArray()` for both cameras to transform image
2633
points to normalized image coordinates, which are valid for the identity camera intrinsic matrix.
2634
When passing these coordinates, pass the identity matrix for this parameter.
2635
@param method Method for computing an essential matrix.
2636
-   @ref RANSAC for the RANSAC algorithm.
2637
-   @ref LMEDS for the LMedS algorithm.
2638
@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of
2639
confidence (probability) that the estimated matrix is correct.
2640
@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar
2641
line in pixels, beyond which the point is considered an outlier and is not used for computing the
2642
final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
2643
point localization, image resolution, and the image noise.
2644
@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1
2645
for the other points. The array is computed only in the RANSAC and LMedS methods.
2646
@param maxIters The maximum number of robust method iterations.
2647
2648
This function estimates essential matrix based on the five-point algorithm solver in @cite Nister03 .
2649
@cite SteweniusCFS is also a related. The epipolar geometry is described by the following equation:
2650
2651
\f[[p_2; 1]^T K^{-T} E K^{-1} [p_1; 1] = 0\f]
2652
2653
where \f$E\f$ is an essential matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the
2654
second images, respectively. The result of this function may be passed further to
2655
#decomposeEssentialMat or #recoverPose to recover the relative pose between cameras.
2656
 */
2657
CV_EXPORTS_W
2658
Mat findEssentialMat(
2659
    InputArray points1, InputArray points2,
2660
    InputArray cameraMatrix, int method = RANSAC,
2661
    double prob = 0.999, double threshold = 1.0,
2662
    int maxIters = 1000, OutputArray mask = noArray()
2663
);
2664
2665
/** @overload */
2666
CV_EXPORTS
2667
Mat findEssentialMat(
2668
    InputArray points1, InputArray points2,
2669
    InputArray cameraMatrix, int method,
2670
    double prob, double threshold,
2671
    OutputArray mask
2672
);  // TODO remove from OpenCV 5.0
2673
2674
/** @overload
2675
@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should
2676
be floating-point (single or double precision).
2677
@param points2 Array of the second image points of the same size and format as points1 .
2678
@param focal focal length of the camera. Note that this function assumes that points1 and points2
2679
are feature points from cameras with same focal length and principal point.
2680
@param pp principal point of the camera.
2681
@param method Method for computing a fundamental matrix.
2682
-   @ref RANSAC for the RANSAC algorithm.
2683
-   @ref LMEDS for the LMedS algorithm.
2684
@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar
2685
line in pixels, beyond which the point is considered an outlier and is not used for computing the
2686
final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
2687
point localization, image resolution, and the image noise.
2688
@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of
2689
confidence (probability) that the estimated matrix is correct.
2690
@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1
2691
for the other points. The array is computed only in the RANSAC and LMedS methods.
2692
@param maxIters The maximum number of robust method iterations.
2693
2694
This function differs from the one above that it computes camera intrinsic matrix from focal length and
2695
principal point:
2696
2697
\f[A =
2698
\begin{bmatrix}
2699
f & 0 & x_{pp}  \\
2700
0 & f & y_{pp}  \\
2701
0 & 0 & 1
2702
\end{bmatrix}\f]
2703
 */
2704
CV_EXPORTS_W
2705
Mat findEssentialMat(
2706
    InputArray points1, InputArray points2,
2707
    double focal = 1.0, Point2d pp = Point2d(0, 0),
2708
    int method = RANSAC, double prob = 0.999,
2709
    double threshold = 1.0, int maxIters = 1000,
2710
    OutputArray mask = noArray()
2711
);
2712
2713
/** @overload */
2714
CV_EXPORTS
2715
Mat findEssentialMat(
2716
    InputArray points1, InputArray points2,
2717
    double focal, Point2d pp,
2718
    int method, double prob,
2719
    double threshold, OutputArray mask
2720
);  // TODO remove from OpenCV 5.0
2721
2722
/** @brief Calculates an essential matrix from the corresponding points in two images from potentially two different cameras.
2723
2724
@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should
2725
be floating-point (single or double precision).
2726
@param points2 Array of the second image points of the same size and format as points1.
2727
@param cameraMatrix1 Camera matrix for the first camera \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
2728
@param cameraMatrix2 Camera matrix for the second camera \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
2729
@param distCoeffs1 Input vector of distortion coefficients for the first camera
2730
\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
2731
of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
2732
@param distCoeffs2 Input vector of distortion coefficients for the second camera
2733
\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
2734
of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
2735
@param method Method for computing an essential matrix.
2736
-   @ref RANSAC for the RANSAC algorithm.
2737
-   @ref LMEDS for the LMedS algorithm.
2738
@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of
2739
confidence (probability) that the estimated matrix is correct.
2740
@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar
2741
line in pixels, beyond which the point is considered an outlier and is not used for computing the
2742
final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
2743
point localization, image resolution, and the image noise.
2744
@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1
2745
for the other points. The array is computed only in the RANSAC and LMedS methods.
2746
2747
This function estimates essential matrix based on the five-point algorithm solver in @cite Nister03 .
2748
@cite SteweniusCFS is also a related. The epipolar geometry is described by the following equation:
2749
2750
\f[[p_2; 1]^T K^{-T} E K^{-1} [p_1; 1] = 0\f]
2751
2752
where \f$E\f$ is an essential matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the
2753
second images, respectively. The result of this function may be passed further to
2754
#decomposeEssentialMat or  #recoverPose to recover the relative pose between cameras.
2755
 */
2756
CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2,
2757
                                 InputArray cameraMatrix1, InputArray distCoeffs1,
2758
                                 InputArray cameraMatrix2, InputArray distCoeffs2,
2759
                                 int method = RANSAC,
2760
                                 double prob = 0.999, double threshold = 1.0,
2761
                                 OutputArray mask = noArray() );
2762
2763
2764
CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2,
2765
                      InputArray cameraMatrix1, InputArray cameraMatrix2,
2766
                      InputArray dist_coeff1, InputArray dist_coeff2, OutputArray mask,
2767
                      const UsacParams &params);
2768
2769
/** @brief Decompose an essential matrix to possible rotations and translation.
2770
2771
@param E The input essential matrix.
2772
@param R1 One possible rotation matrix.
2773
@param R2 Another possible rotation matrix.
2774
@param t One possible translation.
2775
2776
This function decomposes the essential matrix E using svd decomposition @cite HartleyZ00. In
2777
general, four possible poses exist for the decomposition of E. They are \f$[R_1, t]\f$,
2778
\f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$.
2779
2780
If E gives the epipolar constraint \f$[p_2; 1]^T A^{-T} E A^{-1} [p_1; 1] = 0\f$ between the image
2781
points \f$p_1\f$ in the first image and \f$p_2\f$ in second image, then any of the tuples
2782
\f$[R_1, t]\f$, \f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$ is a change of basis from the first
2783
camera's coordinate system to the second camera's coordinate system. However, by decomposing E, one
2784
can only get the direction of the translation. For this reason, the translation t is returned with
2785
unit length.
2786
 */
2787
CV_EXPORTS_W void decomposeEssentialMat( InputArray E, OutputArray R1, OutputArray R2, OutputArray t );
2788
2789
/** @brief Recovers the relative camera rotation and the translation from corresponding points in two images from two different cameras, using cheirality check. Returns the number of
2790
inliers that pass the check.
2791
2792
@param points1 Array of N 2D points from the first image. The point coordinates should be
2793
floating-point (single or double precision).
2794
@param points2 Array of the second image points of the same size and format as points1 .
2795
@param cameraMatrix1 Input/output camera matrix for the first camera, the same as in
2796
@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below.
2797
@param distCoeffs1 Input/output vector of distortion coefficients, the same as in
2798
@ref calibrateCamera.
2799
@param cameraMatrix2 Input/output camera matrix for the first camera, the same as in
2800
@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below.
2801
@param distCoeffs2 Input/output vector of distortion coefficients, the same as in
2802
@ref calibrateCamera.
2803
@param E The output essential matrix.
2804
@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple
2805
that performs a change of basis from the first camera's coordinate system to the second camera's
2806
coordinate system. Note that, in general, t can not be used for this tuple, see the parameter
2807
described below.
2808
@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and
2809
therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit
2810
length.
2811
@param method Method for computing an essential matrix.
2812
-   @ref RANSAC for the RANSAC algorithm.
2813
-   @ref LMEDS for the LMedS algorithm.
2814
@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of
2815
confidence (probability) that the estimated matrix is correct.
2816
@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar
2817
line in pixels, beyond which the point is considered an outlier and is not used for computing the
2818
final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
2819
point localization, image resolution, and the image noise.
2820
@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks
2821
inliers in points1 and points2 for then given essential matrix E. Only these inliers will be used to
2822
recover pose. In the output mask only inliers which pass the cheirality check.
2823
2824
This function decomposes an essential matrix using @ref decomposeEssentialMat and then verifies
2825
possible pose hypotheses by doing cheirality check. The cheirality check means that the
2826
triangulated 3D points should have positive depth. Some details can be found in @cite Nister03.
2827
2828
This function can be used to process the output E and mask from @ref findEssentialMat. In this
2829
scenario, points1 and points2 are the same input for findEssentialMat.:
2830
@code
2831
    // Example. Estimation of fundamental matrix using the RANSAC algorithm
2832
    int point_count = 100;
2833
    vector<Point2f> points1(point_count);
2834
    vector<Point2f> points2(point_count);
2835
2836
    // initialize the points here ...
2837
    for( int i = 0; i < point_count; i++ )
2838
    {
2839
        points1[i] = ...;
2840
        points2[i] = ...;
2841
    }
2842
2843
    // Input: camera calibration of both cameras, for example using intrinsic chessboard calibration.
2844
    Mat cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2;
2845
2846
    // Output: Essential matrix, relative rotation and relative translation.
2847
    Mat E, R, t, mask;
2848
2849
    recoverPose(points1, points2, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, E, R, t, mask);
2850
@endcode
2851
 */
2852
CV_EXPORTS_W int recoverPose( InputArray points1, InputArray points2,
2853
                            InputArray cameraMatrix1, InputArray distCoeffs1,
2854
                            InputArray cameraMatrix2, InputArray distCoeffs2,
2855
                            OutputArray E, OutputArray R, OutputArray t,
2856
                            int method = cv::RANSAC, double prob = 0.999, double threshold = 1.0,
2857
                            InputOutputArray mask = noArray());
2858
2859
/** @brief Recovers the relative camera rotation and the translation from an estimated essential
2860
matrix and the corresponding points in two images, using chirality check. Returns the number of
2861
inliers that pass the check.
2862
2863
@param E The input essential matrix.
2864
@param points1 Array of N 2D points from the first image. The point coordinates should be
2865
floating-point (single or double precision).
2866
@param points2 Array of the second image points of the same size and format as points1 .
2867
@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
2868
Note that this function assumes that points1 and points2 are feature points from cameras with the
2869
same camera intrinsic matrix.
2870
@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple
2871
that performs a change of basis from the first camera's coordinate system to the second camera's
2872
coordinate system. Note that, in general, t can not be used for this tuple, see the parameter
2873
described below.
2874
@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and
2875
therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit
2876
length.
2877
@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks
2878
inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to
2879
recover pose. In the output mask only inliers which pass the chirality check.
2880
2881
This function decomposes an essential matrix using @ref decomposeEssentialMat and then verifies
2882
possible pose hypotheses by doing chirality check. The chirality check means that the
2883
triangulated 3D points should have positive depth. Some details can be found in @cite Nister03.
2884
2885
This function can be used to process the output E and mask from @ref findEssentialMat. In this
2886
scenario, points1 and points2 are the same input for #findEssentialMat :
2887
@code
2888
    // Example. Estimation of fundamental matrix using the RANSAC algorithm
2889
    int point_count = 100;
2890
    vector<Point2f> points1(point_count);
2891
    vector<Point2f> points2(point_count);
2892
2893
    // initialize the points here ...
2894
    for( int i = 0; i < point_count; i++ )
2895
    {
2896
        points1[i] = ...;
2897
        points2[i] = ...;
2898
    }
2899
2900
    // cametra matrix with both focal lengths = 1, and principal point = (0, 0)
2901
    Mat cameraMatrix = Mat::eye(3, 3, CV_64F);
2902
2903
    Mat E, R, t, mask;
2904
2905
    E = findEssentialMat(points1, points2, cameraMatrix, RANSAC, 0.999, 1.0, mask);
2906
    recoverPose(E, points1, points2, cameraMatrix, R, t, mask);
2907
@endcode
2908
 */
2909
CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2,
2910
                            InputArray cameraMatrix, OutputArray R, OutputArray t,
2911
                            InputOutputArray mask = noArray() );
2912
2913
/** @overload
2914
@param E The input essential matrix.
2915
@param points1 Array of N 2D points from the first image. The point coordinates should be
2916
floating-point (single or double precision).
2917
@param points2 Array of the second image points of the same size and format as points1 .
2918
@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple
2919
that performs a change of basis from the first camera's coordinate system to the second camera's
2920
coordinate system. Note that, in general, t can not be used for this tuple, see the parameter
2921
description below.
2922
@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and
2923
therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit
2924
length.
2925
@param focal Focal length of the camera. Note that this function assumes that points1 and points2
2926
are feature points from cameras with same focal length and principal point.
2927
@param pp principal point of the camera.
2928
@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks
2929
inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to
2930
recover pose. In the output mask only inliers which pass the chirality check.
2931
2932
This function differs from the one above that it computes camera intrinsic matrix from focal length and
2933
principal point:
2934
2935
\f[A =
2936
\begin{bmatrix}
2937
f & 0 & x_{pp}  \\
2938
0 & f & y_{pp}  \\
2939
0 & 0 & 1
2940
\end{bmatrix}\f]
2941
 */
2942
CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2,
2943
                            OutputArray R, OutputArray t,
2944
                            double focal = 1.0, Point2d pp = Point2d(0, 0),
2945
                            InputOutputArray mask = noArray() );
2946
2947
/** @overload
2948
@param E The input essential matrix.
2949
@param points1 Array of N 2D points from the first image. The point coordinates should be
2950
floating-point (single or double precision).
2951
@param points2 Array of the second image points of the same size and format as points1.
2952
@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
2953
Note that this function assumes that points1 and points2 are feature points from cameras with the
2954
same camera intrinsic matrix.
2955
@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple
2956
that performs a change of basis from the first camera's coordinate system to the second camera's
2957
coordinate system. Note that, in general, t can not be used for this tuple, see the parameter
2958
description below.
2959
@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and
2960
therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit
2961
length.
2962
@param distanceThresh threshold distance which is used to filter out far away points (i.e. infinite
2963
points).
2964
@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks
2965
inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to
2966
recover pose. In the output mask only inliers which pass the chirality check.
2967
@param triangulatedPoints 3D points which were reconstructed by triangulation.
2968
2969
This function differs from the one above that it outputs the triangulated 3D point that are used for
2970
the chirality check.
2971
 */
2972
CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2,
2973
                            InputArray cameraMatrix, OutputArray R, OutputArray t, double distanceThresh, InputOutputArray mask = noArray(),
2974
                            OutputArray triangulatedPoints = noArray());
2975
2976
/** @brief For points in an image of a stereo pair, computes the corresponding epilines in the other image.
2977
2978
@param points Input points. \f$N \times 1\f$ or \f$1 \times N\f$ matrix of type CV_32FC2 or
2979
vector\<Point2f\> .
2980
@param whichImage Index of the image (1 or 2) that contains the points .
2981
@param F Fundamental matrix that can be estimated using #findFundamentalMat or #stereoRectify .
2982
@param lines Output vector of the epipolar lines corresponding to the points in the other image.
2983
Each line \f$ax + by + c=0\f$ is encoded by 3 numbers \f$(a, b, c)\f$ .
2984
2985
For every point in one of the two images of a stereo pair, the function finds the equation of the
2986
corresponding epipolar line in the other image.
2987
2988
From the fundamental matrix definition (see #findFundamentalMat ), line \f$l^{(2)}_i\f$ in the second
2989
image for the point \f$p^{(1)}_i\f$ in the first image (when whichImage=1 ) is computed as:
2990
2991
\f[l^{(2)}_i = F p^{(1)}_i\f]
2992
2993
And vice versa, when whichImage=2, \f$l^{(1)}_i\f$ is computed from \f$p^{(2)}_i\f$ as:
2994
2995
\f[l^{(1)}_i = F^T p^{(2)}_i\f]
2996
2997
Line coefficients are defined up to a scale. They are normalized so that \f$a_i^2+b_i^2=1\f$ .
2998
 */
2999
CV_EXPORTS_W void computeCorrespondEpilines( InputArray points, int whichImage,
3000
                                             InputArray F, OutputArray lines );
3001
3002
/** @brief This function reconstructs 3-dimensional points (in homogeneous coordinates) by using
3003
their observations with a stereo camera.
3004
3005
@param projMatr1 3x4 projection matrix of the first camera, i.e. this matrix projects 3D points
3006
given in the world's coordinate system into the first image.
3007
@param projMatr2 3x4 projection matrix of the second camera, i.e. this matrix projects 3D points
3008
given in the world's coordinate system into the second image.
3009
@param projPoints1 2xN array of feature points in the first image. In the case of the c++ version,
3010
it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1.
3011
@param projPoints2 2xN array of corresponding points in the second image. In the case of the c++
3012
version, it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1.
3013
@param points4D 4xN array of reconstructed points in homogeneous coordinates. These points are
3014
returned in the world's coordinate system.
3015
3016
@note
3017
   Keep in mind that all input data should be of float type in order for this function to work.
3018
3019
@note
3020
   If the projection matrices from @ref stereoRectify are used, then the returned points are
3021
   represented in the first camera's rectified coordinate system.
3022
3023
@sa
3024
   reprojectImageTo3D
3025
 */
3026
CV_EXPORTS_W void triangulatePoints( InputArray projMatr1, InputArray projMatr2,
3027
                                     InputArray projPoints1, InputArray projPoints2,
3028
                                     OutputArray points4D );
3029
3030
/** @brief Refines coordinates of corresponding points.
3031
3032
@param F 3x3 fundamental matrix.
3033
@param points1 1xN array containing the first set of points.
3034
@param points2 1xN array containing the second set of points.
3035
@param newPoints1 The optimized points1.
3036
@param newPoints2 The optimized points2.
3037
3038
The function implements the Optimal Triangulation Method (see Multiple View Geometry @cite HartleyZ00 for details).
3039
For each given point correspondence points1[i] \<-\> points2[i], and a fundamental matrix F, it
3040
computes the corrected correspondences newPoints1[i] \<-\> newPoints2[i] that minimize the geometric
3041
error \f$d(points1[i], newPoints1[i])^2 + d(points2[i],newPoints2[i])^2\f$ (where \f$d(a,b)\f$ is the
3042
geometric distance between points \f$a\f$ and \f$b\f$ ) subject to the epipolar constraint
3043
\f$newPoints2^T \cdot F \cdot newPoints1 = 0\f$ .
3044
 */
3045
CV_EXPORTS_W void correctMatches( InputArray F, InputArray points1, InputArray points2,
3046
                                  OutputArray newPoints1, OutputArray newPoints2 );
3047
3048
/** @brief Filters off small noise blobs (speckles) in the disparity map
3049
3050
@param img The input 16-bit signed disparity image
3051
@param newVal The disparity value used to paint-off the speckles
3052
@param maxSpeckleSize The maximum speckle size to consider it a speckle. Larger blobs are not
3053
affected by the algorithm
3054
@param maxDiff Maximum difference between neighbor disparity pixels to put them into the same
3055
blob. Note that since StereoBM, StereoSGBM and may be other algorithms return a fixed-point
3056
disparity map, where disparity values are multiplied by 16, this scale factor should be taken into
3057
account when specifying this parameter value.
3058
@param buf The optional temporary buffer to avoid memory allocation within the function.
3059
 */
3060
CV_EXPORTS_W void filterSpeckles( InputOutputArray img, double newVal,
3061
                                  int maxSpeckleSize, double maxDiff,
3062
                                  InputOutputArray buf = noArray() );
3063
3064
//! computes valid disparity ROI from the valid ROIs of the rectified images (that are returned by #stereoRectify)
3065
CV_EXPORTS_W Rect getValidDisparityROI( Rect roi1, Rect roi2,
3066
                                        int minDisparity, int numberOfDisparities,
3067
                                        int blockSize );
3068
3069
//! validates disparity using the left-right check. The matrix "cost" should be computed by the stereo correspondence algorithm
3070
CV_EXPORTS_W void validateDisparity( InputOutputArray disparity, InputArray cost,
3071
                                     int minDisparity, int numberOfDisparities,
3072
                                     int disp12MaxDisp = 1 );
3073
3074
/** @brief Reprojects a disparity image to 3D space.
3075
3076
@param disparity Input single-channel 8-bit unsigned, 16-bit signed, 32-bit signed or 32-bit
3077
floating-point disparity image. The values of 8-bit / 16-bit signed formats are assumed to have no
3078
fractional bits. If the disparity is 16-bit signed format, as computed by @ref StereoBM or
3079
@ref StereoSGBM and maybe other algorithms, it should be divided by 16 (and scaled to float) before
3080
being used here.
3081
@param _3dImage Output 3-channel floating-point image of the same size as disparity. Each element of
3082
_3dImage(x,y) contains 3D coordinates of the point (x,y) computed from the disparity map. If one
3083
uses Q obtained by @ref stereoRectify, then the returned points are represented in the first
3084
camera's rectified coordinate system.
3085
@param Q \f$4 \times 4\f$ perspective transformation matrix that can be obtained with
3086
@ref stereoRectify.
3087
@param handleMissingValues Indicates, whether the function should handle missing values (i.e.
3088
points where the disparity was not computed). If handleMissingValues=true, then pixels with the
3089
minimal disparity that corresponds to the outliers (see StereoMatcher::compute ) are transformed
3090
to 3D points with a very large Z value (currently set to 10000).
3091
@param ddepth The optional output array depth. If it is -1, the output image will have CV_32F
3092
depth. ddepth can also be set to CV_16S, CV_32S or CV_32F.
3093
3094
The function transforms a single-channel disparity map to a 3-channel image representing a 3D
3095
surface. That is, for each pixel (x,y) and the corresponding disparity d=disparity(x,y) , it
3096
computes:
3097
3098
\f[\begin{bmatrix}
3099
X \\
3100
Y \\
3101
Z \\
3102
W
3103
\end{bmatrix} = Q \begin{bmatrix}
3104
x \\
3105
y \\
3106
\texttt{disparity} (x,y) \\
3107
1
3108
\end{bmatrix}.\f]
3109
3110
@sa
3111
   To reproject a sparse set of points {(x,y,d),...} to 3D space, use perspectiveTransform.
3112
 */
3113
CV_EXPORTS_W void reprojectImageTo3D( InputArray disparity,
3114
                                      OutputArray _3dImage, InputArray Q,
3115
                                      bool handleMissingValues = false,
3116
                                      int ddepth = -1 );
3117
3118
/** @brief Calculates the Sampson Distance between two points.
3119
3120
The function cv::sampsonDistance calculates and returns the first order approximation of the geometric error as:
3121
\f[
3122
sd( \texttt{pt1} , \texttt{pt2} )=
3123
\frac{(\texttt{pt2}^t \cdot \texttt{F} \cdot \texttt{pt1})^2}
3124
{((\texttt{F} \cdot \texttt{pt1})(0))^2 +
3125
((\texttt{F} \cdot \texttt{pt1})(1))^2 +
3126
((\texttt{F}^t \cdot \texttt{pt2})(0))^2 +
3127
((\texttt{F}^t \cdot \texttt{pt2})(1))^2}
3128
\f]
3129
The fundamental matrix may be calculated using the #findFundamentalMat function. See @cite HartleyZ00 11.4.3 for details.
3130
@param pt1 first homogeneous 2d point
3131
@param pt2 second homogeneous 2d point
3132
@param F fundamental matrix
3133
@return The computed Sampson distance.
3134
*/
3135
CV_EXPORTS_W double sampsonDistance(InputArray pt1, InputArray pt2, InputArray F);
3136
3137
/** @brief Computes an optimal affine transformation between two 3D point sets.
3138
3139
It computes
3140
\f[
3141
\begin{bmatrix}
3142
x\\
3143
y\\
3144
z\\
3145
\end{bmatrix}
3146
=
3147
\begin{bmatrix}
3148
a_{11} & a_{12} & a_{13}\\
3149
a_{21} & a_{22} & a_{23}\\
3150
a_{31} & a_{32} & a_{33}\\
3151
\end{bmatrix}
3152
\begin{bmatrix}
3153
X\\
3154
Y\\
3155
Z\\
3156
\end{bmatrix}
3157
+
3158
\begin{bmatrix}
3159
b_1\\
3160
b_2\\
3161
b_3\\
3162
\end{bmatrix}
3163
\f]
3164
3165
@param src First input 3D point set containing \f$(X,Y,Z)\f$.
3166
@param dst Second input 3D point set containing \f$(x,y,z)\f$.
3167
@param out Output 3D affine transformation matrix \f$3 \times 4\f$ of the form
3168
\f[
3169
\begin{bmatrix}
3170
a_{11} & a_{12} & a_{13} & b_1\\
3171
a_{21} & a_{22} & a_{23} & b_2\\
3172
a_{31} & a_{32} & a_{33} & b_3\\
3173
\end{bmatrix}
3174
\f]
3175
@param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier).
3176
@param ransacThreshold Maximum reprojection error in the RANSAC algorithm to consider a point as
3177
an inlier.
3178
@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything
3179
between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation
3180
significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation.
3181
3182
The function estimates an optimal 3D affine transformation between two 3D point sets using the
3183
RANSAC algorithm.
3184
 */
3185
CV_EXPORTS_W  int estimateAffine3D(InputArray src, InputArray dst,
3186
                                   OutputArray out, OutputArray inliers,
3187
                                   double ransacThreshold = 3, double confidence = 0.99);
3188
3189
/** @brief Computes an optimal affine transformation between two 3D point sets.
3190
3191
It computes \f$R,s,t\f$ minimizing \f$\sum{i} dst_i - c \cdot R \cdot src_i \f$
3192
where \f$R\f$ is a 3x3 rotation matrix, \f$t\f$ is a 3x1 translation vector and \f$s\f$ is a
3193
scalar size value. This is an implementation of the algorithm by Umeyama \cite umeyama1991least .
3194
The estimated affine transform has a homogeneous scale which is a subclass of affine
3195
transformations with 7 degrees of freedom. The paired point sets need to comprise at least 3
3196
points each.
3197
3198
@param src First input 3D point set.
3199
@param dst Second input 3D point set.
3200
@param scale If null is passed, the scale parameter c will be assumed to be 1.0.
3201
Else the pointed-to variable will be set to the optimal scale.
3202
@param force_rotation If true, the returned rotation will never be a reflection.
3203
This might be unwanted, e.g. when optimizing a transform between a right- and a
3204
left-handed coordinate system.
3205
@return 3D affine transformation matrix \f$3 \times 4\f$ of the form
3206
\f[T =
3207
\begin{bmatrix}
3208
R & t\\
3209
\end{bmatrix}
3210
\f]
3211
3212
 */
3213
CV_EXPORTS_W   cv::Mat estimateAffine3D(InputArray src, InputArray dst,
3214
                                        CV_OUT double* scale = nullptr, bool force_rotation = true);
3215
3216
/** @brief Computes an optimal translation between two 3D point sets.
3217
 *
3218
 * It computes
3219
 * \f[
3220
 * \begin{bmatrix}
3221
 * x\\
3222
 * y\\
3223
 * z\\
3224
 * \end{bmatrix}
3225
 * =
3226
 * \begin{bmatrix}
3227
 * X\\
3228
 * Y\\
3229
 * Z\\
3230
 * \end{bmatrix}
3231
 * +
3232
 * \begin{bmatrix}
3233
 * b_1\\
3234
 * b_2\\
3235
 * b_3\\
3236
 * \end{bmatrix}
3237
 * \f]
3238
 *
3239
 * @param src First input 3D point set containing \f$(X,Y,Z)\f$.
3240
 * @param dst Second input 3D point set containing \f$(x,y,z)\f$.
3241
 * @param out Output 3D translation vector \f$3 \times 1\f$ of the form
3242
 * \f[
3243
 * \begin{bmatrix}
3244
 * b_1 \\
3245
 * b_2 \\
3246
 * b_3 \\
3247
 * \end{bmatrix}
3248
 * \f]
3249
 * @param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier).
3250
 * @param ransacThreshold Maximum reprojection error in the RANSAC algorithm to consider a point as
3251
 * an inlier.
3252
 * @param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything
3253
 * between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation
3254
 * significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation.
3255
 *
3256
 * The function estimates an optimal 3D translation between two 3D point sets using the
3257
 * RANSAC algorithm.
3258
 *  */
3259
CV_EXPORTS_W  int estimateTranslation3D(InputArray src, InputArray dst,
3260
                                        OutputArray out, OutputArray inliers,
3261
                                        double ransacThreshold = 3, double confidence = 0.99);
3262
3263
/** @brief Computes an optimal affine transformation between two 2D point sets.
3264
3265
It computes
3266
\f[
3267
\begin{bmatrix}
3268
x\\
3269
y\\
3270
\end{bmatrix}
3271
=
3272
\begin{bmatrix}
3273
a_{11} & a_{12}\\
3274
a_{21} & a_{22}\\
3275
\end{bmatrix}
3276
\begin{bmatrix}
3277
X\\
3278
Y\\
3279
\end{bmatrix}
3280
+
3281
\begin{bmatrix}
3282
b_1\\
3283
b_2\\
3284
\end{bmatrix}
3285
\f]
3286
3287
@param from First input 2D point set containing \f$(X,Y)\f$.
3288
@param to Second input 2D point set containing \f$(x,y)\f$.
3289
@param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier).
3290
@param method Robust method used to compute transformation. The following methods are possible:
3291
-   @ref RANSAC - RANSAC-based robust method
3292
-   @ref LMEDS - Least-Median robust method
3293
RANSAC is the default method.
3294
@param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider
3295
a point as an inlier. Applies only to RANSAC.
3296
@param maxIters The maximum number of robust method iterations.
3297
@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything
3298
between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation
3299
significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation.
3300
@param refineIters Maximum number of iterations of refining algorithm (Levenberg-Marquardt).
3301
Passing 0 will disable refining, so the output matrix will be output of robust method.
3302
3303
@return Output 2D affine transformation matrix \f$2 \times 3\f$ or empty matrix if transformation
3304
could not be estimated. The returned matrix has the following form:
3305
\f[
3306
\begin{bmatrix}
3307
a_{11} & a_{12} & b_1\\
3308
a_{21} & a_{22} & b_2\\
3309
\end{bmatrix}
3310
\f]
3311
3312
The function estimates an optimal 2D affine transformation between two 2D point sets using the
3313
selected robust algorithm.
3314
3315
The computed transformation is then refined further (using only inliers) with the
3316
Levenberg-Marquardt method to reduce the re-projection error even more.
3317
3318
@note
3319
The RANSAC method can handle practically any ratio of outliers but needs a threshold to
3320
distinguish inliers from outliers. The method LMeDS does not need any threshold but it works
3321
correctly only when there are more than 50% of inliers.
3322
3323
@sa estimateAffinePartial2D, getAffineTransform
3324
*/
3325
CV_EXPORTS_W cv::Mat estimateAffine2D(InputArray from, InputArray to, OutputArray inliers = noArray(),
3326
                                  int method = RANSAC, double ransacReprojThreshold = 3,
3327
                                  size_t maxIters = 2000, double confidence = 0.99,
3328
                                  size_t refineIters = 10);
3329
3330
3331
CV_EXPORTS_W cv::Mat estimateAffine2D(InputArray pts1, InputArray pts2, OutputArray inliers,
3332
                     const UsacParams &params);
3333
3334
/** @brief Computes an optimal limited affine transformation with 4 degrees of freedom between
3335
two 2D point sets.
3336
3337
@param from First input 2D point set.
3338
@param to Second input 2D point set.
3339
@param inliers Output vector indicating which points are inliers.
3340
@param method Robust method used to compute transformation. The following methods are possible:
3341
-   @ref RANSAC - RANSAC-based robust method
3342
-   @ref LMEDS - Least-Median robust method
3343
RANSAC is the default method.
3344
@param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider
3345
a point as an inlier. Applies only to RANSAC.
3346
@param maxIters The maximum number of robust method iterations.
3347
@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything
3348
between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation
3349
significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation.
3350
@param refineIters Maximum number of iterations of refining algorithm (Levenberg-Marquardt).
3351
Passing 0 will disable refining, so the output matrix will be output of robust method.
3352
3353
@return Output 2D affine transformation (4 degrees of freedom) matrix \f$2 \times 3\f$ or
3354
empty matrix if transformation could not be estimated.
3355
3356
The function estimates an optimal 2D affine transformation with 4 degrees of freedom limited to
3357
combinations of translation, rotation, and uniform scaling. Uses the selected algorithm for robust
3358
estimation.
3359
3360
The computed transformation is then refined further (using only inliers) with the
3361
Levenberg-Marquardt method to reduce the re-projection error even more.
3362
3363
Estimated transformation matrix is:
3364
\f[ \begin{bmatrix} \cos(\theta) \cdot s & -\sin(\theta) \cdot s & t_x \\
3365
                \sin(\theta) \cdot s & \cos(\theta) \cdot s & t_y
3366
\end{bmatrix} \f]
3367
Where \f$ \theta \f$ is the rotation angle, \f$ s \f$ the scaling factor and \f$ t_x, t_y \f$ are
3368
translations in \f$ x, y \f$ axes respectively.
3369
3370
@note
3371
The RANSAC method can handle practically any ratio of outliers but need a threshold to
3372
distinguish inliers from outliers. The method LMeDS does not need any threshold but it works
3373
correctly only when there are more than 50% of inliers.
3374
3375
@sa estimateAffine2D, getAffineTransform
3376
*/
3377
CV_EXPORTS_W cv::Mat estimateAffinePartial2D(InputArray from, InputArray to, OutputArray inliers = noArray(),
3378
                                  int method = RANSAC, double ransacReprojThreshold = 3,
3379
                                  size_t maxIters = 2000, double confidence = 0.99,
3380
                                  size_t refineIters = 10);
3381
3382
/** @brief Computes a pure 2D translation between two 2D point sets.
3383
3384
It computes
3385
\f[
3386
\begin{bmatrix}
3387
x\\
3388
y
3389
\end{bmatrix}
3390
=
3391
\begin{bmatrix}
3392
1 & 0\\
3393
0 & 1
3394
\end{bmatrix}
3395
\begin{bmatrix}
3396
X\\
3397
Y
3398
\end{bmatrix}
3399
+
3400
\begin{bmatrix}
3401
t_x\\
3402
t_y
3403
\end{bmatrix}.
3404
\f]
3405
3406
@param from First input 2D point set containing \f$(X,Y)\f$.
3407
@param to Second input 2D point set containing \f$(x,y)\f$.
3408
@param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier).
3409
@param method Robust method used to compute the transformation. The following methods are possible:
3410
-   @ref RANSAC - RANSAC-based robust method
3411
-   @ref LMEDS - Least-Median robust method
3412
RANSAC is the default method.
3413
@param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider
3414
a point as an inlier. Applies only to RANSAC.
3415
@param maxIters The maximum number of robust method iterations.
3416
@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything
3417
between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation
3418
significantly. Values lower than 0.8–0.9 can result in an incorrectly estimated transformation.
3419
@param refineIters Maximum number of iterations of the refining algorithm. For pure translation
3420
the least-squares solution on inliers is closed-form, so passing 0 is recommended (no additional refine).
3421
3422
@return A 2D translation vector \f$[t_x, t_y]^T\f$ as `cv::Vec2d`. If the translation could not be
3423
estimated, both components are set to NaN and, if @p inliers is provided, the mask is filled with zeros.
3424
3425
\par Converting to a 2x3 transformation matrix:
3426
\f[
3427
\begin{bmatrix}
3428
1 & 0 & t_x\\
3429
0 & 1 & t_y
3430
\end{bmatrix}
3431
\f]
3432
3433
@code{.cpp}
3434
cv::Vec2d t = cv::estimateTranslation2D(from, to, inliers);
3435
cv::Mat T = (cv::Mat_<double>(2,3) << 1,0,t[0], 0,1,t[1]);
3436
@endcode
3437
3438
The function estimates a pure 2D translation between two 2D point sets using the selected robust
3439
algorithm. Inliers are determined by the reprojection error threshold.
3440
3441
@note
3442
The RANSAC method can handle practically any ratio of outliers but needs a threshold to
3443
distinguish inliers from outliers. The method LMeDS does not need any threshold but works
3444
correctly only when there are more than 50% inliers.
3445
3446
@sa estimateAffine2D, estimateAffinePartial2D, getAffineTransform
3447
*/
3448
CV_EXPORTS_W cv::Vec2d estimateTranslation2D(InputArray from, InputArray to, OutputArray inliers = noArray(),
3449
                                             int method = RANSAC,
3450
                                             double ransacReprojThreshold = 3,
3451
                                             size_t maxIters = 2000, double confidence = 0.99,
3452
                                             size_t refineIters = 0);
3453
3454
/** @example samples/cpp/tutorial_code/features2D/Homography/decompose_homography.cpp
3455
An example program with homography decomposition.
3456
3457
Check @ref tutorial_homography "the corresponding tutorial" for more details.
3458
*/
3459
3460
/** @brief Decompose a homography matrix to rotation(s), translation(s) and plane normal(s).
3461
3462
@param H The input homography matrix between two images.
3463
@param K The input camera intrinsic matrix.
3464
@param rotations Array of rotation matrices.
3465
@param translations Array of translation matrices.
3466
@param normals Array of plane normal matrices.
3467
3468
This function extracts relative camera motion between two views of a planar object and returns up to
3469
four mathematical solution tuples of rotation, translation, and plane normal. The decomposition of
3470
the homography matrix H is described in detail in @cite Malis2007.
3471
3472
If the homography H, induced by the plane, gives the constraint
3473
\f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f] on the source image points
3474
\f$p_i\f$ and the destination image points \f$p'_i\f$, then the tuple of rotations[k] and
3475
translations[k] is a change of basis from the source camera's coordinate system to the destination
3476
camera's coordinate system. However, by decomposing H, one can only get the translation normalized
3477
by the (typically unknown) depth of the scene, i.e. its direction but with normalized length.
3478
3479
If point correspondences are available, at least two solutions may further be invalidated, by
3480
applying positive depth constraint, i.e. all points must be in front of the camera.
3481
 */
3482
CV_EXPORTS_W int decomposeHomographyMat(InputArray H,
3483
                                        InputArray K,
3484
                                        OutputArrayOfArrays rotations,
3485
                                        OutputArrayOfArrays translations,
3486
                                        OutputArrayOfArrays normals);
3487
3488
/** @brief Filters homography decompositions based on additional information.
3489
3490
@param rotations Vector of rotation matrices.
3491
@param normals Vector of plane normal matrices.
3492
@param beforePoints Vector of (rectified) visible reference points before the homography is applied
3493
@param afterPoints Vector of (rectified) visible reference points after the homography is applied
3494
@param possibleSolutions Vector of int indices representing the viable solution set after filtering
3495
@param pointsMask optional Mat/Vector of 8u type representing the mask for the inliers as given by the #findHomography function
3496
3497
This function is intended to filter the output of the #decomposeHomographyMat based on additional
3498
information as described in @cite Malis2007 . The summary of the method: the #decomposeHomographyMat function
3499
returns 2 unique solutions and their "opposites" for a total of 4 solutions. If we have access to the
3500
sets of points visible in the camera frame before and after the homography transformation is applied,
3501
we can determine which are the true potential solutions and which are the opposites by verifying which
3502
homographies are consistent with all visible reference points being in front of the camera. The inputs
3503
are left unchanged; the filtered solution set is returned as indices into the existing one.
3504
3505
*/
3506
CV_EXPORTS_W void filterHomographyDecompByVisibleRefpoints(InputArrayOfArrays rotations,
3507
                                                           InputArrayOfArrays normals,
3508
                                                           InputArray beforePoints,
3509
                                                           InputArray afterPoints,
3510
                                                           OutputArray possibleSolutions,
3511
                                                           InputArray pointsMask = noArray());
3512
3513
/** @brief The base class for stereo correspondence algorithms.
3514
 */
3515
class CV_EXPORTS_W StereoMatcher : public Algorithm
3516
{
3517
public:
3518
    enum { DISP_SHIFT = 4,
3519
           DISP_SCALE = (1 << DISP_SHIFT)
3520
         };
3521
3522
    /** @brief Computes disparity map for the specified stereo pair
3523
3524
    @param left Left 8-bit single-channel image.
3525
    @param right Right image of the same size and the same type as the left one.
3526
    @param disparity Output disparity map. It has the same size as the input images. Some algorithms,
3527
    like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map (where each disparity value
3528
    has 4 fractional bits), whereas other algorithms output 32-bit floating-point disparity map.
3529
     */
3530
    CV_WRAP virtual void compute( InputArray left, InputArray right,
3531
                                  OutputArray disparity ) = 0;
3532
3533
    CV_WRAP virtual int getMinDisparity() const = 0;
3534
    CV_WRAP virtual void setMinDisparity(int minDisparity) = 0;
3535
3536
    CV_WRAP virtual int getNumDisparities() const = 0;
3537
    CV_WRAP virtual void setNumDisparities(int numDisparities) = 0;
3538
3539
    CV_WRAP virtual int getBlockSize() const = 0;
3540
    CV_WRAP virtual void setBlockSize(int blockSize) = 0;
3541
3542
    CV_WRAP virtual int getSpeckleWindowSize() const = 0;
3543
    CV_WRAP virtual void setSpeckleWindowSize(int speckleWindowSize) = 0;
3544
3545
    CV_WRAP virtual int getSpeckleRange() const = 0;
3546
    CV_WRAP virtual void setSpeckleRange(int speckleRange) = 0;
3547
3548
    CV_WRAP virtual int getDisp12MaxDiff() const = 0;
3549
    CV_WRAP virtual void setDisp12MaxDiff(int disp12MaxDiff) = 0;
3550
};
3551
3552
3553
/**
3554
 * @brief Class for computing stereo correspondence using the block matching algorithm, introduced and contributed to OpenCV by K. Konolige.
3555
 * @details This class implements a block matching algorithm for stereo correspondence, which is used to compute disparity maps from stereo image pairs. It provides methods to fine-tune parameters such as pre-filtering, texture thresholds, uniqueness ratios, and regions of interest (ROIs) to optimize performance and accuracy.
3556
 */
3557
class CV_EXPORTS_W StereoBM : public StereoMatcher
3558
{
3559
public:
3560
    /**
3561
     * @brief Pre-filter types for the stereo matching algorithm.
3562
     * @details These constants define the type of pre-filtering applied to the images before computing the disparity map.
3563
     * - PREFILTER_NORMALIZED_RESPONSE: Uses normalized response for pre-filtering.
3564
     * - PREFILTER_XSOBEL: Uses the X-Sobel operator for pre-filtering.
3565
     */
3566
    enum {
3567
        PREFILTER_NORMALIZED_RESPONSE = 0,  ///< Normalized response pre-filter
3568
        PREFILTER_XSOBEL              = 1   ///< X-Sobel pre-filter
3569
    };
3570
3571
    /**
3572
     * @brief Gets the type of pre-filtering currently used in the algorithm.
3573
     * @return The current pre-filter type: 0 for PREFILTER_NORMALIZED_RESPONSE or 1 for PREFILTER_XSOBEL.
3574
     */
3575
    CV_WRAP virtual int getPreFilterType() const = 0;
3576
3577
    /**
3578
     * @brief Sets the type of pre-filtering used in the algorithm.
3579
     * @param preFilterType The type of pre-filter to use. Possible values are:
3580
     * - PREFILTER_NORMALIZED_RESPONSE (0): Uses normalized response for pre-filtering.
3581
     * - PREFILTER_XSOBEL (1): Uses the X-Sobel operator for pre-filtering.
3582
     * @details The pre-filter type affects how the images are prepared before computing the disparity map. Different pre-filtering methods can enhance specific image features or reduce noise, influencing the quality of the disparity map.
3583
     */
3584
    CV_WRAP virtual void setPreFilterType(int preFilterType) = 0;
3585
3586
    /**
3587
     * @brief Gets the current size of the pre-filter kernel.
3588
     * @return The current pre-filter size.
3589
     */
3590
    CV_WRAP virtual int getPreFilterSize() const = 0;
3591
3592
    /**
3593
     * @brief Sets the size of the pre-filter kernel.
3594
     * @param preFilterSize The size of the pre-filter kernel. Must be an odd integer, typically between 5 and 255.
3595
     * @details The pre-filter size determines the spatial extent of the pre-filtering operation, which prepares the images for disparity computation by normalizing brightness and enhancing texture. Larger sizes reduce noise but may blur details, while smaller sizes preserve details but are more susceptible to noise.
3596
     */
3597
    CV_WRAP virtual void setPreFilterSize(int preFilterSize) = 0;
3598
3599
    /**
3600
     * @brief Gets the current truncation value for prefiltered pixels.
3601
     * @return The current pre-filter cap value.
3602
     */
3603
    CV_WRAP virtual int getPreFilterCap() const = 0;
3604
3605
    /**
3606
     * @brief Sets the truncation value for prefiltered pixels.
3607
     * @param preFilterCap The truncation value. Typically in the range [1, 63].
3608
     * @details This value caps the output of the pre-filter to [-preFilterCap, preFilterCap], helping to reduce the impact of noise and outliers in the pre-filtered image.
3609
     */
3610
    CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0;
3611
3612
    /**
3613
     * @brief Gets the current texture threshold value.
3614
     * @return The current texture threshold.
3615
     */
3616
    CV_WRAP virtual int getTextureThreshold() const = 0;
3617
3618
    /**
3619
     * @brief Sets the threshold for filtering low-texture regions.
3620
     * @param textureThreshold The threshold value. Must be non-negative.
3621
     * @details This parameter filters out regions with low texture, where establishing correspondences is difficult, thus reducing noise in the disparity map. Higher values filter more aggressively but may discard valid information.
3622
     */
3623
    CV_WRAP virtual void setTextureThreshold(int textureThreshold) = 0;
3624
3625
    /**
3626
     * @brief Gets the current uniqueness ratio value.
3627
     * @return The current uniqueness ratio.
3628
     */
3629
    CV_WRAP virtual int getUniquenessRatio() const = 0;
3630
3631
    /**
3632
     * @brief Sets the uniqueness ratio for filtering ambiguous matches.
3633
     * @param uniquenessRatio The uniqueness ratio value. Typically in the range [5, 15], but can be from 0 to 100.
3634
     * @details This parameter ensures that the best match is sufficiently better than the next best match, reducing false positives. Higher values are stricter but may filter out valid matches in difficult regions.
3635
     */
3636
    CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0;
3637
3638
    /**
3639
     * @brief Gets the current size of the smaller block used for texture check.
3640
     * @return The current smaller block size.
3641
     */
3642
    CV_WRAP virtual int getSmallerBlockSize() const = 0;
3643
3644
    /**
3645
     * @brief Sets the size of the smaller block used for texture check.
3646
     * @param blockSize The size of the smaller block. Must be an odd integer between 5 and 255.
3647
     * @details This parameter determines the size of the block used to compute texture variance. Smaller blocks capture finer details but are more sensitive to noise, while larger blocks are more robust but may miss fine details.
3648
     */
3649
    CV_WRAP virtual void setSmallerBlockSize(int blockSize) = 0;
3650
3651
    /**
3652
     * @brief Gets the current Region of Interest (ROI) for the left image.
3653
     * @return The current ROI for the left image.
3654
     */
3655
    CV_WRAP virtual Rect getROI1() const = 0;
3656
3657
    /**
3658
     * @brief Sets the Region of Interest (ROI) for the left image.
3659
     * @param roi1 The ROI rectangle for the left image.
3660
     * @details By setting the ROI, the stereo matching computation is limited to the specified region, improving performance and potentially accuracy by focusing on relevant parts of the image.
3661
     */
3662
    CV_WRAP virtual void setROI1(Rect roi1) = 0;
3663
3664
    /**
3665
     * @brief Gets the current Region of Interest (ROI) for the right image.
3666
     * @return The current ROI for the right image.
3667
     */
3668
    CV_WRAP virtual Rect getROI2() const = 0;
3669
3670
    /**
3671
     * @brief Sets the Region of Interest (ROI) for the right image.
3672
     * @param roi2 The ROI rectangle for the right image.
3673
     * @details Similar to setROI1, this limits the computation to the specified region in the right image.
3674
     */
3675
    CV_WRAP virtual void setROI2(Rect roi2) = 0;
3676
3677
    /**
3678
     * @brief Creates StereoBM object
3679
     * @param numDisparities The disparity search range. For each pixel, the algorithm will find the best disparity from 0 (default minimum disparity) to numDisparities. The search range can be shifted by changing the minimum disparity.
3680
     * @param blockSize The linear size of the blocks compared by the algorithm. The size should be odd (as the block is centered at the current pixel). Larger block size implies smoother, though less accurate disparity map. Smaller block size gives more detailed disparity map, but there is a higher chance for the algorithm to find a wrong correspondence.
3681
     * @return A pointer to the created StereoBM object.
3682
     * @details The function creates a StereoBM object. You can then call StereoBM::compute() to compute disparity for a specific stereo pair.
3683
     */
3684
    CV_WRAP static Ptr<StereoBM> create(int numDisparities = 0, int blockSize = 21);
3685
};
3686
3687
/** @brief The class implements the modified H. Hirschmuller algorithm @cite HH08 that differs from the original
3688
one as follows:
3689
3690
-   By default, the algorithm is single-pass, which means that you consider only 5 directions
3691
instead of 8. Set mode=StereoSGBM::MODE_HH in createStereoSGBM to run the full variant of the
3692
algorithm but beware that it may consume a lot of memory.
3693
-   The algorithm matches blocks, not individual pixels. Though, setting blockSize=1 reduces the
3694
blocks to single pixels.
3695
-   Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi
3696
sub-pixel metric from @cite BT98 is used. Though, the color images are supported as well.
3697
-   Some pre- and post- processing steps from K. Konolige algorithm StereoBM are included, for
3698
example: pre-filtering (StereoBM::PREFILTER_XSOBEL type) and post-filtering (uniqueness
3699
check, quadratic interpolation and speckle filtering).
3700
3701
@note
3702
   -   (Python) An example illustrating the use of the StereoSGBM matching algorithm can be found
3703
        at opencv_source_code/samples/python/stereo_match.py
3704
 */
3705
class CV_EXPORTS_W StereoSGBM : public StereoMatcher
3706
{
3707
public:
3708
    enum
3709
    {
3710
        MODE_SGBM = 0,
3711
        MODE_HH   = 1,
3712
        MODE_SGBM_3WAY = 2,
3713
        MODE_HH4  = 3
3714
    };
3715
3716
    CV_WRAP virtual int getPreFilterCap() const = 0;
3717
    CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0;
3718
3719
    CV_WRAP virtual int getUniquenessRatio() const = 0;
3720
    CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0;
3721
3722
    CV_WRAP virtual int getP1() const = 0;
3723
    CV_WRAP virtual void setP1(int P1) = 0;
3724
3725
    CV_WRAP virtual int getP2() const = 0;
3726
    CV_WRAP virtual void setP2(int P2) = 0;
3727
3728
    CV_WRAP virtual int getMode() const = 0;
3729
    CV_WRAP virtual void setMode(int mode) = 0;
3730
3731
    /** @brief Creates StereoSGBM object
3732
3733
    @param minDisparity Minimum possible disparity value. Normally, it is zero but sometimes
3734
    rectification algorithms can shift images, so this parameter needs to be adjusted accordingly.
3735
    @param numDisparities Maximum disparity minus minimum disparity. The value is always greater than
3736
    zero. In the current implementation, this parameter must be divisible by 16.
3737
    @param blockSize Matched block size. It must be an odd number \>=1 . Normally, it should be
3738
    somewhere in the 3..11 range.
3739
    @param P1 The first parameter controlling the disparity smoothness. See below.
3740
    @param P2 The second parameter controlling the disparity smoothness. The larger the values are,
3741
    the smoother the disparity is. P1 is the penalty on the disparity change by plus or minus 1
3742
    between neighbor pixels. P2 is the penalty on the disparity change by more than 1 between neighbor
3743
    pixels. The algorithm requires P2 \> P1 . See stereo_match.cpp sample where some reasonably good
3744
    P1 and P2 values are shown (like 8\*number_of_image_channels\*blockSize\*blockSize and
3745
    32\*number_of_image_channels\*blockSize\*blockSize , respectively).
3746
    @param disp12MaxDiff Maximum allowed difference (in integer pixel units) in the left-right
3747
    disparity check. Set it to a non-positive value to disable the check.
3748
    @param preFilterCap Truncation value for the prefiltered image pixels. The algorithm first
3749
    computes x-derivative at each pixel and clips its value by [-preFilterCap, preFilterCap] interval.
3750
    The result values are passed to the Birchfield-Tomasi pixel cost function.
3751
    @param uniquenessRatio Margin in percentage by which the best (minimum) computed cost function
3752
    value should "win" the second best value to consider the found match correct. Normally, a value
3753
    within the 5-15 range is good enough.
3754
    @param speckleWindowSize Maximum size of smooth disparity regions to consider their noise speckles
3755
    and invalidate. Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the
3756
    50-200 range.
3757
    @param speckleRange Maximum disparity variation within each connected component. If you do speckle
3758
    filtering, set the parameter to a positive value, it will be implicitly multiplied by 16.
3759
    Normally, 1 or 2 is good enough.
3760
    @param mode Set it to StereoSGBM::MODE_HH to run the full-scale two-pass dynamic programming
3761
    algorithm. It will consume O(W\*H\*numDisparities) bytes, which is large for 640x480 stereo and
3762
    huge for HD-size pictures. By default, it is set to false .
3763
3764
    The first constructor initializes StereoSGBM with all the default parameters. So, you only have to
3765
    set StereoSGBM::numDisparities at minimum. The second constructor enables you to set each parameter
3766
    to a custom value.
3767
     */
3768
    CV_WRAP static Ptr<StereoSGBM> create(int minDisparity = 0, int numDisparities = 16, int blockSize = 3,
3769
                                          int P1 = 0, int P2 = 0, int disp12MaxDiff = 0,
3770
                                          int preFilterCap = 0, int uniquenessRatio = 0,
3771
                                          int speckleWindowSize = 0, int speckleRange = 0,
3772
                                          int mode = StereoSGBM::MODE_SGBM);
3773
};
3774
3775
3776
//! cv::undistort mode
3777
enum UndistortTypes
3778
{
3779
    PROJ_SPHERICAL_ORTHO  = 0,
3780
    PROJ_SPHERICAL_EQRECT = 1
3781
};
3782
3783
/** @brief Transforms an image to compensate for lens distortion.
3784
3785
The function transforms an image to compensate radial and tangential lens distortion.
3786
3787
The function is simply a combination of #initUndistortRectifyMap (with unity R ) and #remap
3788
(with bilinear interpolation). See the former function for details of the transformation being
3789
performed.
3790
3791
Those pixels in the destination image, for which there is no correspondent pixels in the source
3792
image, are filled with zeros (black color).
3793
3794
A particular subset of the source image that will be visible in the corrected image can be regulated
3795
by newCameraMatrix. You can use #getOptimalNewCameraMatrix to compute the appropriate
3796
newCameraMatrix depending on your requirements.
3797
3798
The camera matrix and the distortion parameters can be determined using #calibrateCamera. If
3799
the resolution of images is different from the resolution used at the calibration stage, \f$f_x,
3800
f_y, c_x\f$ and \f$c_y\f$ need to be scaled accordingly, while the distortion coefficients remain
3801
the same.
3802
3803
@param src Input (distorted) image.
3804
@param dst Output (corrected) image that has the same size and type as src .
3805
@param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
3806
@param distCoeffs Input vector of distortion coefficients
3807
\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
3808
of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
3809
@param newCameraMatrix Camera matrix of the distorted image. By default, it is the same as
3810
cameraMatrix but you may additionally scale and shift the result by using a different matrix.
3811
 */
3812
CV_EXPORTS_W void undistort( InputArray src, OutputArray dst,
3813
                             InputArray cameraMatrix,
3814
                             InputArray distCoeffs,
3815
                             InputArray newCameraMatrix = noArray() );
3816
3817
/** @brief Computes the undistortion and rectification transformation map.
3818
3819
The function computes the joint undistortion and rectification transformation and represents the
3820
result in the form of maps for #remap. The undistorted image looks like original, as if it is
3821
captured with a camera using the camera matrix =newCameraMatrix and zero distortion. In case of a
3822
monocular camera, newCameraMatrix is usually equal to cameraMatrix, or it can be computed by
3823
#getOptimalNewCameraMatrix for a better control over scaling. In case of a stereo camera,
3824
newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify .
3825
3826
Also, this new camera is oriented differently in the coordinate space, according to R. That, for
3827
example, helps to align two heads of a stereo camera so that the epipolar lines on both images
3828
become horizontal and have the same y- coordinate (in case of a horizontally aligned stereo camera).
3829
3830
The function actually builds the maps for the inverse mapping algorithm that is used by #remap. That
3831
is, for each pixel \f$(u, v)\f$ in the destination (corrected and rectified) image, the function
3832
computes the corresponding coordinates in the source image (that is, in the original image from
3833
camera). The following process is applied:
3834
\f[
3835
\begin{array}{l}
3836
x  \leftarrow (u - {c'}_x)/{f'}_x  \\
3837
y  \leftarrow (v - {c'}_y)/{f'}_y  \\
3838
{[X\,Y\,W]} ^T  \leftarrow R^{-1}*[x \, y \, 1]^T  \\
3839
x'  \leftarrow X/W  \\
3840
y'  \leftarrow Y/W  \\
3841
r^2  \leftarrow x'^2 + y'^2 \\
3842
x''  \leftarrow x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}
3843
+ 2p_1 x' y' + p_2(r^2 + 2 x'^2)  + s_1 r^2 + s_2 r^4\\
3844
y''  \leftarrow y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}
3845
+ p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\
3846
s\vecthree{x'''}{y'''}{1} =
3847
\vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}((\tau_x, \tau_y)}
3848
{0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)}
3849
{0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\\
3850
map_x(u,v)  \leftarrow x''' f_x + c_x  \\
3851
map_y(u,v)  \leftarrow y''' f_y + c_y
3852
\end{array}
3853
\f]
3854
where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
3855
are the distortion coefficients.
3856
3857
In case of a stereo camera, this function is called twice: once for each camera head, after
3858
#stereoRectify, which in its turn is called after #stereoCalibrate. But if the stereo camera
3859
was not calibrated, it is still possible to compute the rectification transformations directly from
3860
the fundamental matrix using #stereoRectifyUncalibrated. For each camera, the function computes
3861
homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D
3862
space. R can be computed from H as
3863
\f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f]
3864
where cameraMatrix can be chosen arbitrarily.
3865
3866
@param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
3867
@param distCoeffs Input vector of distortion coefficients
3868
\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
3869
of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
3870
@param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2 ,
3871
computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation
3872
is assumed. In #initUndistortRectifyMap R assumed to be an identity matrix.
3873
@param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$.
3874
@param size Undistorted image size.
3875
@param m1type Type of the first output map that can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps
3876
@param map1 The first output map.
3877
@param map2 The second output map.
3878
 */
3879
CV_EXPORTS_W
3880
void initUndistortRectifyMap(InputArray cameraMatrix, InputArray distCoeffs,
3881
                             InputArray R, InputArray newCameraMatrix,
3882
                             Size size, int m1type, OutputArray map1, OutputArray map2);
3883
3884
/** @brief Computes the projection and inverse-rectification transformation map. In essense, this is the inverse of
3885
#initUndistortRectifyMap to accommodate stereo-rectification of projectors ('inverse-cameras') in projector-camera pairs.
3886
3887
The function computes the joint projection and inverse rectification transformation and represents the
3888
result in the form of maps for #remap. The projected image looks like a distorted version of the original which,
3889
once projected by a projector, should visually match the original. In case of a monocular camera, newCameraMatrix
3890
is usually equal to cameraMatrix, or it can be computed by
3891
#getOptimalNewCameraMatrix for a better control over scaling. In case of a projector-camera pair,
3892
newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify .
3893
3894
The projector is oriented differently in the coordinate space, according to R. In case of projector-camera pairs,
3895
this helps align the projector (in the same manner as #initUndistortRectifyMap for the camera) to create a stereo-rectified pair. This
3896
allows epipolar lines on both images to become horizontal and have the same y-coordinate (in case of a horizontally aligned projector-camera pair).
3897
3898
The function builds the maps for the inverse mapping algorithm that is used by #remap. That
3899
is, for each pixel \f$(u, v)\f$ in the destination (projected and inverse-rectified) image, the function
3900
computes the corresponding coordinates in the source image (that is, in the original digital image). The following process is applied:
3901
3902
\f[
3903
\begin{array}{l}
3904
\text{newCameraMatrix}\\
3905
x  \leftarrow (u - {c'}_x)/{f'}_x  \\
3906
y  \leftarrow (v - {c'}_y)/{f'}_y  \\
3907
3908
\\\text{Undistortion}
3909
\\\scriptsize{\textit{though equation shown is for radial undistortion, function implements cv::undistortPoints()}}\\
3910
r^2  \leftarrow x^2 + y^2 \\
3911
\theta \leftarrow \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}\\
3912
x' \leftarrow \frac{x}{\theta} \\
3913
y'  \leftarrow \frac{y}{\theta} \\
3914
3915
\\\text{Rectification}\\
3916
{[X\,Y\,W]} ^T  \leftarrow R*[x' \, y' \, 1]^T  \\
3917
x''  \leftarrow X/W  \\
3918
y''  \leftarrow Y/W  \\
3919
3920
\\\text{cameraMatrix}\\
3921
map_x(u,v)  \leftarrow x'' f_x + c_x  \\
3922
map_y(u,v)  \leftarrow y'' f_y + c_y
3923
\end{array}
3924
\f]
3925
where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
3926
are the distortion coefficients vector distCoeffs.
3927
3928
In case of a stereo-rectified projector-camera pair, this function is called for the projector while #initUndistortRectifyMap is called for the camera head.
3929
This is done after #stereoRectify, which in turn is called after #stereoCalibrate. If the projector-camera pair
3930
is not calibrated, it is still possible to compute the rectification transformations directly from
3931
the fundamental matrix using #stereoRectifyUncalibrated. For the projector and camera, the function computes
3932
homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D
3933
space. R can be computed from H as
3934
\f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f]
3935
where cameraMatrix can be chosen arbitrarily.
3936
3937
@param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
3938
@param distCoeffs Input vector of distortion coefficients
3939
\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
3940
of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
3941
@param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2,
3942
computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation
3943
is assumed.
3944
@param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$.
3945
@param size Distorted image size.
3946
@param m1type Type of the first output map. Can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps
3947
@param map1 The first output map for #remap.
3948
@param map2 The second output map for #remap.
3949
 */
3950
CV_EXPORTS_W
3951
void initInverseRectificationMap( InputArray cameraMatrix, InputArray distCoeffs,
3952
                           InputArray R, InputArray newCameraMatrix,
3953
                           const Size& size, int m1type, OutputArray map1, OutputArray map2 );
3954
3955
//! initializes maps for #remap for wide-angle
3956
CV_EXPORTS
3957
float initWideAngleProjMap(InputArray cameraMatrix, InputArray distCoeffs,
3958
                           Size imageSize, int destImageWidth,
3959
                           int m1type, OutputArray map1, OutputArray map2,
3960
                           enum UndistortTypes projType = PROJ_SPHERICAL_EQRECT, double alpha = 0);
3961
static inline
3962
float initWideAngleProjMap(InputArray cameraMatrix, InputArray distCoeffs,
3963
                           Size imageSize, int destImageWidth,
3964
                           int m1type, OutputArray map1, OutputArray map2,
3965
                           int projType, double alpha = 0)
3966
0
{
3967
0
    return initWideAngleProjMap(cameraMatrix, distCoeffs, imageSize, destImageWidth,
3968
0
                                m1type, map1, map2, (UndistortTypes)projType, alpha);
3969
0
}
Unexecuted instantiation: generateusergallerycollage_fuzzer.cc:cv::initWideAngleProjMap(cv::_InputArray const&, cv::_InputArray const&, cv::Size_<int>, int, int, cv::_OutputArray const&, cv::_OutputArray const&, int, double)
Unexecuted instantiation: imread_fuzzer.cc:cv::initWideAngleProjMap(cv::_InputArray const&, cv::_InputArray const&, cv::Size_<int>, int, int, cv::_OutputArray const&, cv::_OutputArray const&, int, double)
Unexecuted instantiation: imdecode_fuzzer.cc:cv::initWideAngleProjMap(cv::_InputArray const&, cv::_InputArray const&, cv::Size_<int>, int, int, cv::_OutputArray const&, cv::_OutputArray const&, int, double)
Unexecuted instantiation: filestorage_read_string_fuzzer.cc:cv::initWideAngleProjMap(cv::_InputArray const&, cv::_InputArray const&, cv::Size_<int>, int, int, cv::_OutputArray const&, cv::_OutputArray const&, int, double)
Unexecuted instantiation: filestorage_read_file_fuzzer.cc:cv::initWideAngleProjMap(cv::_InputArray const&, cv::_InputArray const&, cv::Size_<int>, int, int, cv::_OutputArray const&, cv::_OutputArray const&, int, double)
Unexecuted instantiation: core_fuzzer.cc:cv::initWideAngleProjMap(cv::_InputArray const&, cv::_InputArray const&, cv::Size_<int>, int, int, cv::_OutputArray const&, cv::_OutputArray const&, int, double)
Unexecuted instantiation: imencode_fuzzer.cc:cv::initWideAngleProjMap(cv::_InputArray const&, cv::_InputArray const&, cv::Size_<int>, int, int, cv::_OutputArray const&, cv::_OutputArray const&, int, double)
Unexecuted instantiation: filestorage_read_filename_fuzzer.cc:cv::initWideAngleProjMap(cv::_InputArray const&, cv::_InputArray const&, cv::Size_<int>, int, int, cv::_OutputArray const&, cv::_OutputArray const&, int, double)
3970
3971
/** @brief Returns the default new camera matrix.
3972
3973
The function returns the camera matrix that is either an exact copy of the input cameraMatrix (when
3974
centerPrinicipalPoint=false ), or the modified one (when centerPrincipalPoint=true).
3975
3976
In the latter case, the new camera matrix will be:
3977
3978
\f[\begin{bmatrix} f_x && 0 && ( \texttt{imgSize.width} -1)*0.5  \\ 0 && f_y && ( \texttt{imgSize.height} -1)*0.5  \\ 0 && 0 && 1 \end{bmatrix} ,\f]
3979
3980
where \f$f_x\f$ and \f$f_y\f$ are \f$(0,0)\f$ and \f$(1,1)\f$ elements of cameraMatrix, respectively.
3981
3982
By default, the undistortion functions in OpenCV (see #initUndistortRectifyMap, #undistort) do not
3983
move the principal point. However, when you work with stereo, it is important to move the principal
3984
points in both views to the same y-coordinate (which is required by most of stereo correspondence
3985
algorithms), and may be to the same x-coordinate too. So, you can form the new camera matrix for
3986
each view where the principal points are located at the center.
3987
3988
@param cameraMatrix Input camera matrix.
3989
@param imgsize Camera view image size in pixels.
3990
@param centerPrincipalPoint Location of the principal point in the new camera matrix. The
3991
parameter indicates whether this location should be at the image center or not.
3992
 */
3993
CV_EXPORTS_W
3994
Mat getDefaultNewCameraMatrix(InputArray cameraMatrix, Size imgsize = Size(),
3995
                              bool centerPrincipalPoint = false);
3996
3997
/** @brief Computes the ideal point coordinates from the observed point coordinates.
3998
3999
The function is similar to #undistort and #initUndistortRectifyMap but it operates on a
4000
sparse set of points instead of a raster image. Also the function performs a reverse transformation
4001
to  #projectPoints. In case of a 3D object, it does not reconstruct its 3D coordinates, but for a
4002
planar object, it does, up to a translation vector, if the proper R is specified.
4003
4004
For each observed point coordinate \f$(u, v)\f$ the function computes:
4005
\f[
4006
\begin{array}{l}
4007
x^{"}  \leftarrow (u - c_x)/f_x  \\
4008
y^{"}  \leftarrow (v - c_y)/f_y  \\
4009
(x',y') = undistort(x^{"},y^{"}, \texttt{distCoeffs}) \\
4010
{[X\,Y\,W]} ^T  \leftarrow R*[x' \, y' \, 1]^T  \\
4011
x  \leftarrow X/W  \\
4012
y  \leftarrow Y/W  \\
4013
\text{only performed if P is specified:} \\
4014
u'  \leftarrow x {f'}_x + {c'}_x  \\
4015
v'  \leftarrow y {f'}_y + {c'}_y
4016
\end{array}
4017
\f]
4018
4019
where *undistort* is an approximate iterative algorithm that estimates the normalized original
4020
point coordinates out of the normalized distorted point coordinates ("normalized" means that the
4021
coordinates do not depend on the camera matrix).
4022
4023
The function can be used for both a stereo camera head or a monocular camera (when R is empty).
4024
4025
@note **Coordinate Systems:**
4026
- **Input (`src`)**: Points are expected in **pixel coordinates** of the distorted image, i.e.,
4027
  coordinates \f$(u, v)\f$ measured in pixels from the top-left corner of the image.
4028
- **Output (`dst`)**: The coordinate system of output points depends on parameter `P`:
4029
  - If `P` is provided (not empty): Output points are in **pixel coordinates** of the rectified/undistorted image plane, using the camera matrix `P`.
4030
  - If `P` is empty or identity: Output points are in **normalized camera coordinates** (also called "normalized image coordinates"),
4031
    which are dimensionless coordinates \f$(x, y)\f$ in the camera's focal plane, related to pixel coordinates by:
4032
    \f$x = (u - c_x) / f_x\f$ and \f$y = (v - c_y) / f_y\f$. These normalized coordinates are independent of the camera's intrinsic parameters and are useful for 3D reconstruction or epipolar geometry.
4033
4034
@param src Observed point coordinates in **pixel coordinates** of the distorted image, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or CV_64FC2) (or
4035
vector\<Point2f\> ).
4036
@param dst Output ideal point coordinates (1xN/Nx1 2-channel or vector\<Point2f\> ) after undistortion and reverse perspective
4037
transformation. If matrix P is identity or omitted, dst will contain **normalized camera coordinates** (normalized image coordinates),
4038
otherwise it contains pixel coordinates in the coordinate system defined by P.
4039
@param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
4040
@param distCoeffs Input vector of distortion coefficients
4041
\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
4042
of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
4043
@param R Rectification transformation in the object space (3x3 matrix). R1 or R2 computed by
4044
#stereoRectify can be passed here. If the matrix is empty, the identity transformation is used.
4045
@param P New camera matrix (3x3) or new projection matrix (3x4) \f$\begin{bmatrix} {f'}_x & 0 & {c'}_x & t_x \\ 0 & {f'}_y & {c'}_y & t_y \\ 0 & 0 & 1 & t_z \end{bmatrix}\f$. P1 or P2 computed by
4046
#stereoRectify can be passed here. If the matrix is empty, the identity new camera matrix is used and output will be in normalized coordinates.
4047
 */
4048
CV_EXPORTS_W
4049
void undistortPoints(InputArray src, OutputArray dst,
4050
                     InputArray cameraMatrix, InputArray distCoeffs,
4051
                     InputArray R = noArray(), InputArray P = noArray());
4052
/** @overload
4053
    @note Default version of #undistortPoints does 5 iterations to compute undistorted points.
4054
 */
4055
CV_EXPORTS_AS(undistortPointsIter)
4056
void undistortPoints(InputArray src, OutputArray dst,
4057
                     InputArray cameraMatrix, InputArray distCoeffs,
4058
                     InputArray R, InputArray P, TermCriteria criteria);
4059
4060
/**
4061
 * @brief Compute undistorted image points position
4062
 *
4063
 * @param src Observed points position, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or
4064
CV_64FC2) (or vector\<Point2f\> ).
4065
 * @param dst Output undistorted points position (1xN/Nx1 2-channel or vector\<Point2f\> ).
4066
 * @param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
4067
 * @param distCoeffs Distortion coefficients
4068
 */
4069
CV_EXPORTS_W
4070
void undistortImagePoints(InputArray src, OutputArray dst, InputArray cameraMatrix,
4071
                          InputArray distCoeffs,
4072
                          TermCriteria = TermCriteria(TermCriteria::MAX_ITER, 5, 0.01));
4073
4074
//! @} calib3d
4075
4076
/** @brief The methods in this namespace use a so-called fisheye camera model.
4077
  @ingroup calib3d_fisheye
4078
*/
4079
namespace fisheye
4080
{
4081
//! @addtogroup calib3d_fisheye
4082
//! @{
4083
4084
    enum{
4085
        CALIB_USE_INTRINSIC_GUESS   = 1 << 0,
4086
        CALIB_RECOMPUTE_EXTRINSIC   = 1 << 1,
4087
        CALIB_CHECK_COND            = 1 << 2,
4088
        CALIB_FIX_SKEW              = 1 << 3,
4089
        CALIB_FIX_K1                = 1 << 4,
4090
        CALIB_FIX_K2                = 1 << 5,
4091
        CALIB_FIX_K3                = 1 << 6,
4092
        CALIB_FIX_K4                = 1 << 7,
4093
        CALIB_FIX_INTRINSIC         = 1 << 8,
4094
        CALIB_FIX_PRINCIPAL_POINT   = 1 << 9,
4095
        CALIB_ZERO_DISPARITY        = 1 << 10,
4096
        CALIB_FIX_FOCAL_LENGTH      = 1 << 11
4097
    };
4098
4099
    /** @brief Projects points using fisheye model
4100
4101
    @param objectPoints Array of object points, 1xN/Nx1 3-channel (or vector\<Point3f\> ), where N is
4102
    the number of points in the view.
4103
    @param imagePoints Output array of image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, or
4104
    vector\<Point2f\>.
4105
    @param affine Pose of the camera.
4106
    @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$.
4107
    @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
4108
    @param alpha The skew coefficient.
4109
    @param jacobian Optional output 2Nx15 jacobian matrix of derivatives of image points with respect
4110
    to components of the focal lengths, coordinates of the principal point, distortion coefficients,
4111
    rotation vector, translation vector, and the skew. In the old interface different components of
4112
    the jacobian are returned via different output parameters.
4113
4114
    The function computes projections of 3D points to the image plane given intrinsic and extrinsic
4115
    camera parameters. Optionally, the function computes Jacobians - matrices of partial derivatives of
4116
    image points coordinates (as functions of all the input parameters) with respect to the particular
4117
    parameters, intrinsic and/or extrinsic.
4118
     */
4119
    CV_EXPORTS void projectPoints(InputArray objectPoints, OutputArray imagePoints, const Affine3d& affine,
4120
        InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray());
4121
4122
    /** @overload */
4123
    CV_EXPORTS_W void projectPoints(InputArray objectPoints, OutputArray imagePoints, InputArray rvec, InputArray tvec,
4124
        InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray());
4125
4126
    /** @brief Distorts 2D points using fisheye model.
4127
4128
    @param undistorted Array of object points, 1xN/Nx1 2-channel (or vector\<Point2f\> ), where N is
4129
    the number of points in the view.
4130
    @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$.
4131
    @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
4132
    @param alpha The skew coefficient.
4133
    @param distorted Output array of image points, 1xN/Nx1 2-channel, or vector\<Point2f\> .
4134
4135
    Note that the function assumes the camera intrinsic matrix of the undistorted points to be identity.
4136
    This means if you want to distort image points you have to multiply them with \f$K^{-1}\f$ or
4137
    use another function overload.
4138
     */
4139
    CV_EXPORTS_W void distortPoints(InputArray undistorted, OutputArray distorted, InputArray K, InputArray D, double alpha = 0);
4140
4141
    /** @overload
4142
    Overload of distortPoints function to handle cases when undistorted points are obtained with non-identity
4143
    camera matrix, e.g. output of #estimateNewCameraMatrixForUndistortRectify.
4144
    @param undistorted Array of object points, 1xN/Nx1 2-channel (or vector\<Point2f\> ), where N is
4145
    the number of points in the view.
4146
    @param Kundistorted Camera intrinsic matrix used as new camera matrix for undistortion.
4147
    @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$.
4148
    @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
4149
    @param alpha The skew coefficient.
4150
    @param distorted Output array of image points, 1xN/Nx1 2-channel, or vector\<Point2f\> .
4151
    @sa estimateNewCameraMatrixForUndistortRectify
4152
    */
4153
    CV_EXPORTS_W void distortPoints(InputArray undistorted, OutputArray distorted, InputArray Kundistorted, InputArray K, InputArray D, double alpha = 0);
4154
4155
    /** @brief Undistorts 2D points using fisheye camera model
4156
4157
    This function performs undistortion for fisheye camera models, which use a different distortion model
4158
    compared to the standard pinhole camera model used by #undistortPoints. The fisheye model is suitable
4159
    for wide-angle cameras.
4160
4161
    The function transforms points from the distorted fisheye image to undistorted coordinates, optionally
4162
    applying a rectification transformation (R) and projecting to a new image plane (P).
4163
4164
    @note **Coordinate Systems:**
4165
    - **Input (`distorted`)**: Points are expected in **pixel coordinates** of the distorted fisheye image,
4166
      i.e., coordinates measured in pixels from the top-left corner of the image.
4167
    - **Output (`undistorted`)**: The coordinate system depends on parameter `P`:
4168
      - If `P` is provided (not empty): Output points are in **pixel coordinates** of the rectified/undistorted
4169
        image plane, using the camera matrix `P`.
4170
      - If `P` is empty or identity: Output points are in **normalized camera coordinates** (normalized image coordinates),
4171
        which are dimensionless coordinates in the camera's focal plane, independent of intrinsic parameters.
4172
4173
    @note **Fisheye vs. Standard Model:**
4174
    Use this function (#fisheye::undistortPoints) for fisheye cameras (wide-angle lenses).
4175
    For standard pinhole cameras, use #undistortPoints instead. The fisheye model uses a different distortion
4176
    parameterization (4 coefficients) compared to the standard model (4-14 coefficients).
4177
4178
    @param distorted Array of distorted point coordinates in **pixel coordinates** of the fisheye image,
4179
    1xN/Nx1 2-channel (or vector\<Point2f\> ), where N is the number of points in the view.
4180
    @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$ of the fisheye camera.
4181
    @param D Input vector of fisheye distortion coefficients \f$\distcoeffsfisheye\f$ (must contain exactly 4 coefficients).
4182
    @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3
4183
    1-channel or 1x1 3-channel. If empty, the identity transformation is used.
4184
    @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4). If empty or identity,
4185
    output will be in normalized camera coordinates.
4186
    @param criteria Termination criteria for the iterative undistortion algorithm.
4187
    @param undistorted Output array of undistorted image points, 1xN/Nx1 2-channel, or vector\<Point2f\> .
4188
    The coordinate system depends on parameter P (see above).
4189
     */
4190
    CV_EXPORTS_W void undistortPoints(InputArray distorted, OutputArray undistorted,
4191
        InputArray K, InputArray D, InputArray R = noArray(), InputArray P  = noArray(),
4192
                TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 10, 1e-8));
4193
4194
    /** @brief Computes undistortion and rectification maps for image transform by #remap. If D is empty zero
4195
    distortion is used, if R or P is empty identity matrixes are used.
4196
4197
    @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$.
4198
    @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
4199
    @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3
4200
    1-channel or 1x1 3-channel
4201
    @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4)
4202
    @param size Undistorted image size.
4203
    @param m1type Type of the first output map that can be CV_32FC1 or CV_16SC2 . See #convertMaps
4204
    for details.
4205
    @param map1 The first output map.
4206
    @param map2 The second output map.
4207
     */
4208
    CV_EXPORTS_W void initUndistortRectifyMap(InputArray K, InputArray D, InputArray R, InputArray P,
4209
        const cv::Size& size, int m1type, OutputArray map1, OutputArray map2);
4210
4211
    /** @brief Transforms an image to compensate for fisheye lens distortion.
4212
4213
    @param distorted image with fisheye lens distortion.
4214
    @param undistorted Output image with compensated fisheye lens distortion.
4215
    @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$.
4216
    @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
4217
    @param Knew Camera intrinsic matrix of the distorted image. By default, it is the identity matrix but you
4218
    may additionally scale and shift the result by using a different matrix.
4219
    @param new_size the new size
4220
4221
    The function transforms an image to compensate radial lens distortion.
4222
4223
    The function is simply a combination of #fisheye::initUndistortRectifyMap (with unity R ) and #remap
4224
    (with bilinear interpolation). See the former function for details of the transformation being
4225
    performed.
4226
4227
    See below the results of undistortImage.
4228
       -   a\) result of undistort of perspective camera model (all possible coefficients (k_1, k_2, k_3,
4229
            k_4, k_5, k_6) of distortion were optimized under calibration)
4230
        -   b\) result of #fisheye::undistortImage of fisheye camera model (all possible coefficients (k_1, k_2,
4231
            k_3, k_4) of fisheye distortion were optimized under calibration)
4232
        -   c\) original image was captured with fisheye lens
4233
4234
    Pictures a) and b) almost the same. But if we consider points of image located far from the center
4235
    of image, we can notice that on image a) these points are distorted.
4236
4237
    ![image](pics/fisheye_undistorted.jpg)
4238
     */
4239
    CV_EXPORTS_W void undistortImage(InputArray distorted, OutputArray undistorted,
4240
        InputArray K, InputArray D, InputArray Knew = cv::noArray(), const Size& new_size = Size());
4241
4242
    /** @brief Estimates new camera intrinsic matrix for undistortion or rectification.
4243
4244
    @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$.
4245
    @param image_size Size of the image
4246
    @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
4247
    @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3
4248
    1-channel or 1x1 3-channel
4249
    @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4)
4250
    @param balance Sets the new focal length in range between the min focal length and the max focal
4251
    length. Balance is in range of [0, 1].
4252
    @param new_size the new size
4253
    @param fov_scale Divisor for new focal length.
4254
     */
4255
    CV_EXPORTS_W void estimateNewCameraMatrixForUndistortRectify(InputArray K, InputArray D, const Size &image_size, InputArray R,
4256
        OutputArray P, double balance = 0.0, const Size& new_size = Size(), double fov_scale = 1.0);
4257
4258
    /** @brief Performs camera calibration
4259
4260
    @param objectPoints vector of vectors of calibration pattern points in the calibration pattern
4261
    coordinate space.
4262
    @param imagePoints vector of vectors of the projections of calibration pattern points.
4263
    imagePoints.size() and objectPoints.size() and imagePoints[i].size() must be equal to
4264
    objectPoints[i].size() for each i.
4265
    @param image_size Size of the image used only to initialize the camera intrinsic matrix.
4266
    @param K Output 3x3 floating-point camera intrinsic matrix
4267
    \f$\cameramatrix{A}\f$ . If
4268
    @ref fisheye::CALIB_USE_INTRINSIC_GUESS is specified, some or all of fx, fy, cx, cy must be
4269
    initialized before calling the function.
4270
    @param D Output vector of distortion coefficients \f$\distcoeffsfisheye\f$.
4271
    @param rvecs Output vector of rotation vectors (see @ref Rodrigues ) estimated for each pattern view.
4272
    That is, each k-th rotation vector together with the corresponding k-th translation vector (see
4273
    the next output parameter description) brings the calibration pattern from the model coordinate
4274
    space (in which object points are specified) to the world coordinate space, that is, a real
4275
    position of the calibration pattern in the k-th pattern view (k=0.. *M* -1).
4276
    @param tvecs Output vector of translation vectors estimated for each pattern view.
4277
    @param flags Different flags that may be zero or a combination of the following values:
4278
    -    @ref fisheye::CALIB_USE_INTRINSIC_GUESS  cameraMatrix contains valid initial values of
4279
    fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image
4280
    center ( imageSize is used), and focal distances are computed in a least-squares fashion.
4281
    -    @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC  Extrinsic will be recomputed after each iteration
4282
    of intrinsic optimization.
4283
    -    @ref fisheye::CALIB_CHECK_COND  The functions will check validity of condition number.
4284
    -    @ref fisheye::CALIB_FIX_SKEW  Skew coefficient (alpha) is set to zero and stay zero.
4285
    -    @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients
4286
    are set to zeros and stay zero.
4287
    -    @ref fisheye::CALIB_FIX_PRINCIPAL_POINT  The principal point is not changed during the global
4288
optimization. It stays at the center or at a different location specified when @ref fisheye::CALIB_USE_INTRINSIC_GUESS is set too.
4289
    -    @ref fisheye::CALIB_FIX_FOCAL_LENGTH The focal length is not changed during the global
4290
optimization. It is the \f$max(width,height)/\pi\f$ or the provided \f$f_x\f$, \f$f_y\f$ when @ref fisheye::CALIB_USE_INTRINSIC_GUESS is set too.
4291
    @param criteria Termination criteria for the iterative optimization algorithm.
4292
     */
4293
    CV_EXPORTS_W double calibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, const Size& image_size,
4294
        InputOutputArray K, InputOutputArray D, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = 0,
4295
            TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON));
4296
4297
    /** @brief Stereo rectification for fisheye camera model
4298
4299
    @param K1 First camera intrinsic matrix.
4300
    @param D1 First camera distortion parameters.
4301
    @param K2 Second camera intrinsic matrix.
4302
    @param D2 Second camera distortion parameters.
4303
    @param imageSize Size of the image used for stereo calibration.
4304
    @param R Rotation matrix between the coordinate systems of the first and the second
4305
    cameras.
4306
    @param tvec Translation vector between coordinate systems of the cameras.
4307
    @param R1 Output 3x3 rectification transform (rotation matrix) for the first camera.
4308
    @param R2 Output 3x3 rectification transform (rotation matrix) for the second camera.
4309
    @param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first
4310
    camera.
4311
    @param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second
4312
    camera.
4313
    @param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see #reprojectImageTo3D ).
4314
    @param flags Operation flags that may be zero or @ref fisheye::CALIB_ZERO_DISPARITY . If the flag is set,
4315
    the function makes the principal points of each camera have the same pixel coordinates in the
4316
    rectified views. And if the flag is not set, the function may still shift the images in the
4317
    horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the
4318
    useful image area.
4319
    @param newImageSize New image resolution after rectification. The same size should be passed to
4320
    #initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0)
4321
    is passed (default), it is set to the original imageSize . Setting it to larger value can help you
4322
    preserve details in the original image, especially when there is a big radial distortion.
4323
    @param balance Sets the new focal length in range between the min focal length and the max focal
4324
    length. Balance is in range of [0, 1].
4325
    @param fov_scale Divisor for new focal length.
4326
     */
4327
    CV_EXPORTS_W void stereoRectify(InputArray K1, InputArray D1, InputArray K2, InputArray D2, const Size &imageSize, InputArray R, InputArray tvec,
4328
        OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, int flags, const Size &newImageSize = Size(),
4329
        double balance = 0.0, double fov_scale = 1.0);
4330
4331
    /** @brief Performs stereo calibration
4332
4333
    @param objectPoints Vector of vectors of the calibration pattern points.
4334
    @param imagePoints1 Vector of vectors of the projections of the calibration pattern points,
4335
    observed by the first camera.
4336
    @param imagePoints2 Vector of vectors of the projections of the calibration pattern points,
4337
    observed by the second camera.
4338
    @param K1 Input/output first camera intrinsic matrix:
4339
    \f$\vecthreethree{f_x^{(j)}}{0}{c_x^{(j)}}{0}{f_y^{(j)}}{c_y^{(j)}}{0}{0}{1}\f$ , \f$j = 0,\, 1\f$ . If
4340
    any of @ref fisheye::CALIB_USE_INTRINSIC_GUESS , @ref fisheye::CALIB_FIX_INTRINSIC are specified,
4341
    some or all of the matrix components must be initialized.
4342
    @param D1 Input/output vector of distortion coefficients \f$\distcoeffsfisheye\f$ of 4 elements.
4343
    @param K2 Input/output second camera intrinsic matrix. The parameter is similar to K1 .
4344
    @param D2 Input/output lens distortion coefficients for the second camera. The parameter is
4345
    similar to D1 .
4346
    @param imageSize Size of the image used only to initialize camera intrinsic matrix.
4347
    @param R Output rotation matrix between the 1st and the 2nd camera coordinate systems.
4348
    @param T Output translation vector between the coordinate systems of the cameras.
4349
    @param rvecs Output vector of rotation vectors ( @ref Rodrigues ) estimated for each pattern view in the
4350
    coordinate system of the first camera of the stereo pair (e.g. std::vector<cv::Mat>). More in detail, each
4351
    i-th rotation vector together with the corresponding i-th translation vector (see the next output parameter
4352
    description) brings the calibration pattern from the object coordinate space (in which object points are
4353
    specified) to the camera coordinate space of the first camera of the stereo pair. In more technical terms,
4354
    the tuple of the i-th rotation and translation vector performs a change of basis from object coordinate space
4355
    to camera coordinate space of the first camera of the stereo pair.
4356
    @param tvecs Output vector of translation vectors estimated for each pattern view, see parameter description
4357
    of previous output parameter ( rvecs ).
4358
    @param flags Different flags that may be zero or a combination of the following values:
4359
    -    @ref fisheye::CALIB_FIX_INTRINSIC  Fix K1, K2? and D1, D2? so that only R, T matrices
4360
    are estimated.
4361
    -    @ref fisheye::CALIB_USE_INTRINSIC_GUESS  K1, K2 contains valid initial values of
4362
    fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image
4363
    center (imageSize is used), and focal distances are computed in a least-squares fashion.
4364
    -    @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC  Extrinsic will be recomputed after each iteration
4365
    of intrinsic optimization.
4366
    -    @ref fisheye::CALIB_CHECK_COND  The functions will check validity of condition number.
4367
    -    @ref fisheye::CALIB_FIX_SKEW  Skew coefficient (alpha) is set to zero and stay zero.
4368
    -   @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients are set to zeros and stay
4369
    zero.
4370
    @param criteria Termination criteria for the iterative optimization algorithm.
4371
     */
4372
    CV_EXPORTS_W double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
4373
                                  InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize,
4374
                                  OutputArray R, OutputArray T, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = fisheye::CALIB_FIX_INTRINSIC,
4375
                                  TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON));
4376
4377
    /// @overload
4378
    CV_EXPORTS_W double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
4379
                                  InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize,
4380
                                  OutputArray R, OutputArray T, int flags = fisheye::CALIB_FIX_INTRINSIC,
4381
                                  TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON));
4382
4383
    /**
4384
    @brief Finds an object pose from 3D-2D point correspondences for fisheye camera model.
4385
4386
    @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or
4387
    1xN/Nx1 3-channel, where N is the number of points. vector\<Point3d\> can also be passed here.
4388
    @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
4389
    where N is the number of points. vector\<Point2d\> can also be passed here.
4390
    @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
4391
    @param distCoeffs Input vector of distortion coefficients (4x1/1x4).
4392
    @param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
4393
    the model coordinate system to the camera coordinate system.
4394
    @param tvec Output translation vector.
4395
    @param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses
4396
    the provided rvec and tvec values as initial approximations of the rotation and translation
4397
    vectors, respectively, and further optimizes them.
4398
    @param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags
4399
    @param criteria Termination criteria for internal undistortPoints call.
4400
    The function internally undistorts points with @ref undistortPoints and call @ref cv::solvePnP,
4401
    thus the input are very similar. More information about Perspective-n-Points is described in @ref calib3d_solvePnP
4402
    for more information.
4403
    */
4404
    CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints,
4405
                                InputArray cameraMatrix, InputArray distCoeffs,
4406
                                OutputArray rvec, OutputArray tvec,
4407
                                bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE,
4408
                                TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 10, 1e-8)
4409
                              );
4410
4411
    /**
4412
    @brief Finds an object pose from 3D-2D point correspondences using the RANSAC scheme for fisheye camera moodel.
4413
4414
    @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or
4415
    1xN/Nx1 3-channel, where N is the number of points. vector\<Point3d\> can be also passed here.
4416
    @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
4417
    where N is the number of points. vector\<Point2d\> can be also passed here.
4418
    @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
4419
    @param distCoeffs Input vector of distortion coefficients (4x1/1x4).
4420
    @param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
4421
    the model coordinate system to the camera coordinate system.
4422
    @param tvec Output translation vector.
4423
    @param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses
4424
    the provided rvec and tvec values as initial approximations of the rotation and translation
4425
    vectors, respectively, and further optimizes them.
4426
    @param iterationsCount Number of iterations.
4427
    @param reprojectionError Inlier threshold value used by the RANSAC procedure. The parameter value
4428
    is the maximum allowed distance between the observed and computed point projections to consider it
4429
    an inlier.
4430
    @param confidence The probability that the algorithm produces a useful result.
4431
    @param inliers Output vector that contains indices of inliers in objectPoints and imagePoints .
4432
    @param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags
4433
    This function returns the rotation and the translation vectors that transform a 3D point expressed in the object
4434
    coordinate frame to the camera coordinate frame, using different methods:
4435
    - P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): need 4 input points to return a unique solution.
4436
    - @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar.
4437
    - @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation.
4438
    Number of input points must be 4. Object points must be defined in the following order:
4439
    - point 0: [-squareLength / 2,  squareLength / 2, 0]
4440
    - point 1: [ squareLength / 2,  squareLength / 2, 0]
4441
    - point 2: [ squareLength / 2, -squareLength / 2, 0]
4442
    - point 3: [-squareLength / 2, -squareLength / 2, 0]
4443
    - for all the other flags, number of input points must be >= 4 and object points can be in any configuration.
4444
    @param criteria Termination criteria for internal undistortPoints call.
4445
    The function interally undistorts points with @ref undistortPoints and call @ref cv::solvePnP,
4446
    thus the input are very similar. More information about Perspective-n-Points is described in @ref calib3d_solvePnP
4447
    for more information.
4448
    */
4449
    CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints,
4450
                                      InputArray cameraMatrix, InputArray distCoeffs,
4451
                                      OutputArray rvec, OutputArray tvec,
4452
                                      bool useExtrinsicGuess = false, int iterationsCount = 100,
4453
                                      float reprojectionError = 8.0, double confidence = 0.99,
4454
                                      OutputArray inliers = noArray(), int flags = SOLVEPNP_ITERATIVE,
4455
                                      TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 10, 1e-8)
4456
                                    );
4457
4458
//! @} calib3d_fisheye
4459
} // end namespace fisheye
4460
4461
} //end namespace cv
4462
4463
#if 0 //def __cplusplus
4464
//////////////////////////////////////////////////////////////////////////////////////////
4465
class CV_EXPORTS CvLevMarq
4466
{
4467
public:
4468
    CvLevMarq();
4469
    CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria=
4470
              cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON),
4471
              bool completeSymmFlag=false );
4472
    ~CvLevMarq();
4473
    void init( int nparams, int nerrs, CvTermCriteria criteria=
4474
              cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON),
4475
              bool completeSymmFlag=false );
4476
    bool update( const CvMat*& param, CvMat*& J, CvMat*& err );
4477
    bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm );
4478
4479
    void clear();
4480
    void step();
4481
    enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 };
4482
4483
    cv::Ptr<CvMat> mask;
4484
    cv::Ptr<CvMat> prevParam;
4485
    cv::Ptr<CvMat> param;
4486
    cv::Ptr<CvMat> J;
4487
    cv::Ptr<CvMat> err;
4488
    cv::Ptr<CvMat> JtJ;
4489
    cv::Ptr<CvMat> JtJN;
4490
    cv::Ptr<CvMat> JtErr;
4491
    cv::Ptr<CvMat> JtJV;
4492
    cv::Ptr<CvMat> JtJW;
4493
    double prevErrNorm, errNorm;
4494
    int lambdaLg10;
4495
    CvTermCriteria criteria;
4496
    int state;
4497
    int iters;
4498
    bool completeSymmFlag;
4499
    int solveMethod;
4500
};
4501
#endif
4502
4503
#endif