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-2015, Intel Corporation, all rights reserved.
14// Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
15// Copyright (C) 2015, OpenCV Foundation, all rights reserved.
16// Copyright (C) 2015, Itseez Inc., all rights reserved.
17// Third party copyrights are property of their respective owners.
18//
19// Redistribution and use in source and binary forms, with or without modification,
20// are permitted provided that the following conditions are met:
21//
22// * Redistribution's of source code must retain the above copyright notice,
23// this list of conditions and the following disclaimer.
24//
25// * Redistribution's in binary form must reproduce the above copyright notice,
26// this list of conditions and the following disclaimer in the documentation
27// and/or other materials provided with the distribution.
28//
29// * The name of the copyright holders may not be used to endorse or promote products
30// derived from this software without specific prior written permission.
31//
32// This software is provided by the copyright holders and contributors "as is" and
33// any express or implied warranties, including, but not limited to, the implied
34// warranties of merchantability and fitness for a particular purpose are disclaimed.
35// In no event shall the Intel Corporation or contributors be liable for any direct,
36// indirect, incidental, special, exemplary, or consequential damages
37// (including, but not limited to, procurement of substitute goods or services;
38// loss of use, data, or profits; or business interruption) however caused
39// and on any theory of liability, whether in contract, strict liability,
40// or tort (including negligence or otherwise) arising in any way out of
41// the use of this software, even if advised of the possibility of such damage.
42//
43//M*/
44
45#ifndef OPENCV_CORE_HPP
46#define OPENCV_CORE_HPP
47
48#ifndef __cplusplus
49# error core.hpp header must be compiled as C++
50#endif
51
52#include "opencv2/core/cvdef.h"
53#include "opencv2/core/base.hpp"
54#include "opencv2/core/cvstd.hpp"
55#include "opencv2/core/traits.hpp"
56#include "opencv2/core/matx.hpp"
57#include "opencv2/core/types.hpp"
58#include "opencv2/core/mat.hpp"
59#include "opencv2/core/persistence.hpp"
60
61/**
62@defgroup core Core functionality
63
64The Core module is the backbone of OpenCV, offering fundamental data structures, matrix operations,
65and utility functions that other modules depend on. It’s essential for handling image data,
66performing mathematical computations, and managing memory efficiently within the OpenCV ecosystem.
67
68@{
69 @defgroup core_basic Basic structures
70 @defgroup core_array Operations on arrays
71 @defgroup core_async Asynchronous API
72 @defgroup core_xml XML/YAML/JSON Persistence
73 @defgroup core_cluster Clustering
74 @defgroup core_utils Utility and system functions and macros
75 @{
76 @defgroup core_logging Logging facilities
77 @defgroup core_utils_sse SSE utilities
78 @defgroup core_utils_neon NEON utilities
79 @defgroup core_utils_vsx VSX utilities
80 @defgroup core_utils_softfloat Softfloat support
81 @defgroup core_utils_samples Utility functions for OpenCV samples
82 @}
83 @defgroup core_opengl OpenGL interoperability
84 @defgroup core_optim Optimization Algorithms
85 @defgroup core_directx DirectX interoperability
86 @defgroup core_eigen Eigen support
87 @defgroup core_opencl OpenCL support
88 @defgroup core_va_intel Intel VA-API/OpenCL (CL-VA) interoperability
89 @defgroup core_hal Hardware Acceleration Layer
90 @{
91 @defgroup core_hal_functions Functions
92 @defgroup core_hal_interface Interface
93 @defgroup core_hal_intrin Universal intrinsics
94 @{
95 @defgroup core_hal_intrin_impl Private implementation helpers
96 @}
97 @defgroup core_lowlevel_api Low-level API for external libraries / plugins
98 @}
99 @defgroup core_parallel Parallel Processing
100 @{
101 @defgroup core_parallel_backend Parallel backends API
102 @}
103 @defgroup core_quaternion Quaternion
104@}
105 */
106
107namespace cv {
108
109//! @addtogroup core_utils
110//! @{
111
112/*! @brief Class passed to an error.
113
114This class encapsulates all or almost all necessary
115information about the error happened in the program. The exception is
116usually constructed and thrown implicitly via CV_Error and CV_Error_ macros.
117@see error
118 */
119class CV_EXPORTS Exception : public std::exception
120{
121public:
122 /*!
123 Default constructor
124 */
125 Exception();
126 /*!
127 Full constructor. Normally the constructor is not called explicitly.
128 Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used.
129 */
130 Exception(int _code, const String& _err, const String& _func, const String& _file, int _line);
131 virtual ~Exception() CV_NOEXCEPT;
132
133 /*!
134 \return the error description and the context as a text string.
135 */
136 virtual const char *what() const CV_NOEXCEPT CV_OVERRIDE;
137 void formatMessage();
138
139 String msg; ///< the formatted error message
140
141 int code; ///< error code @see CVStatus
142 String err; ///< error description
143 String func; ///< function name. Available only when the compiler supports getting it
144 String file; ///< source file name where the error has occurred
145 int line; ///< line number in the source file where the error has occurred
146};
147
148/*! @brief Signals an error and raises the exception.
149
150By default the function prints information about the error to stderr,
151then it either stops if cv::setBreakOnError() had been called before or raises the exception.
152It is possible to alternate error processing by using #redirectError().
153@param exc the exception raisen.
154@deprecated drop this version
155 */
156CV_EXPORTS CV_NORETURN void error(const Exception& exc);
157
158enum SortFlags { SORT_EVERY_ROW = 0, //!< each matrix row is sorted independently
159 SORT_EVERY_COLUMN = 1, //!< each matrix column is sorted
160 //!< independently; this flag and the previous one are
161 //!< mutually exclusive.
162 SORT_ASCENDING = 0, //!< each matrix row is sorted in the ascending
163 //!< order.
164 SORT_DESCENDING = 16 //!< each matrix row is sorted in the
165 //!< descending order; this flag and the previous one are also
166 //!< mutually exclusive.
167 };
168
169//! @} core_utils
170
171//! @addtogroup core_array
172//! @{
173
174//! Covariation flags
175enum CovarFlags {
176 /** The output covariance matrix is calculated as:
177 \f[\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...]^T \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...],\f]
178 The covariance matrix will be nsamples x nsamples. Such an unusual covariance matrix is used
179 for fast PCA of a set of very large vectors (see, for example, the EigenFaces technique for
180 face recognition). Eigenvalues of this "scrambled" matrix match the eigenvalues of the true
181 covariance matrix. The "true" eigenvectors can be easily calculated from the eigenvectors of
182 the "scrambled" covariance matrix. */
183 COVAR_SCRAMBLED = 0,
184 /**The output covariance matrix is calculated as:
185 \f[\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...] \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...]^T,\f]
186 covar will be a square matrix of the same size as the total number of elements in each input
187 vector. One and only one of #COVAR_SCRAMBLED and #COVAR_NORMAL must be specified.*/
188 COVAR_NORMAL = 1,
189 /** If the flag is specified, the function does not calculate mean from
190 the input vectors but, instead, uses the passed mean vector. This is useful if mean has been
191 pre-calculated or known in advance, or if the covariance matrix is calculated by parts. In
192 this case, mean is not a mean vector of the input sub-set of vectors but rather the mean
193 vector of the whole set.*/
194 COVAR_USE_AVG = 2,
195 /** If the flag is specified, the covariance matrix is scaled. In the
196 "normal" mode, scale is 1./nsamples . In the "scrambled" mode, scale is the reciprocal of the
197 total number of elements in each input vector. By default (if the flag is not specified), the
198 covariance matrix is not scaled ( scale=1 ).*/
199 COVAR_SCALE = 4,
200 /** If the flag is
201 specified, all the input vectors are stored as rows of the samples matrix. mean should be a
202 single-row vector in this case.*/
203 COVAR_ROWS = 8,
204 /** If the flag is
205 specified, all the input vectors are stored as columns of the samples matrix. mean should be a
206 single-column vector in this case.*/
207 COVAR_COLS = 16
208};
209
210enum ReduceTypes { REDUCE_SUM = 0, //!< the output is the sum of all rows/columns of the matrix.
211 REDUCE_AVG = 1, //!< the output is the mean vector of all rows/columns of the matrix.
212 REDUCE_MAX = 2, //!< the output is the maximum (column/row-wise) of all rows/columns of the matrix.
213 REDUCE_MIN = 3, //!< the output is the minimum (column/row-wise) of all rows/columns of the matrix.
214 REDUCE_SUM2 = 4 //!< the output is the sum of all squared rows/columns of the matrix.
215 };
216
217/** @brief Swaps two matrices
218*/
219CV_EXPORTS void swap(Mat& a, Mat& b);
220/** @overload */
221CV_EXPORTS void swap( UMat& a, UMat& b );
222
223/** @brief Computes the source location of an extrapolated pixel.
224
225The function computes and returns the coordinate of a donor pixel corresponding to the specified
226extrapolated pixel when using the specified extrapolation border mode. For example, if you use
227cv::BORDER_WRAP mode in the horizontal direction, cv::BORDER_REFLECT_101 in the vertical direction and
228want to compute value of the "virtual" pixel Point(-5, 100) in a floating-point image img, it
229looks like:
230@code{.cpp}
231 float val = img.at<float>(borderInterpolate(100, img.rows, cv::BORDER_REFLECT_101),
232 borderInterpolate(-5, img.cols, cv::BORDER_WRAP));
233@endcode
234Normally, the function is not called directly. It is used inside filtering functions and also in
235copyMakeBorder.
236@param p 0-based coordinate of the extrapolated pixel along one of the axes, likely \<0 or \>= len
237@param len Length of the array along the corresponding axis.
238@param borderType Border type, one of the #BorderTypes, except for #BORDER_TRANSPARENT and
239#BORDER_ISOLATED. When borderType==#BORDER_CONSTANT, the function always returns -1, regardless
240of p and len.
241
242@sa copyMakeBorder
243*/
244CV_EXPORTS_W int borderInterpolate(int p, int len, int borderType);
245
246/** @example samples/cpp/tutorial_code/ImgTrans/copyMakeBorder_demo.cpp
247An example using copyMakeBorder function.
248Check @ref tutorial_copyMakeBorder "the corresponding tutorial" for more details
249*/
250
251/** @brief Forms a border around an image.
252
253The function copies the source image into the middle of the destination image. The areas to the
254left, to the right, above and below the copied source image will be filled with extrapolated
255pixels. This is not what filtering functions based on it do (they extrapolate pixels on-fly), but
256what other more complex functions, including your own, may do to simplify image boundary handling.
257
258The function supports the mode when src is already in the middle of dst . In this case, the
259function does not copy src itself but simply constructs the border, for example:
260
261@code{.cpp}
262 // let border be the same in all directions
263 int border=2;
264 // constructs a larger image to fit both the image and the border
265 Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth());
266 // select the middle part of it w/o copying data
267 Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows));
268 // convert image from RGB to grayscale
269 cvtColor(rgb, gray, COLOR_RGB2GRAY);
270 // form a border in-place
271 copyMakeBorder(gray, gray_buf, border, border,
272 border, border, BORDER_REPLICATE);
273 // now do some custom filtering ...
274 ...
275@endcode
276@note When the source image is a part (ROI) of a bigger image, the function will try to use the
277pixels outside of the ROI to form a border. To disable this feature and always do extrapolation, as
278if src was not a ROI, use borderType | #BORDER_ISOLATED.
279
280@param src Source image.
281@param dst Destination image of the same type as src and the size Size(src.cols+left+right,
282src.rows+top+bottom) .
283@param top the top pixels
284@param bottom the bottom pixels
285@param left the left pixels
286@param right Parameter specifying how many pixels in each direction from the source image rectangle
287to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs
288to be built.
289@param borderType Border type. See borderInterpolate for details.
290@param value Border value if borderType==BORDER_CONSTANT .
291
292@sa borderInterpolate
293*/
294CV_EXPORTS_W void copyMakeBorder(InputArray src, OutputArray dst,
295 int top, int bottom, int left, int right,
296 int borderType, const Scalar& value = Scalar() );
297
298/** @brief Calculates the per-element sum of two arrays or an array and a scalar.
299
300The function add calculates:
301- Sum of two arrays when both input arrays have the same size and the same number of channels:
302\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f]
303- Sum of an array and a scalar when src2 is constructed from Scalar or has the same number of
304elements as `src1.channels()`:
305\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f]
306- Sum of a scalar and an array when src1 is constructed from Scalar or has the same number of
307elements as `src2.channels()`:
308\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} + \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f]
309where `I` is a multi-dimensional index of array elements. In case of multi-channel arrays, each
310channel is processed independently.
311
312The first function in the list above can be replaced with matrix expressions:
313@code{.cpp}
314 dst = src1 + src2;
315 dst += src1; // equivalent to add(dst, src1, dst);
316@endcode
317The input arrays and the output array can all have the same or different depths. For example, you
318can add a 16-bit unsigned array to a 8-bit signed array and store the sum as a 32-bit
319floating-point array. Depth of the output array is determined by the dtype parameter. In the second
320and third cases above, as well as in the first case, when src1.depth() == src2.depth(), dtype can
321be set to the default -1. In this case, the output array will have the same depth as the input
322array, be it src1, src2 or both.
323@note Saturation is not applied when the output array has the depth CV_32S. You may even get
324result of an incorrect sign in the case of overflow.
325@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array.
326`add(src,X)` means `add(src,(X,X,X,X))`.
327`add(src,(X,))` means `add(src,(X,0,0,0))`.
328@param src1 first input array or a scalar.
329@param src2 second input array or a scalar.
330@param dst output array that has the same size and number of channels as the input array(s); the
331depth is defined by dtype or src1/src2.
332@param mask optional operation mask - 8-bit single channel array, that specifies elements of the
333output array to be changed.
334@param dtype optional depth of the output array (see the discussion below).
335@sa subtract, addWeighted, scaleAdd, Mat::convertTo
336*/
337CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst,
338 InputArray mask = noArray(), int dtype = -1);
339
340/** @brief Calculates the per-element difference between two arrays or array and a scalar.
341
342The function subtract calculates:
343- Difference between two arrays, when both input arrays have the same size and the same number of
344channels:
345 \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f]
346- Difference between an array and a scalar, when src2 is constructed from Scalar or has the same
347number of elements as `src1.channels()`:
348 \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f]
349- Difference between a scalar and an array, when src1 is constructed from Scalar or has the same
350number of elements as `src2.channels()`:
351 \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} - \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f]
352- The reverse difference between a scalar and an array in the case of `SubRS`:
353 \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src2} - \texttt{src1}(I) ) \quad \texttt{if mask}(I) \ne0\f]
354where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each
355channel is processed independently.
356
357The first function in the list above can be replaced with matrix expressions:
358@code{.cpp}
359 dst = src1 - src2;
360 dst -= src1; // equivalent to subtract(dst, src1, dst);
361@endcode
362The input arrays and the output array can all have the same or different depths. For example, you
363can subtract to 8-bit unsigned arrays and store the difference in a 16-bit signed array. Depth of
364the output array is determined by dtype parameter. In the second and third cases above, as well as
365in the first case, when src1.depth() == src2.depth(), dtype can be set to the default -1. In this
366case the output array will have the same depth as the input array, be it src1, src2 or both.
367@note Saturation is not applied when the output array has the depth CV_32S. You may even get
368result of an incorrect sign in the case of overflow.
369@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array.
370`subtract(src,X)` means `subtract(src,(X,X,X,X))`.
371`subtract(src,(X,))` means `subtract(src,(X,0,0,0))`.
372@param src1 first input array or a scalar.
373@param src2 second input array or a scalar.
374@param dst output array of the same size and the same number of channels as the input array.
375@param mask optional operation mask; this is an 8-bit single channel array that specifies elements
376of the output array to be changed.
377@param dtype optional depth of the output array
378@sa add, addWeighted, scaleAdd, Mat::convertTo
379 */
380CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst,
381 InputArray mask = noArray(), int dtype = -1);
382
383
384/** @brief Calculates the per-element scaled product of two arrays.
385
386The function multiply calculates the per-element product of two arrays:
387
388\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\f]
389
390There is also a @ref MatrixExpressions -friendly variant of the first function. See Mat::mul .
391
392For a not-per-element matrix product, see gemm .
393
394@note Saturation is not applied when the output array has the depth
395CV_32S. You may even get result of an incorrect sign in the case of
396overflow.
397@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array.
398`multiply(src,X)` means `multiply(src,(X,X,X,X))`.
399`multiply(src,(X,))` means `multiply(src,(X,0,0,0))`.
400@param src1 first input array.
401@param src2 second input array of the same size and the same type as src1.
402@param dst output array of the same size and type as src1.
403@param scale optional scale factor.
404@param dtype optional depth of the output array
405@sa add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare,
406Mat::convertTo
407*/
408CV_EXPORTS_W void multiply(InputArray src1, InputArray src2,
409 OutputArray dst, double scale = 1, int dtype = -1);
410
411/** @brief Performs per-element division of two arrays or a scalar by an array.
412
413The function cv::divide divides one array by another:
414\f[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\f]
415or a scalar by an array when there is no src1 :
416\f[\texttt{dst(I) = saturate(scale/src2(I))}\f]
417
418Different channels of multi-channel arrays are processed independently.
419
420For integer types when src2(I) is zero, dst(I) will also be zero.
421
422@note In case of floating point data there is no special defined behavior for zero src2(I) values.
423Regular floating-point division is used.
424Expect correct IEEE-754 behaviour for floating-point data (with NaN, Inf result values).
425
426@note Saturation is not applied when the output array has the depth CV_32S. You may even get
427result of an incorrect sign in the case of overflow.
428@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array.
429`divide(src,X)` means `divide(src,(X,X,X,X))`.
430`divide(src,(X,))` means `divide(src,(X,0,0,0))`.
431@param src1 first input array.
432@param src2 second input array of the same size and type as src1.
433@param scale scalar factor.
434@param dst output array of the same size and type as src2.
435@param dtype optional depth of the output array; if -1, dst will have depth src2.depth(), but in
436case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth().
437@sa multiply, add, subtract
438*/
439CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst,
440 double scale = 1, int dtype = -1);
441
442/** @overload */
443CV_EXPORTS_W void divide(double scale, InputArray src2,
444 OutputArray dst, int dtype = -1);
445
446/** @brief Calculates the sum of a scaled array and another array.
447
448The function scaleAdd is one of the classical primitive linear algebra operations, known as DAXPY
449or SAXPY in [BLAS](http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms). It calculates
450the sum of a scaled array and another array:
451\f[\texttt{dst} (I)= \texttt{scale} \cdot \texttt{src1} (I) + \texttt{src2} (I)\f]
452The function can also be emulated with a matrix expression, for example:
453@code{.cpp}
454 Mat A(3, 3, CV_64F);
455 ...
456 A.row(0) = A.row(1)*2 + A.row(2);
457@endcode
458@param src1 first input array.
459@param alpha scale factor for the first array.
460@param src2 second input array of the same size and type as src1.
461@param dst output array of the same size and type as src1.
462@sa add, addWeighted, subtract, Mat::dot, Mat::convertTo
463*/
464CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst);
465
466/** @brief Calculates the weighted sum of two arrays.
467
468The function addWeighted calculates the weighted sum of two arrays as follows:
469\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} + \texttt{src2} (I)* \texttt{beta} + \texttt{gamma} )\f]
470where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each
471channel is processed independently.
472The function can be replaced with a matrix expression:
473@code{.cpp}
474 dst = src1*alpha + src2*beta + gamma;
475@endcode
476@note Saturation is not applied when the output array has the depth CV_32S. You may even get
477result of an incorrect sign in the case of overflow.
478@param src1 first input array.
479@param alpha weight of the first array elements.
480@param src2 second input array of the same size and channel number as src1.
481@param beta weight of the second array elements.
482@param gamma scalar added to each sum.
483@param dst output array that has the same size and number of channels as the input arrays.
484@param dtype optional depth of the output array; when both input arrays have the same depth, dtype
485can be set to -1, which will be equivalent to src1.depth().
486@sa add, subtract, scaleAdd, Mat::convertTo
487*/
488CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2,
489 double beta, double gamma, OutputArray dst, int dtype = -1);
490
491/** @brief Scales, calculates absolute values, and converts the result to 8-bit.
492
493On each element of the input array, the function convertScaleAbs
494performs three operations sequentially: scaling, taking an absolute
495value, conversion to an unsigned 8-bit type:
496\f[\texttt{dst} (I)= \texttt{saturate\_cast<uchar>} (| \texttt{src} (I)* \texttt{alpha} + \texttt{beta} |)\f]
497In case of multi-channel arrays, the function processes each channel
498independently. When the output is not 8-bit, the operation can be
499emulated by calling the Mat::convertTo method (or by using matrix
500expressions) and then by calculating an absolute value of the result.
501For example:
502@code{.cpp}
503 Mat_<float> A(30,30);
504 randu(A, Scalar(-100), Scalar(100));
505 Mat_<float> B = A*5 + 3;
506 B = abs(B);
507 // Mat_<float> B = abs(A*5+3) will also do the job,
508 // but it will allocate a temporary matrix
509@endcode
510@param src input array.
511@param dst output array.
512@param alpha optional scale factor.
513@param beta optional delta added to the scaled values.
514@sa Mat::convertTo, cv::abs(const Mat&)
515*/
516CV_EXPORTS_W void convertScaleAbs(InputArray src, OutputArray dst,
517 double alpha = 1, double beta = 0);
518
519/** @brief Converts an array to half precision floating number.
520
521This function converts FP32 (single precision floating point) from/to FP16 (half precision floating point). CV_16S format is used to represent FP16 data.
522There are two use modes (src -> dst): CV_32F -> CV_16S and CV_16S -> CV_32F. The input array has to have type of CV_32F or
523CV_16S to represent the bit depth. If the input array is neither of them, the function will raise an error.
524The format of half precision floating point is defined in IEEE 754-2008.
525
526@param src input array.
527@param dst output array.
528
529@deprecated Use Mat::convertTo with CV_16F instead.
530*/
531CV_EXPORTS_W void convertFp16(InputArray src, OutputArray dst);
532
533/** @example samples/cpp/tutorial_code/core/how_to_scan_images/how_to_scan_images.cpp
534Check @ref tutorial_how_to_scan_images "the corresponding tutorial" for more details
535*/
536
537/** @brief Performs a look-up table transform of an array.
538
539The function LUT fills the output array with values from the look-up table. Indices of the entries
540are taken from the input array. That is, the function processes each element of src as follows:
541\f[\texttt{dst} (I) \leftarrow \texttt{lut(src(I) + d)}\f]
542where
543\f[d = \fork{0}{if \(\texttt{src}\) has depth \(\texttt{CV_8U}\)}{128}{if \(\texttt{src}\) has depth \(\texttt{CV_8S}\)}\f]
544@param src input array of 8-bit elements.
545@param lut look-up table of 256 elements; in case of multi-channel input array, the table should
546either have a single channel (in this case the same table is used for all channels) or the same
547number of channels as in the input array.
548@param dst output array of the same size and number of channels as src, and the same depth as lut.
549@sa convertScaleAbs, Mat::convertTo
550*/
551CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst);
552
553/** @brief Calculates the sum of array elements.
554
555The function cv::sum calculates and returns the sum of array elements,
556independently for each channel.
557@param src input array that must have from 1 to 4 channels.
558@sa countNonZero, mean, meanStdDev, norm, minMaxLoc, reduce
559*/
560CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src);
561
562/** @brief Checks for the presence of at least one non-zero array element.
563
564The function returns whether there are non-zero elements in src
565
566The function do not work with multi-channel arrays. If you need to check non-zero array
567elements across all the channels, use Mat::reshape first to reinterpret the array as
568single-channel. Or you may extract the particular channel using either extractImageCOI, or
569mixChannels, or split.
570
571@note
572- If the location of non-zero array elements is important, @ref findNonZero is helpful.
573- If the count of non-zero array elements is important, @ref countNonZero is helpful.
574@param src single-channel array.
575@sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix
576@sa findNonZero, countNonZero
577*/
578CV_EXPORTS_W bool hasNonZero( InputArray src );
579
580/** @brief Counts non-zero array elements.
581
582The function returns the number of non-zero elements in src :
583\f[\sum _{I: \; \texttt{src} (I) \ne0 } 1\f]
584
585The function do not work with multi-channel arrays. If you need to count non-zero array
586elements across all the channels, use Mat::reshape first to reinterpret the array as
587single-channel. Or you may extract the particular channel using either extractImageCOI, or
588mixChannels, or split.
589
590@note
591- If only whether there are non-zero elements is important, @ref hasNonZero is helpful.
592- If the location of non-zero array elements is important, @ref findNonZero is helpful.
593@param src single-channel array.
594@sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix
595@sa findNonZero, hasNonZero
596*/
597CV_EXPORTS_W int countNonZero( InputArray src );
598
599/** @brief Returns the list of locations of non-zero pixels
600
601Given a binary matrix (likely returned from an operation such
602as threshold(), compare(), >, ==, etc, return all of
603the non-zero indices as a cv::Mat or std::vector<cv::Point> (x,y)
604For example:
605@code{.cpp}
606 cv::Mat binaryImage; // input, binary image
607 cv::Mat locations; // output, locations of non-zero pixels
608 cv::findNonZero(binaryImage, locations);
609
610 // access pixel coordinates
611 Point pnt = locations.at<Point>(i);
612@endcode
613or
614@code{.cpp}
615 cv::Mat binaryImage; // input, binary image
616 vector<Point> locations; // output, locations of non-zero pixels
617 cv::findNonZero(binaryImage, locations);
618
619 // access pixel coordinates
620 Point pnt = locations[i];
621@endcode
622
623The function do not work with multi-channel arrays. If you need to find non-zero
624elements across all the channels, use Mat::reshape first to reinterpret the array as
625single-channel. Or you may extract the particular channel using either extractImageCOI, or
626mixChannels, or split.
627
628@note
629- If only count of non-zero array elements is important, @ref countNonZero is helpful.
630- If only whether there are non-zero elements is important, @ref hasNonZero is helpful.
631@param src single-channel array
632@param idx the output array, type of cv::Mat or std::vector<Point>, corresponding to non-zero indices in the input
633@sa countNonZero, hasNonZero
634*/
635CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx );
636
637/** @brief Calculates an average (mean) of array elements.
638
639The function cv::mean calculates the mean value M of array elements,
640independently for each channel, and return it:
641\f[\begin{array}{l} N = \sum _{I: \; \texttt{mask} (I) \ne 0} 1 \\ M_c = \left ( \sum _{I: \; \texttt{mask} (I) \ne 0}{ \texttt{mtx} (I)_c} \right )/N \end{array}\f]
642When all the mask elements are 0's, the function returns Scalar::all(0)
643@param src input array that should have from 1 to 4 channels so that the result can be stored in
644Scalar_ .
645@param mask optional operation mask.
646@sa countNonZero, meanStdDev, norm, minMaxLoc
647*/
648CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask = noArray());
649
650/** Calculates a mean and standard deviation of array elements.
651
652The function cv::meanStdDev calculates the mean and the standard deviation M
653of array elements independently for each channel and returns it via the
654output parameters:
655\f[\begin{array}{l} N = \sum _{I, \texttt{mask} (I) \ne 0} 1 \\ \texttt{mean} _c = \frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \texttt{src} (I)_c}{N} \\ \texttt{stddev} _c = \sqrt{\frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \left ( \texttt{src} (I)_c - \texttt{mean} _c \right )^2}{N}} \end{array}\f]
656When all the mask elements are 0's, the function returns
657mean=stddev=Scalar::all(0).
658@note The calculated standard deviation is only the diagonal of the
659complete normalized covariance matrix. If the full matrix is needed, you
660can reshape the multi-channel array M x N to the single-channel array
661M\*N x mtx.channels() (only possible when the matrix is continuous) and
662then pass the matrix to calcCovarMatrix .
663@param src input array that should have from 1 to 4 channels so that the results can be stored in
664Scalar_ 's.
665@param mean output parameter: calculated mean value.
666@param stddev output parameter: calculated standard deviation.
667@param mask optional operation mask.
668@sa countNonZero, mean, norm, minMaxLoc, calcCovarMatrix
669*/
670CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev,
671 InputArray mask=noArray());
672
673/** @brief Calculates the absolute norm of an array.
674
675This version of #norm calculates the absolute norm of src1. The type of norm to calculate is specified using #NormTypes.
676
677As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$.
678The \f$ L_{1}, L_{2} \f$ and \f$ L_{\infty} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$
679is calculated as follows
680\f{align*}
681 \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\
682 \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\
683 \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2
684\f}
685and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is
686\f{align*}
687 \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\
688 \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\
689 \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5.
690\f}
691The following graphic shows all values for the three norm functions \f$\| r(x) \|_{L_1}, \| r(x) \|_{L_2}\f$ and \f$\| r(x) \|_{L_\infty}\f$.
692It is notable that the \f$ L_{1} \f$ norm forms the upper and the \f$ L_{\infty} \f$ norm forms the lower border for the example function \f$ r(x) \f$.
693![Graphs for the different norm functions from the above example](pics/NormTypes_OneArray_1-2-INF.png)
694
695When the mask parameter is specified and it is not empty, the norm is
696
697If normType is not specified, #NORM_L2 is used.
698calculated only over the region specified by the mask.
699
700Multi-channel input arrays are treated as single-channel arrays, that is,
701the results for all channels are combined.
702
703Hamming norms can only be calculated with CV_8U depth arrays.
704
705@param src1 first input array.
706@param normType type of the norm (see #NormTypes).
707@param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type.
708*/
709CV_EXPORTS_W double norm(InputArray src1, int normType = NORM_L2, InputArray mask = noArray());
710
711/** @brief Calculates an absolute difference norm or a relative difference norm.
712
713This version of cv::norm calculates the absolute difference norm
714or the relative difference norm of arrays src1 and src2.
715The type of norm to calculate is specified using #NormTypes.
716
717@param src1 first input array.
718@param src2 second input array of the same size and the same type as src1.
719@param normType type of the norm (see #NormTypes).
720@param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type.
721*/
722CV_EXPORTS_W double norm(InputArray src1, InputArray src2,
723 int normType = NORM_L2, InputArray mask = noArray());
724/** @overload
725@param src first input array.
726@param normType type of the norm (see #NormTypes).
727*/
728CV_EXPORTS double norm( const SparseMat& src, int normType );
729
730/** @brief Computes the Peak Signal-to-Noise Ratio (PSNR) image quality metric.
731
732This function calculates the Peak Signal-to-Noise Ratio (PSNR) image quality metric in decibels (dB),
733between two input arrays src1 and src2. The arrays must have the same type.
734
735The PSNR is calculated as follows:
736
737\f[
738\texttt{PSNR} = 10 \cdot \log_{10}{\left( \frac{R^2}{MSE} \right) }
739\f]
740
741where R is the maximum integer value of depth (e.g. 255 in the case of CV_8U data)
742and MSE is the mean squared error between the two arrays.
743
744@param src1 first input array.
745@param src2 second input array of the same size as src1.
746@param R the maximum pixel value (255 by default)
747
748 */
749CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2, double R=255.);
750
751/** @brief naive nearest neighbor finder
752
753see http://en.wikipedia.org/wiki/Nearest_neighbor_search
754@todo document
755 */
756CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2,
757 OutputArray dist, int dtype, OutputArray nidx,
758 int normType = NORM_L2, int K = 0,
759 InputArray mask = noArray(), int update = 0,
760 bool crosscheck = false);
761
762/** @brief Normalizes the norm or value range of an array.
763
764The function cv::normalize normalizes scale and shift the input array elements so that
765\f[\| \texttt{dst} \| _{L_p}= \texttt{alpha}\f]
766(where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that
767\f[\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\f]
768
769when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be
770normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this
771sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or
772min-max but modify the whole array, you can use norm and Mat::convertTo.
773
774In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this,
775the range transformation for sparse matrices is not allowed since it can shift the zero level.
776
777Possible usage with some positive example data:
778@code{.cpp}
779 vector<double> positiveData = { 2.0, 8.0, 10.0 };
780 vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax;
781
782 // Norm to probability (total count)
783 // sum(numbers) = 20.0
784 // 2.0 0.1 (2.0/20.0)
785 // 8.0 0.4 (8.0/20.0)
786 // 10.0 0.5 (10.0/20.0)
787 normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1);
788
789 // Norm to unit vector: ||positiveData|| = 1.0
790 // 2.0 0.15
791 // 8.0 0.62
792 // 10.0 0.77
793 normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2);
794
795 // Norm to max element
796 // 2.0 0.2 (2.0/10.0)
797 // 8.0 0.8 (8.0/10.0)
798 // 10.0 1.0 (10.0/10.0)
799 normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF);
800
801 // Norm to range [0.0;1.0]
802 // 2.0 0.0 (shift to left border)
803 // 8.0 0.75 (6.0/8.0)
804 // 10.0 1.0 (shift to right border)
805 normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX);
806@endcode
807
808@note Due to rounding issues, min-max normalization can result in values outside provided boundaries.
809If exact range conformity is needed, following workarounds can be used:
810- use double floating point precision (dtype = CV_64F)
811- manually clip values (`cv::max(res, left_bound, res)`, `cv::min(res, right_bound, res)` or `np.clip`)
812
813@param src input array.
814@param dst output array of the same size as src .
815@param alpha norm value to normalize to or the lower range boundary in case of the range
816normalization.
817@param beta upper range boundary in case of the range normalization; it is not used for the norm
818normalization.
819@param norm_type normalization type (see cv::NormTypes).
820@param dtype when negative, the output array has the same type as src; otherwise, it has the same
821number of channels as src and the depth =CV_MAT_DEPTH(dtype).
822@param mask optional operation mask.
823@sa norm, Mat::convertTo, SparseMat::convertTo
824*/
825CV_EXPORTS_W void normalize( InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0,
826 int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray());
827
828/** @overload
829@param src input array.
830@param dst output array of the same size as src .
831@param alpha norm value to normalize to or the lower range boundary in case of the range
832normalization.
833@param normType normalization type (see cv::NormTypes).
834*/
835CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType );
836
837/** @brief Finds the global minimum and maximum in an array.
838
839The function cv::minMaxLoc finds the minimum and maximum element values and their positions. The
840extrema are searched across the whole array or, if mask is not an empty array, in the specified
841array region.
842
843In C++, if the input is multi-channel, you should omit the minLoc, maxLoc, and mask arguments
844(i.e. leave them as NULL, NULL, and noArray() respectively). These arguments are not
845supported for multi-channel input arrays. If working with multi-channel input and you
846need the minLoc, maxLoc, or mask arguments, then use Mat::reshape first to reinterpret
847the array as single-channel. Alternatively, you can extract the particular channel using either
848extractImageCOI, mixChannels, or split.
849
850In Python, multi-channel input is not supported at all due to a limitation in the
851binding generation process (there is no way to set minLoc and maxLoc to NULL). A
852workaround is to operate on each channel individually or to use NumPy to achieve the same
853functionality.
854
855@param src input single-channel array.
856@param minVal pointer to the returned minimum value; NULL is used if not required.
857@param maxVal pointer to the returned maximum value; NULL is used if not required.
858@param minLoc pointer to the returned minimum location (in 2D case); NULL is used if not required.
859@param maxLoc pointer to the returned maximum location (in 2D case); NULL is used if not required.
860@param mask optional mask used to select a sub-array.
861@sa max, min, reduceArgMin, reduceArgMax, compare, inRange, extractImageCOI, mixChannels, split, Mat::reshape
862*/
863CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal,
864 CV_OUT double* maxVal = 0, CV_OUT Point* minLoc = 0,
865 CV_OUT Point* maxLoc = 0, InputArray mask = noArray());
866
867/**
868 * @brief Finds indices of min elements along provided axis
869 *
870 * @note
871 * - If input or output array is not continuous, this function will create an internal copy.
872 * - NaN handling is left unspecified, see patchNaNs().
873 * - The returned index is always in bounds of input matrix.
874 *
875 * @param src input single-channel array.
876 * @param dst output array of type CV_32SC1 with the same dimensionality as src,
877 * except for axis being reduced - it should be set to 1.
878 * @param lastIndex whether to get the index of first or last occurrence of min.
879 * @param axis axis to reduce along.
880 * @sa reduceArgMax, minMaxLoc, min, max, compare, reduce
881 */
882CV_EXPORTS_W void reduceArgMin(InputArray src, OutputArray dst, int axis, bool lastIndex = false);
883
884/**
885 * @brief Finds indices of max elements along provided axis
886 *
887 * @note
888 * - If input or output array is not continuous, this function will create an internal copy.
889 * - NaN handling is left unspecified, see patchNaNs().
890 * - The returned index is always in bounds of input matrix.
891 *
892 * @param src input single-channel array.
893 * @param dst output array of type CV_32SC1 with the same dimensionality as src,
894 * except for axis being reduced - it should be set to 1.
895 * @param lastIndex whether to get the index of first or last occurrence of max.
896 * @param axis axis to reduce along.
897 * @sa reduceArgMin, minMaxLoc, min, max, compare, reduce
898 */
899CV_EXPORTS_W void reduceArgMax(InputArray src, OutputArray dst, int axis, bool lastIndex = false);
900
901/** @brief Finds the global minimum and maximum in an array
902
903The function cv::minMaxIdx finds the minimum and maximum element values and their positions. The
904extremums are searched across the whole array or, if mask is not an empty array, in the specified
905array region. In case of a sparse matrix, the minimum is found among non-zero elements
906only. Multi-channel input is supported without mask and extremums indexes (should be nullptr).
907@note When minIdx is not NULL, it must have at least 2 elements (as well as maxIdx), even if src is
908a single-row or single-column matrix. In OpenCV (following MATLAB) each array has at least 2
909dimensions, i.e. single-column matrix is Mx1 matrix (and therefore minIdx/maxIdx will be
910(i1,0)/(i2,0)) and single-row matrix is 1xN matrix (and therefore minIdx/maxIdx will be
911(0,j1)/(0,j2)).
912@param src input single-channel array.
913@param minVal pointer to the returned minimum value; NULL is used if not required.
914@param maxVal pointer to the returned maximum value; NULL is used if not required.
915@param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required;
916Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element
917in each dimension are stored there sequentially.
918@param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required.
919@param mask specified array region
920*/
921CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal = 0,
922 int* minIdx = 0, int* maxIdx = 0, InputArray mask = noArray());
923
924/** @overload
925@param a input single-channel array.
926@param minVal pointer to the returned minimum value; NULL is used if not required.
927@param maxVal pointer to the returned maximum value; NULL is used if not required.
928@param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required;
929Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element
930in each dimension are stored there sequentially.
931@param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required.
932*/
933CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal,
934 double* maxVal, int* minIdx = 0, int* maxIdx = 0);
935
936/** @brief Reduces a matrix to a vector.
937
938The function #reduce reduces the matrix to a vector by treating the matrix rows/columns as a set of
9391D vectors and performing the specified operation on the vectors until a single row/column is
940obtained. For example, the function can be used to compute horizontal and vertical projections of a
941raster image. In case of #REDUCE_MAX and #REDUCE_MIN, the output image should have the same type as the source one.
942In case of #REDUCE_SUM, #REDUCE_SUM2 and #REDUCE_AVG, the output may have a larger element bit-depth to preserve accuracy.
943And multi-channel arrays are also supported in these two reduction modes.
944
945The following code demonstrates its usage for a single channel matrix.
946@snippet snippets/core_reduce.cpp example
947
948And the following code demonstrates its usage for a two-channel matrix.
949@snippet snippets/core_reduce.cpp example2
950
951@param src input 2D matrix.
952@param dst output vector. Its size and type is defined by dim and dtype parameters.
953@param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to
954a single row. 1 means that the matrix is reduced to a single column.
955@param rtype reduction operation that could be one of #ReduceTypes
956@param dtype when negative, the output vector will have the same type as the input matrix,
957otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()).
958@sa repeat, reduceArgMin, reduceArgMax
959*/
960CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype = -1);
961
962/** @brief Creates one multi-channel array out of several single-channel ones.
963
964The function cv::merge merges several arrays to make a single multi-channel array. That is, each
965element of the output array will be a concatenation of the elements of the input arrays, where
966elements of i-th input array are treated as mv[i].channels()-element vectors.
967
968The function cv::split does the reverse operation. If you need to shuffle channels in some other
969advanced way, use cv::mixChannels.
970
971The following example shows how to merge 3 single channel matrices into a single 3-channel matrix.
972@snippet snippets/core_merge.cpp example
973
974@param mv input array of matrices to be merged; all the matrices in mv must have the same
975size and the same depth.
976@param count number of input matrices when mv is a plain C array; it must be greater than zero.
977@param dst output array of the same size and the same depth as mv[0]; The number of channels will
978be equal to the parameter count.
979@sa mixChannels, split, Mat::reshape
980*/
981CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst);
982
983/** @overload
984@param mv input vector of matrices to be merged; all the matrices in mv must have the same
985size and the same depth.
986@param dst output array of the same size and the same depth as mv[0]; The number of channels will
987be the total number of channels in the matrix array.
988 */
989CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst);
990
991/** @brief Divides a multi-channel array into several single-channel arrays.
992
993The function cv::split splits a multi-channel array into separate single-channel arrays:
994\f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f]
995If you need to extract a single channel or do some other sophisticated channel permutation, use
996mixChannels.
997
998The following example demonstrates how to split a 3-channel matrix into 3 single channel matrices.
999@snippet snippets/core_split.cpp example
1000
1001@param src input multi-channel array.
1002@param mvbegin output array; the number of arrays must match src.channels(); the arrays themselves are
1003reallocated, if needed.
1004@sa merge, mixChannels, cvtColor
1005*/
1006CV_EXPORTS void split(const Mat& src, Mat* mvbegin);
1007
1008/** @overload
1009@param m input multi-channel array.
1010@param mv output vector of arrays; the arrays themselves are reallocated, if needed.
1011*/
1012CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv);
1013
1014/** @brief Copies specified channels from input arrays to the specified channels of
1015output arrays.
1016
1017The function cv::mixChannels provides an advanced mechanism for shuffling image channels.
1018
1019cv::split,cv::merge,cv::extractChannel,cv::insertChannel and some forms of cv::cvtColor are partial cases of cv::mixChannels.
1020
1021In the example below, the code splits a 4-channel BGRA image into a 3-channel BGR (with B and R
1022channels swapped) and a separate alpha-channel image:
1023@code{.cpp}
1024 Mat bgra( 100, 100, CV_8UC4, Scalar(255,0,0,255) );
1025 Mat bgr( bgra.rows, bgra.cols, CV_8UC3 );
1026 Mat alpha( bgra.rows, bgra.cols, CV_8UC1 );
1027
1028 // forming an array of matrices is a quite efficient operation,
1029 // because the matrix data is not copied, only the headers
1030 Mat out[] = { bgr, alpha };
1031 // bgra[0] -> bgr[2], bgra[1] -> bgr[1],
1032 // bgra[2] -> bgr[0], bgra[3] -> alpha[0]
1033 int from_to[] = { 0,2, 1,1, 2,0, 3,3 };
1034 mixChannels( &bgra, 1, out, 2, from_to, 4 );
1035@endcode
1036@note Unlike many other new-style C++ functions in OpenCV (see the introduction section and
1037Mat::create ), cv::mixChannels requires the output arrays to be pre-allocated before calling the
1038function.
1039@param src input array or vector of matrices; all of the matrices must have the same size and the
1040same depth.
1041@param nsrcs number of matrices in `src`.
1042@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and
1043depth must be the same as in `src[0]`.
1044@param ndsts number of matrices in `dst`.
1045@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is
1046a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in
1047dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to
1048src[0].channels()-1, the second input image channels are indexed from src[0].channels() to
1049src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image
1050channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is
1051filled with zero .
1052@param npairs number of index pairs in `fromTo`.
1053@sa split, merge, extractChannel, insertChannel, cvtColor
1054*/
1055CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts,
1056 const int* fromTo, size_t npairs);
1057
1058/** @overload
1059@param src input array or vector of matrices; all of the matrices must have the same size and the
1060same depth.
1061@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and
1062depth must be the same as in src[0].
1063@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is
1064a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in
1065dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to
1066src[0].channels()-1, the second input image channels are indexed from src[0].channels() to
1067src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image
1068channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is
1069filled with zero .
1070@param npairs number of index pairs in fromTo.
1071*/
1072CV_EXPORTS void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst,
1073 const int* fromTo, size_t npairs);
1074
1075/** @overload
1076@param src input array or vector of matrices; all of the matrices must have the same size and the
1077same depth.
1078@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and
1079depth must be the same as in src[0].
1080@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is
1081a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in
1082dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to
1083src[0].channels()-1, the second input image channels are indexed from src[0].channels() to
1084src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image
1085channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is
1086filled with zero .
1087*/
1088CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst,
1089 const std::vector<int>& fromTo);
1090
1091/** @brief Extracts a single channel from src (coi is 0-based index)
1092@param src input array
1093@param dst output array
1094@param coi index of channel to extract
1095@sa mixChannels, split
1096*/
1097CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi);
1098
1099/** @brief Inserts a single channel to dst (coi is 0-based index)
1100@param src input array
1101@param dst output array
1102@param coi index of channel for insertion
1103@sa mixChannels, merge
1104*/
1105CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi);
1106
1107/** @brief Flips a 2D array around vertical, horizontal, or both axes.
1108
1109The function cv::flip flips the array in one of three different ways (row
1110and column indices are 0-based):
1111\f[\texttt{dst} _{ij} =
1112\left\{
1113\begin{array}{l l}
1114\texttt{src} _{\texttt{src.rows}-i-1,j} & if\; \texttt{flipCode} = 0 \\
1115\texttt{src} _{i, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} > 0 \\
1116\texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\
1117\end{array}
1118\right.\f]
1119The example scenarios of using the function are the following:
1120* Vertical flipping of the image (flipCode == 0) to switch between
1121 top-left and bottom-left image origin. This is a typical operation
1122 in video processing on Microsoft Windows\* OS.
1123* Horizontal flipping of the image with the subsequent horizontal
1124 shift and absolute difference calculation to check for a
1125 vertical-axis symmetry (flipCode \> 0).
1126* Simultaneous horizontal and vertical flipping of the image with
1127 the subsequent shift and absolute difference calculation to check
1128 for a central symmetry (flipCode \< 0).
1129* Reversing the order of point arrays (flipCode \> 0 or
1130 flipCode == 0).
1131@param src input array.
1132@param dst output array of the same size and type as src.
1133@param flipCode a flag to specify how to flip the array; 0 means
1134flipping around the x-axis and positive value (for example, 1) means
1135flipping around y-axis. Negative value (for example, -1) means flipping
1136around both axes.
1137@sa transpose, repeat, completeSymm
1138*/
1139CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode);
1140
1141/** @brief Flips a n-dimensional at given axis
1142 * @param src input array
1143 * @param dst output array that has the same shape of src
1144 * @param axis axis that performs a flip on. 0 <= axis < src.dims.
1145 */
1146CV_EXPORTS_W void flipND(InputArray src, OutputArray dst, int axis);
1147
1148/** @brief Broadcast the given Mat to the given shape.
1149 * @param src input array
1150 * @param shape target shape. Should be a list of CV_32S numbers. Note that negative values are not supported.
1151 * @param dst output array that has the given shape
1152 */
1153CV_EXPORTS_W void broadcast(InputArray src, InputArray shape, OutputArray dst);
1154
1155enum RotateFlags {
1156 ROTATE_90_CLOCKWISE = 0, //!<Rotate 90 degrees clockwise
1157 ROTATE_180 = 1, //!<Rotate 180 degrees clockwise
1158 ROTATE_90_COUNTERCLOCKWISE = 2, //!<Rotate 270 degrees clockwise
1159};
1160/** @brief Rotates a 2D array in multiples of 90 degrees.
1161The function cv::rotate rotates the array in one of three different ways:
1162* Rotate by 90 degrees clockwise (rotateCode = ROTATE_90_CLOCKWISE).
1163* Rotate by 180 degrees clockwise (rotateCode = ROTATE_180).
1164* Rotate by 270 degrees clockwise (rotateCode = ROTATE_90_COUNTERCLOCKWISE).
1165@param src input array.
1166@param dst output array of the same type as src. The size is the same with ROTATE_180,
1167and the rows and cols are switched for ROTATE_90_CLOCKWISE and ROTATE_90_COUNTERCLOCKWISE.
1168@param rotateCode an enum to specify how to rotate the array; see the enum #RotateFlags
1169@sa transpose, repeat, completeSymm, flip, RotateFlags
1170*/
1171CV_EXPORTS_W void rotate(InputArray src, OutputArray dst, int rotateCode);
1172
1173/** @brief Fills the output array with repeated copies of the input array.
1174
1175The function cv::repeat duplicates the input array one or more times along each of the two axes:
1176\f[\texttt{dst} _{ij}= \texttt{src} _{i\mod src.rows, \; j\mod src.cols }\f]
1177The second variant of the function is more convenient to use with @ref MatrixExpressions.
1178@param src input array to replicate.
1179@param ny Flag to specify how many times the `src` is repeated along the
1180vertical axis.
1181@param nx Flag to specify how many times the `src` is repeated along the
1182horizontal axis.
1183@param dst output array of the same type as `src`.
1184@sa cv::reduce
1185*/
1186CV_EXPORTS_W void repeat(InputArray src, int ny, int nx, OutputArray dst);
1187
1188/** @overload
1189@param src input array to replicate.
1190@param ny Flag to specify how many times the `src` is repeated along the
1191vertical axis.
1192@param nx Flag to specify how many times the `src` is repeated along the
1193horizontal axis.
1194 */
1195CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx);
1196
1197/** @brief Applies horizontal concatenation to given matrices.
1198
1199The function horizontally concatenates two or more cv::Mat matrices (with the same number of rows).
1200@code{.cpp}
1201 cv::Mat matArray[] = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)),
1202 cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)),
1203 cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),};
1204
1205 cv::Mat out;
1206 cv::hconcat( matArray, 3, out );
1207 //out:
1208 //[1, 2, 3;
1209 // 1, 2, 3;
1210 // 1, 2, 3;
1211 // 1, 2, 3]
1212@endcode
1213@param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth.
1214@param nsrc number of matrices in src.
1215@param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src.
1216@sa cv::vconcat(const Mat*, size_t, OutputArray), @sa cv::vconcat(InputArrayOfArrays, OutputArray) and @sa cv::vconcat(InputArray, InputArray, OutputArray)
1217*/
1218CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, OutputArray dst);
1219/** @overload
1220 @code{.cpp}
1221 cv::Mat_<float> A = (cv::Mat_<float>(3, 2) << 1, 4,
1222 2, 5,
1223 3, 6);
1224 cv::Mat_<float> B = (cv::Mat_<float>(3, 2) << 7, 10,
1225 8, 11,
1226 9, 12);
1227
1228 cv::Mat C;
1229 cv::hconcat(A, B, C);
1230 //C:
1231 //[1, 4, 7, 10;
1232 // 2, 5, 8, 11;
1233 // 3, 6, 9, 12]
1234 @endcode
1235 @param src1 first input array to be considered for horizontal concatenation.
1236 @param src2 second input array to be considered for horizontal concatenation.
1237 @param dst output array. It has the same number of rows and depth as the src1 and src2, and the sum of cols of the src1 and src2.
1238 */
1239CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst);
1240/** @overload
1241 @code{.cpp}
1242 std::vector<cv::Mat> matrices = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)),
1243 cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)),
1244 cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),};
1245
1246 cv::Mat out;
1247 cv::hconcat( matrices, out );
1248 //out:
1249 //[1, 2, 3;
1250 // 1, 2, 3;
1251 // 1, 2, 3;
1252 // 1, 2, 3]
1253 @endcode
1254 @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth.
1255 @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src.
1256same depth.
1257 */
1258CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst);
1259
1260/** @brief Applies vertical concatenation to given matrices.
1261
1262The function vertically concatenates two or more cv::Mat matrices (with the same number of cols).
1263@code{.cpp}
1264 cv::Mat matArray[] = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)),
1265 cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)),
1266 cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),};
1267
1268 cv::Mat out;
1269 cv::vconcat( matArray, 3, out );
1270 //out:
1271 //[1, 1, 1, 1;
1272 // 2, 2, 2, 2;
1273 // 3, 3, 3, 3]
1274@endcode
1275@param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth.
1276@param nsrc number of matrices in src.
1277@param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src.
1278@sa cv::hconcat(const Mat*, size_t, OutputArray), @sa cv::hconcat(InputArrayOfArrays, OutputArray) and @sa cv::hconcat(InputArray, InputArray, OutputArray)
1279*/
1280CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst);
1281/** @overload
1282 @code{.cpp}
1283 cv::Mat_<float> A = (cv::Mat_<float>(3, 2) << 1, 7,
1284 2, 8,
1285 3, 9);
1286 cv::Mat_<float> B = (cv::Mat_<float>(3, 2) << 4, 10,
1287 5, 11,
1288 6, 12);
1289
1290 cv::Mat C;
1291 cv::vconcat(A, B, C);
1292 //C:
1293 //[1, 7;
1294 // 2, 8;
1295 // 3, 9;
1296 // 4, 10;
1297 // 5, 11;
1298 // 6, 12]
1299 @endcode
1300 @param src1 first input array to be considered for vertical concatenation.
1301 @param src2 second input array to be considered for vertical concatenation.
1302 @param dst output array. It has the same number of cols and depth as the src1 and src2, and the sum of rows of the src1 and src2.
1303 */
1304CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst);
1305/** @overload
1306 @code{.cpp}
1307 std::vector<cv::Mat> matrices = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)),
1308 cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)),
1309 cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),};
1310
1311 cv::Mat out;
1312 cv::vconcat( matrices, out );
1313 //out:
1314 //[1, 1, 1, 1;
1315 // 2, 2, 2, 2;
1316 // 3, 3, 3, 3]
1317 @endcode
1318 @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth
1319 @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src.
1320same depth.
1321 */
1322CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst);
1323
1324/** @brief computes bitwise conjunction of the two arrays (dst = src1 & src2)
1325Calculates the per-element bit-wise conjunction of two arrays or an
1326array and a scalar.
1327
1328The function cv::bitwise_and calculates the per-element bit-wise logical conjunction for:
1329* Two arrays when src1 and src2 have the same size:
1330 \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
1331* An array and a scalar when src2 is constructed from Scalar or has
1332 the same number of elements as `src1.channels()`:
1333 \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]
1334* A scalar and an array when src1 is constructed from Scalar or has
1335 the same number of elements as `src2.channels()`:
1336 \f[\texttt{dst} (I) = \texttt{src1} \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
1337In case of floating-point arrays, their machine-specific bit
1338representations (usually IEEE754-compliant) are used for the operation.
1339In case of multi-channel arrays, each channel is processed
1340independently. In the second and third cases above, the scalar is first
1341converted to the array type.
1342@param src1 first input array or a scalar.
1343@param src2 second input array or a scalar.
1344@param dst output array that has the same size and type as the input
1345arrays.
1346@param mask optional operation mask, 8-bit single channel array, that
1347specifies elements of the output array to be changed.
1348*/
1349CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2,
1350 OutputArray dst, InputArray mask = noArray());
1351
1352/** @brief Calculates the per-element bit-wise disjunction of two arrays or an
1353array and a scalar.
1354
1355The function cv::bitwise_or calculates the per-element bit-wise logical disjunction for:
1356* Two arrays when src1 and src2 have the same size:
1357 \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
1358* An array and a scalar when src2 is constructed from Scalar or has
1359 the same number of elements as `src1.channels()`:
1360 \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]
1361* A scalar and an array when src1 is constructed from Scalar or has
1362 the same number of elements as `src2.channels()`:
1363 \f[\texttt{dst} (I) = \texttt{src1} \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
1364In case of floating-point arrays, their machine-specific bit
1365representations (usually IEEE754-compliant) are used for the operation.
1366In case of multi-channel arrays, each channel is processed
1367independently. In the second and third cases above, the scalar is first
1368converted to the array type.
1369@param src1 first input array or a scalar.
1370@param src2 second input array or a scalar.
1371@param dst output array that has the same size and type as the input
1372arrays.
1373@param mask optional operation mask, 8-bit single channel array, that
1374specifies elements of the output array to be changed.
1375*/
1376CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2,
1377 OutputArray dst, InputArray mask = noArray());
1378
1379/** @brief Calculates the per-element bit-wise "exclusive or" operation on two
1380arrays or an array and a scalar.
1381
1382The function cv::bitwise_xor calculates the per-element bit-wise logical "exclusive-or"
1383operation for:
1384* Two arrays when src1 and src2 have the same size:
1385 \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
1386* An array and a scalar when src2 is constructed from Scalar or has
1387 the same number of elements as `src1.channels()`:
1388 \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]
1389* A scalar and an array when src1 is constructed from Scalar or has
1390 the same number of elements as `src2.channels()`:
1391 \f[\texttt{dst} (I) = \texttt{src1} \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
1392In case of floating-point arrays, their machine-specific bit
1393representations (usually IEEE754-compliant) are used for the operation.
1394In case of multi-channel arrays, each channel is processed
1395independently. In the 2nd and 3rd cases above, the scalar is first
1396converted to the array type.
1397@param src1 first input array or a scalar.
1398@param src2 second input array or a scalar.
1399@param dst output array that has the same size and type as the input
1400arrays.
1401@param mask optional operation mask, 8-bit single channel array, that
1402specifies elements of the output array to be changed.
1403*/
1404CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2,
1405 OutputArray dst, InputArray mask = noArray());
1406
1407/** @brief Inverts every bit of an array.
1408
1409The function cv::bitwise_not calculates per-element bit-wise inversion of the input
1410array:
1411\f[\texttt{dst} (I) = \neg \texttt{src} (I)\f]
1412In case of a floating-point input array, its machine-specific bit
1413representation (usually IEEE754-compliant) is used for the operation. In
1414case of multi-channel arrays, each channel is processed independently.
1415@param src input array.
1416@param dst output array that has the same size and type as the input
1417array.
1418@param mask optional operation mask, 8-bit single channel array, that
1419specifies elements of the output array to be changed.
1420*/
1421CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst,
1422 InputArray mask = noArray());
1423
1424/** @brief Calculates the per-element absolute difference between two arrays or between an array and a scalar.
1425
1426The function cv::absdiff calculates:
1427* Absolute difference between two arrays when they have the same
1428 size and type:
1429 \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\f]
1430* Absolute difference between an array and a scalar when the second
1431 array is constructed from Scalar or has as many elements as the
1432 number of channels in `src1`:
1433 \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2} |)\f]
1434* Absolute difference between a scalar and an array when the first
1435 array is constructed from Scalar or has as many elements as the
1436 number of channels in `src2`:
1437 \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1} - \texttt{src2}(I) |)\f]
1438 where I is a multi-dimensional index of array elements. In case of
1439 multi-channel arrays, each channel is processed independently.
1440@note Saturation is not applied when the arrays have the depth CV_32S.
1441You may even get a negative value in the case of overflow.
1442@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array.
1443`absdiff(src,X)` means `absdiff(src,(X,X,X,X))`.
1444`absdiff(src,(X,))` means `absdiff(src,(X,0,0,0))`.
1445@param src1 first input array or a scalar.
1446@param src2 second input array or a scalar.
1447@param dst output array that has the same size and type as input arrays.
1448@sa cv::abs(const Mat&)
1449*/
1450CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst);
1451
1452/** @brief This is an overloaded member function, provided for convenience (python)
1453Copies the matrix to another one.
1454When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data.
1455@param src source matrix.
1456@param dst Destination matrix. If it does not have a proper size or type before the operation, it is
1457reallocated.
1458@param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix
1459elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels.
1460*/
1461
1462void CV_EXPORTS_W copyTo(InputArray src, OutputArray dst, InputArray mask);
1463/** @brief Checks if array elements lie between the elements of two other arrays.
1464
1465The function checks the range as follows:
1466- For every element of a single-channel input array:
1467 \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0\f]
1468- For two-channel arrays:
1469 \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0 \land \texttt{lowerb} (I)_1 \leq \texttt{src} (I)_1 \leq \texttt{upperb} (I)_1\f]
1470- and so forth.
1471
1472That is, dst (I) is set to 255 (all 1 -bits) if src (I) is within the
1473specified 1D, 2D, 3D, ... box and 0 otherwise.
1474
1475When the lower and/or upper boundary parameters are scalars, the indexes
1476(I) at lowerb and upperb in the above formulas should be omitted.
1477@param src first input array.
1478@param lowerb inclusive lower boundary array or a scalar.
1479@param upperb inclusive upper boundary array or a scalar.
1480@param dst output array of the same size as src and CV_8U type.
1481*/
1482CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb,
1483 InputArray upperb, OutputArray dst);
1484
1485/** @brief Performs the per-element comparison of two arrays or an array and scalar value.
1486
1487The function compares:
1488* Elements of two arrays when src1 and src2 have the same size:
1489 \f[\texttt{dst} (I) = \texttt{src1} (I) \,\texttt{cmpop}\, \texttt{src2} (I)\f]
1490* Elements of src1 with a scalar src2 when src2 is constructed from
1491 Scalar or has a single element:
1492 \f[\texttt{dst} (I) = \texttt{src1}(I) \,\texttt{cmpop}\, \texttt{src2}\f]
1493* src1 with elements of src2 when src1 is constructed from Scalar or
1494 has a single element:
1495 \f[\texttt{dst} (I) = \texttt{src1} \,\texttt{cmpop}\, \texttt{src2} (I)\f]
1496When the comparison result is true, the corresponding element of output
1497array is set to 255. The comparison operations can be replaced with the
1498equivalent matrix expressions:
1499@code{.cpp}
1500 Mat dst1 = src1 >= src2;
1501 Mat dst2 = src1 < 8;
1502 ...
1503@endcode
1504@param src1 first input array or a scalar; when it is an array, it must have a single channel.
1505@param src2 second input array or a scalar; when it is an array, it must have a single channel.
1506@param dst output array of type ref CV_8U that has the same size and the same number of channels as
1507 the input arrays.
1508@param cmpop a flag, that specifies correspondence between the arrays (cv::CmpTypes)
1509@sa checkRange, min, max, threshold
1510*/
1511CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop);
1512
1513/** @brief Calculates per-element minimum of two arrays or an array and a scalar.
1514
1515The function cv::min calculates the per-element minimum of two arrays:
1516\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f]
1517or array and a scalar:
1518\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{value} )\f]
1519@param src1 first input array.
1520@param src2 second input array of the same size and type as src1.
1521@param dst output array of the same size and type as src1.
1522@sa max, compare, inRange, minMaxLoc
1523*/
1524CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst);
1525/** @overload
1526needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
1527*/
1528CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst);
1529/** @overload
1530needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
1531*/
1532CV_EXPORTS void min(const UMat& src1, const UMat& src2, UMat& dst);
1533
1534/** @brief Calculates per-element maximum of two arrays or an array and a scalar.
1535
1536The function cv::max calculates the per-element maximum of two arrays:
1537\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f]
1538or array and a scalar:
1539\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{value} )\f]
1540@param src1 first input array.
1541@param src2 second input array of the same size and type as src1 .
1542@param dst output array of the same size and type as src1.
1543@sa min, compare, inRange, minMaxLoc, @ref MatrixExpressions
1544*/
1545CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst);
1546/** @overload
1547needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
1548*/
1549CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst);
1550/** @overload
1551needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
1552*/
1553CV_EXPORTS void max(const UMat& src1, const UMat& src2, UMat& dst);
1554
1555/** @brief Calculates a square root of array elements.
1556
1557The function cv::sqrt calculates a square root of each input array element.
1558In case of multi-channel arrays, each channel is processed
1559independently. The accuracy is approximately the same as of the built-in
1560std::sqrt .
1561@param src input floating-point array.
1562@param dst output array of the same size and type as src.
1563*/
1564CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst);
1565
1566/** @brief Raises every array element to a power.
1567
1568The function cv::pow raises every element of the input array to power :
1569\f[\texttt{dst} (I) = \fork{\texttt{src}(I)^{power}}{if \(\texttt{power}\) is integer}{|\texttt{src}(I)|^{power}}{otherwise}\f]
1570
1571So, for a non-integer power exponent, the absolute values of input array
1572elements are used. However, it is possible to get true values for
1573negative values using some extra operations. In the example below,
1574computing the 5th root of array src shows:
1575@code{.cpp}
1576 Mat mask = src < 0;
1577 pow(src, 1./5, dst);
1578 subtract(Scalar::all(0), dst, dst, mask);
1579@endcode
1580For some values of power, such as integer values, 0.5 and -0.5,
1581specialized faster algorithms are used.
1582
1583Special values (NaN, Inf) are not handled.
1584@param src input array.
1585@param power exponent of power.
1586@param dst output array of the same size and type as src.
1587@sa sqrt, exp, log, cartToPolar, polarToCart
1588*/
1589CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst);
1590
1591/** @brief Calculates the exponent of every array element.
1592
1593The function cv::exp calculates the exponent of every element of the input
1594array:
1595\f[\texttt{dst} [I] = e^{ src(I) }\f]
1596
1597The maximum relative error is about 7e-6 for single-precision input and
1598less than 1e-10 for double-precision input. Currently, the function
1599converts denormalized values to zeros on output. Special values (NaN,
1600Inf) are not handled.
1601@param src input array.
1602@param dst output array of the same size and type as src.
1603@sa log, cartToPolar, polarToCart, phase, pow, sqrt, magnitude
1604*/
1605CV_EXPORTS_W void exp(InputArray src, OutputArray dst);
1606
1607/** @brief Calculates the natural logarithm of every array element.
1608
1609The function cv::log calculates the natural logarithm of every element of the input array:
1610\f[\texttt{dst} (I) = \log (\texttt{src}(I)) \f]
1611
1612Output on zero, negative and special (NaN, Inf) values is undefined.
1613
1614@param src input array.
1615@param dst output array of the same size and type as src .
1616@sa exp, cartToPolar, polarToCart, phase, pow, sqrt, magnitude
1617*/
1618CV_EXPORTS_W void log(InputArray src, OutputArray dst);
1619
1620/** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle.
1621
1622The function cv::polarToCart calculates the Cartesian coordinates of each 2D
1623vector represented by the corresponding elements of magnitude and angle:
1624\f[\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\f]
1625
1626The relative accuracy of the estimated coordinates is about 1e-6.
1627@param magnitude input floating-point array of magnitudes of 2D vectors;
1628it can be an empty matrix (=Mat()), in this case, the function assumes
1629that all the magnitudes are =1; if it is not empty, it must have the
1630same size and type as angle.
1631@param angle input floating-point array of angles of 2D vectors.
1632@param x output array of x-coordinates of 2D vectors; it has the same
1633size and type as angle.
1634@param y output array of y-coordinates of 2D vectors; it has the same
1635size and type as angle.
1636@param angleInDegrees when true, the input angles are measured in
1637degrees, otherwise, they are measured in radians.
1638@sa cartToPolar, magnitude, phase, exp, log, pow, sqrt
1639*/
1640CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle,
1641 OutputArray x, OutputArray y, bool angleInDegrees = false);
1642
1643/** @brief Calculates the magnitude and angle of 2D vectors.
1644
1645The function cv::cartToPolar calculates either the magnitude, angle, or both
1646for every 2D vector (x(I),y(I)):
1647\f[\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\f]
1648
1649The angles are calculated with accuracy about 0.3 degrees. For the point
1650(0,0), the angle is set to 0.
1651@param x array of x-coordinates; this must be a single-precision or
1652double-precision floating-point array.
1653@param y array of y-coordinates, that must have the same size and same type as x.
1654@param magnitude output array of magnitudes of the same size and type as x.
1655@param angle output array of angles that has the same size and type as
1656x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees).
1657@param angleInDegrees a flag, indicating whether the angles are measured
1658in radians (which is by default), or in degrees.
1659@sa Sobel, Scharr
1660*/
1661CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y,
1662 OutputArray magnitude, OutputArray angle,
1663 bool angleInDegrees = false);
1664
1665/** @brief Calculates the rotation angle of 2D vectors.
1666
1667The function cv::phase calculates the rotation angle of each 2D vector that
1668is formed from the corresponding elements of x and y :
1669\f[\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f]
1670
1671The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 ,
1672the corresponding angle(I) is set to 0.
1673@param x input floating-point array of x-coordinates of 2D vectors.
1674@param y input array of y-coordinates of 2D vectors; it must have the
1675same size and the same type as x.
1676@param angle output array of vector angles; it has the same size and
1677same type as x .
1678@param angleInDegrees when true, the function calculates the angle in
1679degrees, otherwise, they are measured in radians.
1680*/
1681CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle,
1682 bool angleInDegrees = false);
1683
1684/** @brief Calculates the magnitude of 2D vectors.
1685
1686The function cv::magnitude calculates the magnitude of 2D vectors formed
1687from the corresponding elements of x and y arrays:
1688\f[\texttt{dst} (I) = \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}\f]
1689@param x floating-point array of x-coordinates of the vectors.
1690@param y floating-point array of y-coordinates of the vectors; it must
1691have the same size as x.
1692@param magnitude output array of the same size and type as x.
1693@sa cartToPolar, polarToCart, phase, sqrt
1694*/
1695CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude);
1696
1697/** @brief Checks every element of an input array for invalid values.
1698
1699The function cv::checkRange checks that every array element is neither NaN nor infinite. When minVal \>
1700-DBL_MAX and maxVal \< DBL_MAX, the function also checks that each value is between minVal and
1701maxVal. In case of multi-channel arrays, each channel is processed independently. If some values
1702are out of range, position of the first outlier is stored in pos (when pos != NULL). Then, the
1703function either returns false (when quiet=true) or throws an exception.
1704@param a input array.
1705@param quiet a flag, indicating whether the functions quietly return false when the array elements
1706are out of range or they throw an exception.
1707@param pos optional output parameter, when not NULL, must be a pointer to array of src.dims
1708elements.
1709@param minVal inclusive lower boundary of valid values range.
1710@param maxVal exclusive upper boundary of valid values range.
1711*/
1712CV_EXPORTS_W bool checkRange(InputArray a, bool quiet = true, CV_OUT Point* pos = 0,
1713 double minVal = -DBL_MAX, double maxVal = DBL_MAX);
1714
1715/** @brief Replaces NaNs by given number
1716@param a input/output matrix (CV_32F type).
1717@param val value to convert the NaNs
1718*/
1719CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0);
1720
1721/** @brief Performs generalized matrix multiplication.
1722
1723The function cv::gemm performs generalized matrix multiplication similar to the
1724gemm functions in BLAS level 3. For example,
1725`gemm(src1, src2, alpha, src3, beta, dst, GEMM_1_T + GEMM_3_T)`
1726corresponds to
1727\f[\texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T\f]
1728
1729In case of complex (two-channel) data, performed a complex matrix
1730multiplication.
1731
1732The function can be replaced with a matrix expression. For example, the
1733above call can be replaced with:
1734@code{.cpp}
1735 dst = alpha*src1.t()*src2 + beta*src3.t();
1736@endcode
1737@param src1 first multiplied input matrix that could be real(CV_32FC1,
1738CV_64FC1) or complex(CV_32FC2, CV_64FC2).
1739@param src2 second multiplied input matrix of the same type as src1.
1740@param alpha weight of the matrix product.
1741@param src3 third optional delta matrix added to the matrix product; it
1742should have the same type as src1 and src2.
1743@param beta weight of src3.
1744@param dst output matrix; it has the proper size and the same type as
1745input matrices.
1746@param flags operation flags (cv::GemmFlags)
1747@sa mulTransposed, transform
1748*/
1749CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha,
1750 InputArray src3, double beta, OutputArray dst, int flags = 0);
1751
1752/** @brief Calculates the product of a matrix and its transposition.
1753
1754The function cv::mulTransposed calculates the product of src and its
1755transposition:
1756\f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} )^T ( \texttt{src} - \texttt{delta} )\f]
1757if aTa=true, and
1758\f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} ) ( \texttt{src} - \texttt{delta} )^T\f]
1759otherwise. The function is used to calculate the covariance matrix. With
1760zero delta, it can be used as a faster substitute for general matrix
1761product A\*B when B=A'
1762@param src input single-channel matrix. Note that unlike gemm, the
1763function can multiply not only floating-point matrices.
1764@param dst output square matrix.
1765@param aTa Flag specifying the multiplication ordering. See the
1766description below.
1767@param delta Optional delta matrix subtracted from src before the
1768multiplication. When the matrix is empty ( delta=noArray() ), it is
1769assumed to be zero, that is, nothing is subtracted. If it has the same
1770size as src, it is simply subtracted. Otherwise, it is "repeated" (see
1771repeat ) to cover the full src and then subtracted. Type of the delta
1772matrix, when it is not empty, must be the same as the type of created
1773output matrix. See the dtype parameter description below.
1774@param scale Optional scale factor for the matrix product.
1775@param dtype Optional type of the output matrix. When it is negative,
1776the output matrix will have the same type as src . Otherwise, it will be
1777type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F .
1778@sa calcCovarMatrix, gemm, repeat, reduce
1779*/
1780CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa,
1781 InputArray delta = noArray(),
1782 double scale = 1, int dtype = -1 );
1783
1784/** @brief Transposes a matrix.
1785
1786The function cv::transpose transposes the matrix src :
1787\f[\texttt{dst} (i,j) = \texttt{src} (j,i)\f]
1788@note No complex conjugation is done in case of a complex matrix. It
1789should be done separately if needed.
1790@param src input array.
1791@param dst output array of the same type as src.
1792*/
1793CV_EXPORTS_W void transpose(InputArray src, OutputArray dst);
1794
1795/** @brief Transpose for n-dimensional matrices.
1796 *
1797 * @note Input should be continuous single-channel matrix.
1798 * @param src input array.
1799 * @param order a permutation of [0,1,..,N-1] where N is the number of axes of src.
1800 * The i'th axis of dst will correspond to the axis numbered order[i] of the input.
1801 * @param dst output array of the same type as src.
1802 */
1803CV_EXPORTS_W void transposeND(InputArray src, const std::vector<int>& order, OutputArray dst);
1804
1805/** @brief Performs the matrix transformation of every array element.
1806
1807The function cv::transform performs the matrix transformation of every
1808element of the array src and stores the results in dst :
1809\f[\texttt{dst} (I) = \texttt{m} \cdot \texttt{src} (I)\f]
1810(when m.cols=src.channels() ), or
1811\f[\texttt{dst} (I) = \texttt{m} \cdot [ \texttt{src} (I); 1]\f]
1812(when m.cols=src.channels()+1 )
1813
1814Every element of the N -channel array src is interpreted as N -element
1815vector that is transformed using the M x N or M x (N+1) matrix m to
1816M-element vector - the corresponding element of the output array dst .
1817
1818The function may be used for geometrical transformation of
1819N -dimensional points, arbitrary linear color space transformation (such
1820as various kinds of RGB to YUV transforms), shuffling the image
1821channels, and so forth.
1822@param src input array that must have as many channels (1 to 4) as
1823m.cols or m.cols-1.
1824@param dst output array of the same size and depth as src; it has as
1825many channels as m.rows.
1826@param m transformation 2x2 or 2x3 floating-point matrix.
1827@sa perspectiveTransform, getAffineTransform, estimateAffine2D, warpAffine, warpPerspective
1828*/
1829CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m );
1830
1831/** @brief Performs the perspective matrix transformation of vectors.
1832
1833The function cv::perspectiveTransform transforms every element of src by
1834treating it as a 2D or 3D vector, in the following way:
1835\f[(x, y, z) \rightarrow (x'/w, y'/w, z'/w)\f]
1836where
1837\f[(x', y', z', w') = \texttt{mat} \cdot \begin{bmatrix} x & y & z & 1 \end{bmatrix}\f]
1838and
1839\f[w = \fork{w'}{if \(w' \ne 0\)}{\infty}{otherwise}\f]
1840
1841Here a 3D vector transformation is shown. In case of a 2D vector
1842transformation, the z component is omitted.
1843
1844@note The function transforms a sparse set of 2D or 3D vectors. If you
1845want to transform an image using perspective transformation, use
1846warpPerspective . If you have an inverse problem, that is, you want to
1847compute the most probable perspective transformation out of several
1848pairs of corresponding points, you can use getPerspectiveTransform or
1849findHomography .
1850@param src input two-channel or three-channel floating-point array; each
1851element is a 2D/3D vector to be transformed.
1852@param dst output array of the same size and type as src.
1853@param m 3x3 or 4x4 floating-point transformation matrix.
1854@sa transform, warpPerspective, getPerspectiveTransform, findHomography
1855*/
1856CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m );
1857
1858/** @brief Copies the lower or the upper half of a square matrix to its another half.
1859
1860The function cv::completeSymm copies the lower or the upper half of a square matrix to
1861its another half. The matrix diagonal remains unchanged:
1862 - \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i > j\f$ if
1863 lowerToUpper=false
1864 - \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i < j\f$ if
1865 lowerToUpper=true
1866
1867@param m input-output floating-point square matrix.
1868@param lowerToUpper operation flag; if true, the lower half is copied to
1869the upper half. Otherwise, the upper half is copied to the lower half.
1870@sa flip, transpose
1871*/
1872CV_EXPORTS_W void completeSymm(InputOutputArray m, bool lowerToUpper = false);
1873
1874/** @brief Initializes a scaled identity matrix.
1875
1876The function cv::setIdentity initializes a scaled identity matrix:
1877\f[\texttt{mtx} (i,j)= \fork{\texttt{value}}{ if \(i=j\)}{0}{otherwise}\f]
1878
1879The function can also be emulated using the matrix initializers and the
1880matrix expressions:
1881@code
1882 Mat A = Mat::eye(4, 3, CV_32F)*5;
1883 // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]]
1884@endcode
1885@param mtx matrix to initialize (not necessarily square).
1886@param s value to assign to diagonal elements.
1887@sa Mat::zeros, Mat::ones, Mat::setTo, Mat::operator=
1888*/
1889CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s = Scalar(1));
1890
1891/** @brief Returns the determinant of a square floating-point matrix.
1892
1893The function cv::determinant calculates and returns the determinant of the
1894specified matrix. For small matrices ( mtx.cols=mtx.rows\<=3 ), the
1895direct method is used. For larger matrices, the function uses LU
1896factorization with partial pivoting.
1897
1898For symmetric positively-determined matrices, it is also possible to use
1899eigen decomposition to calculate the determinant.
1900@param mtx input matrix that must have CV_32FC1 or CV_64FC1 type and
1901square size.
1902@sa trace, invert, solve, eigen, @ref MatrixExpressions
1903*/
1904CV_EXPORTS_W double determinant(InputArray mtx);
1905
1906/** @brief Returns the trace of a matrix.
1907
1908The function cv::trace returns the sum of the diagonal elements of the
1909matrix mtx .
1910\f[\mathrm{tr} ( \texttt{mtx} ) = \sum _i \texttt{mtx} (i,i)\f]
1911@param mtx input matrix.
1912*/
1913CV_EXPORTS_W Scalar trace(InputArray mtx);
1914
1915/** @brief Finds the inverse or pseudo-inverse of a matrix.
1916
1917The function cv::invert inverts the matrix src and stores the result in dst
1918. When the matrix src is singular or non-square, the function calculates
1919the pseudo-inverse matrix (the dst matrix) so that norm(src\*dst - I) is
1920minimal, where I is an identity matrix.
1921
1922In case of the #DECOMP_LU method, the function returns non-zero value if
1923the inverse has been successfully calculated and 0 if src is singular.
1924
1925In case of the #DECOMP_SVD method, the function returns the inverse
1926condition number of src (the ratio of the smallest singular value to the
1927largest singular value) and 0 if src is singular. The SVD method
1928calculates a pseudo-inverse matrix if src is singular.
1929
1930Similarly to #DECOMP_LU, the method #DECOMP_CHOLESKY works only with
1931non-singular square matrices that should also be symmetrical and
1932positively defined. In this case, the function stores the inverted
1933matrix in dst and returns non-zero. Otherwise, it returns 0.
1934
1935@param src input floating-point M x N matrix.
1936@param dst output matrix of N x M size and the same type as src.
1937@param flags inversion method (cv::DecompTypes)
1938@sa solve, SVD
1939*/
1940CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags = DECOMP_LU);
1941
1942/** @brief Solves one or more linear systems or least-squares problems.
1943
1944The function cv::solve solves a linear system or least-squares problem (the
1945latter is possible with SVD or QR methods, or by specifying the flag
1946#DECOMP_NORMAL ):
1947\f[\texttt{dst} = \arg \min _X \| \texttt{src1} \cdot \texttt{X} - \texttt{src2} \|\f]
1948
1949If #DECOMP_LU or #DECOMP_CHOLESKY method is used, the function returns 1
1950if src1 (or \f$\texttt{src1}^T\texttt{src1}\f$ ) is non-singular. Otherwise,
1951it returns 0. In the latter case, dst is not valid. Other methods find a
1952pseudo-solution in case of a singular left-hand side part.
1953
1954@note If you want to find a unity-norm solution of an under-defined
1955singular system \f$\texttt{src1}\cdot\texttt{dst}=0\f$ , the function solve
1956will not do the work. Use SVD::solveZ instead.
1957
1958@param src1 input matrix on the left-hand side of the system.
1959@param src2 input matrix on the right-hand side of the system.
1960@param dst output solution.
1961@param flags solution (matrix inversion) method (#DecompTypes)
1962@sa invert, SVD, eigen
1963*/
1964CV_EXPORTS_W bool solve(InputArray src1, InputArray src2,
1965 OutputArray dst, int flags = DECOMP_LU);
1966
1967/** @brief Sorts each row or each column of a matrix.
1968
1969The function cv::sort sorts each matrix row or each matrix column in
1970ascending or descending order. So you should pass two operation flags to
1971get desired behaviour. If you want to sort matrix rows or columns
1972lexicographically, you can use STL std::sort generic function with the
1973proper comparison predicate.
1974
1975@param src input single-channel array.
1976@param dst output array of the same size and type as src.
1977@param flags operation flags, a combination of #SortFlags
1978@sa sortIdx, randShuffle
1979*/
1980CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags);
1981
1982/** @brief Sorts each row or each column of a matrix.
1983
1984The function cv::sortIdx sorts each matrix row or each matrix column in the
1985ascending or descending order. So you should pass two operation flags to
1986get desired behaviour. Instead of reordering the elements themselves, it
1987stores the indices of sorted elements in the output array. For example:
1988@code
1989 Mat A = Mat::eye(3,3,CV_32F), B;
1990 sortIdx(A, B, SORT_EVERY_ROW + SORT_ASCENDING);
1991 // B will probably contain
1992 // (because of equal elements in A some permutations are possible):
1993 // [[1, 2, 0], [0, 2, 1], [0, 1, 2]]
1994@endcode
1995@param src input single-channel array.
1996@param dst output integer array of the same size as src.
1997@param flags operation flags that could be a combination of cv::SortFlags
1998@sa sort, randShuffle
1999*/
2000CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags);
2001
2002/** @brief Finds the real roots of a cubic equation.
2003
2004The function solveCubic finds the real roots of a cubic equation:
2005- if coeffs is a 4-element vector:
2006\f[\texttt{coeffs} [0] x^3 + \texttt{coeffs} [1] x^2 + \texttt{coeffs} [2] x + \texttt{coeffs} [3] = 0\f]
2007- if coeffs is a 3-element vector:
2008\f[x^3 + \texttt{coeffs} [0] x^2 + \texttt{coeffs} [1] x + \texttt{coeffs} [2] = 0\f]
2009
2010The roots are stored in the roots array.
2011@param coeffs equation coefficients, an array of 3 or 4 elements.
2012@param roots output array of real roots that has 0, 1, 2 or 3 elements.
2013@return number of real roots. It can be -1 (all real numbers), 0, 1, 2 or 3.
2014*/
2015CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots);
2016
2017/** @brief Finds the real or complex roots of a polynomial equation.
2018
2019The function cv::solvePoly finds real and complex roots of a polynomial equation:
2020\f[\texttt{coeffs} [n] x^{n} + \texttt{coeffs} [n-1] x^{n-1} + ... + \texttt{coeffs} [1] x + \texttt{coeffs} [0] = 0\f]
2021@param coeffs array of polynomial coefficients.
2022@param roots output (complex) array of roots.
2023@param maxIters maximum number of iterations the algorithm does.
2024*/
2025CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters = 300);
2026
2027/** @brief Calculates eigenvalues and eigenvectors of a symmetric matrix.
2028
2029The function cv::eigen calculates just eigenvalues, or eigenvalues and eigenvectors of the symmetric
2030matrix src:
2031@code
2032 src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t()
2033@endcode
2034
2035@note Use cv::eigenNonSymmetric for calculation of real eigenvalues and eigenvectors of non-symmetric matrix.
2036
2037@param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical
2038(src ^T^ == src).
2039@param eigenvalues output vector of eigenvalues of the same type as src; the eigenvalues are stored
2040in the descending order.
2041@param eigenvectors output matrix of eigenvectors; it has the same size and type as src; the
2042eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding
2043eigenvalues.
2044@sa eigenNonSymmetric, completeSymm, PCA
2045*/
2046CV_EXPORTS_W bool eigen(InputArray src, OutputArray eigenvalues,
2047 OutputArray eigenvectors = noArray());
2048
2049/** @brief Calculates eigenvalues and eigenvectors of a non-symmetric matrix (real eigenvalues only).
2050
2051@note Assumes real eigenvalues.
2052
2053The function calculates eigenvalues and eigenvectors (optional) of the square matrix src:
2054@code
2055 src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t()
2056@endcode
2057
2058@param src input matrix (CV_32FC1 or CV_64FC1 type).
2059@param eigenvalues output vector of eigenvalues (type is the same type as src).
2060@param eigenvectors output matrix of eigenvectors (type is the same type as src). The eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding eigenvalues.
2061@sa eigen
2062*/
2063CV_EXPORTS_W void eigenNonSymmetric(InputArray src, OutputArray eigenvalues,
2064 OutputArray eigenvectors);
2065
2066/** @brief Calculates the covariance matrix of a set of vectors.
2067
2068The function cv::calcCovarMatrix calculates the covariance matrix and, optionally, the mean vector of
2069the set of input vectors.
2070@param samples samples stored as separate matrices
2071@param nsamples number of samples
2072@param covar output covariance matrix of the type ctype and square size.
2073@param mean input or output (depending on the flags) array as the average value of the input vectors.
2074@param flags operation flags as a combination of #CovarFlags
2075@param ctype type of the matrixl; it equals 'CV_64F' by default.
2076@sa PCA, mulTransposed, Mahalanobis
2077@todo InputArrayOfArrays
2078*/
2079CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean,
2080 int flags, int ctype = CV_64F);
2081
2082/** @overload
2083@note use #COVAR_ROWS or #COVAR_COLS flag
2084@param samples samples stored as rows/columns of a single matrix.
2085@param covar output covariance matrix of the type ctype and square size.
2086@param mean input or output (depending on the flags) array as the average value of the input vectors.
2087@param flags operation flags as a combination of #CovarFlags
2088@param ctype type of the matrixl; it equals 'CV_64F' by default.
2089*/
2090CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar,
2091 InputOutputArray mean, int flags, int ctype = CV_64F);
2092
2093/** wrap PCA::operator() */
2094CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean,
2095 OutputArray eigenvectors, int maxComponents = 0);
2096
2097/** wrap PCA::operator() and add eigenvalues output parameter */
2098CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean,
2099 OutputArray eigenvectors, OutputArray eigenvalues,
2100 int maxComponents = 0);
2101
2102/** wrap PCA::operator() */
2103CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean,
2104 OutputArray eigenvectors, double retainedVariance);
2105
2106/** wrap PCA::operator() and add eigenvalues output parameter */
2107CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean,
2108 OutputArray eigenvectors, OutputArray eigenvalues,
2109 double retainedVariance);
2110
2111/** wrap PCA::project */
2112CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean,
2113 InputArray eigenvectors, OutputArray result);
2114
2115/** wrap PCA::backProject */
2116CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean,
2117 InputArray eigenvectors, OutputArray result);
2118
2119/** wrap SVD::compute */
2120CV_EXPORTS_W void SVDecomp( InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags = 0 );
2121
2122/** wrap SVD::backSubst */
2123CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt,
2124 InputArray rhs, OutputArray dst );
2125
2126/** @brief Calculates the Mahalanobis distance between two vectors.
2127
2128The function cv::Mahalanobis calculates and returns the weighted distance between two vectors:
2129\f[d( \texttt{vec1} , \texttt{vec2} )= \sqrt{\sum_{i,j}{\texttt{icovar(i,j)}\cdot(\texttt{vec1}(I)-\texttt{vec2}(I))\cdot(\texttt{vec1(j)}-\texttt{vec2(j)})} }\f]
2130The covariance matrix may be calculated using the #calcCovarMatrix function and then inverted using
2131the invert function (preferably using the #DECOMP_SVD method, as the most accurate).
2132@param v1 first 1D input vector.
2133@param v2 second 1D input vector.
2134@param icovar inverse covariance matrix.
2135*/
2136CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar);
2137
2138/** @brief Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array.
2139
2140The function cv::dft performs one of the following:
2141- Forward the Fourier transform of a 1D vector of N elements:
2142 \f[Y = F^{(N)} \cdot X,\f]
2143 where \f$F^{(N)}_{jk}=\exp(-2\pi i j k/N)\f$ and \f$i=\sqrt{-1}\f$
2144- Inverse the Fourier transform of a 1D vector of N elements:
2145 \f[\begin{array}{l} X'= \left (F^{(N)} \right )^{-1} \cdot Y = \left (F^{(N)} \right )^* \cdot y \\ X = (1/N) \cdot X, \end{array}\f]
2146 where \f$F^*=\left(\textrm{Re}(F^{(N)})-\textrm{Im}(F^{(N)})\right)^T\f$
2147- Forward the 2D Fourier transform of a M x N matrix:
2148 \f[Y = F^{(M)} \cdot X \cdot F^{(N)}\f]
2149- Inverse the 2D Fourier transform of a M x N matrix:
2150 \f[\begin{array}{l} X'= \left (F^{(M)} \right )^* \cdot Y \cdot \left (F^{(N)} \right )^* \\ X = \frac{1}{M \cdot N} \cdot X' \end{array}\f]
2151
2152In case of real (single-channel) data, the output spectrum of the forward Fourier transform or input
2153spectrum of the inverse Fourier transform can be represented in a packed format called *CCS*
2154(complex-conjugate-symmetrical). It was borrowed from IPL (Intel\* Image Processing Library). Here
2155is how 2D *CCS* spectrum looks:
2156\f[\begin{bmatrix} Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\ Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\ Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\ \hdotsfor{9} \\ Re Y_{M/2-1,0} & Re Y_{M-3,1} & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\ Im Y_{M/2-1,0} & Re Y_{M-2,1} & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\ Re Y_{M/2,0} & Re Y_{M-1,1} & Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2} \end{bmatrix}\f]
2157
2158In case of 1D transform of a real vector, the output looks like the first row of the matrix above.
2159
2160So, the function chooses an operation mode depending on the flags and size of the input array:
2161- If #DFT_ROWS is set or the input array has a single row or single column, the function
2162 performs a 1D forward or inverse transform of each row of a matrix when #DFT_ROWS is set.
2163 Otherwise, it performs a 2D transform.
2164- If the input array is real and #DFT_INVERSE is not set, the function performs a forward 1D or
2165 2D transform:
2166 - When #DFT_COMPLEX_OUTPUT is set, the output is a complex matrix of the same size as
2167 input.
2168 - When #DFT_COMPLEX_OUTPUT is not set, the output is a real matrix of the same size as
2169 input. In case of 2D transform, it uses the packed format as shown above. In case of a
2170 single 1D transform, it looks like the first row of the matrix above. In case of
2171 multiple 1D transforms (when using the #DFT_ROWS flag), each row of the output matrix
2172 looks like the first row of the matrix above.
2173- If the input array is complex and either #DFT_INVERSE or #DFT_REAL_OUTPUT are not set, the
2174 output is a complex array of the same size as input. The function performs a forward or
2175 inverse 1D or 2D transform of the whole input array or each row of the input array
2176 independently, depending on the flags DFT_INVERSE and DFT_ROWS.
2177- When #DFT_INVERSE is set and the input array is real, or it is complex but #DFT_REAL_OUTPUT
2178 is set, the output is a real array of the same size as input. The function performs a 1D or 2D
2179 inverse transformation of the whole input array or each individual row, depending on the flags
2180 #DFT_INVERSE and #DFT_ROWS.
2181
2182If #DFT_SCALE is set, the scaling is done after the transformation.
2183
2184Unlike dct, the function supports arrays of arbitrary size. But only those arrays are processed
2185efficiently, whose sizes can be factorized in a product of small prime numbers (2, 3, and 5 in the
2186current implementation). Such an efficient DFT size can be calculated using the getOptimalDFTSize
2187method.
2188
2189The sample below illustrates how to calculate a DFT-based convolution of two 2D real arrays:
2190@code
2191 void convolveDFT(InputArray A, InputArray B, OutputArray C)
2192 {
2193 // reallocate the output array if needed
2194 C.create(abs(A.rows - B.rows)+1, abs(A.cols - B.cols)+1, A.type());
2195 Size dftSize;
2196 // calculate the size of DFT transform
2197 dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1);
2198 dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1);
2199
2200 // allocate temporary buffers and initialize them with 0's
2201 Mat tempA(dftSize, A.type(), Scalar::all(0));
2202 Mat tempB(dftSize, B.type(), Scalar::all(0));
2203
2204 // copy A and B to the top-left corners of tempA and tempB, respectively
2205 Mat roiA(tempA, Rect(0,0,A.cols,A.rows));
2206 A.copyTo(roiA);
2207 Mat roiB(tempB, Rect(0,0,B.cols,B.rows));
2208 B.copyTo(roiB);
2209
2210 // now transform the padded A & B in-place;
2211 // use "nonzeroRows" hint for faster processing
2212 dft(tempA, tempA, 0, A.rows);
2213 dft(tempB, tempB, 0, B.rows);
2214
2215 // multiply the spectrums;
2216 // the function handles packed spectrum representations well
2217 mulSpectrums(tempA, tempB, tempA);
2218
2219 // transform the product back from the frequency domain.
2220 // Even though all the result rows will be non-zero,
2221 // you need only the first C.rows of them, and thus you
2222 // pass nonzeroRows == C.rows
2223 dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows);
2224
2225 // now copy the result back to C.
2226 tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C);
2227
2228 // all the temporary buffers will be deallocated automatically
2229 }
2230@endcode
2231To optimize this sample, consider the following approaches:
2232- Since nonzeroRows != 0 is passed to the forward transform calls and since A and B are copied to
2233 the top-left corners of tempA and tempB, respectively, it is not necessary to clear the whole
2234 tempA and tempB. It is only necessary to clear the tempA.cols - A.cols ( tempB.cols - B.cols)
2235 rightmost columns of the matrices.
2236- This DFT-based convolution does not have to be applied to the whole big arrays, especially if B
2237 is significantly smaller than A or vice versa. Instead, you can calculate convolution by parts.
2238 To do this, you need to split the output array C into multiple tiles. For each tile, estimate
2239 which parts of A and B are required to calculate convolution in this tile. If the tiles in C are
2240 too small, the speed will decrease a lot because of repeated work. In the ultimate case, when
2241 each tile in C is a single pixel, the algorithm becomes equivalent to the naive convolution
2242 algorithm. If the tiles are too big, the temporary arrays tempA and tempB become too big and
2243 there is also a slowdown because of bad cache locality. So, there is an optimal tile size
2244 somewhere in the middle.
2245- If different tiles in C can be calculated in parallel and, thus, the convolution is done by
2246 parts, the loop can be threaded.
2247
2248All of the above improvements have been implemented in #matchTemplate and #filter2D . Therefore, by
2249using them, you can get the performance even better than with the above theoretically optimal
2250implementation. Though, those two functions actually calculate cross-correlation, not convolution,
2251so you need to "flip" the second convolution operand B vertically and horizontally using flip .
2252@note
2253- An example using the discrete fourier transform can be found at
2254 opencv_source_code/samples/cpp/dft.cpp
2255- (Python) An example using the dft functionality to perform Wiener deconvolution can be found
2256 at opencv_source/samples/python/deconvolution.py
2257- (Python) An example rearranging the quadrants of a Fourier image can be found at
2258 opencv_source/samples/python/dft.py
2259@param src input array that could be real or complex.
2260@param dst output array whose size and type depends on the flags .
2261@param flags transformation flags, representing a combination of the #DftFlags
2262@param nonzeroRows when the parameter is not zero, the function assumes that only the first
2263nonzeroRows rows of the input array (#DFT_INVERSE is not set) or only the first nonzeroRows of the
2264output array (#DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the
2265rows more efficiently and save some time; this technique is very useful for calculating array
2266cross-correlation or convolution using DFT.
2267@sa dct, getOptimalDFTSize, mulSpectrums, filter2D, matchTemplate, flip, cartToPolar,
2268magnitude, phase
2269*/
2270CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0);
2271
2272/** @brief Calculates the inverse Discrete Fourier Transform of a 1D or 2D array.
2273
2274idft(src, dst, flags) is equivalent to dft(src, dst, flags | #DFT_INVERSE) .
2275@note None of dft and idft scales the result by default. So, you should pass #DFT_SCALE to one of
2276dft or idft explicitly to make these transforms mutually inverse.
2277@sa dft, dct, idct, mulSpectrums, getOptimalDFTSize
2278@param src input floating-point real or complex array.
2279@param dst output array whose size and type depend on the flags.
2280@param flags operation flags (see dft and #DftFlags).
2281@param nonzeroRows number of dst rows to process; the rest of the rows have undefined content (see
2282the convolution sample in dft description.
2283*/
2284CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0);
2285
2286/** @brief Performs a forward or inverse discrete Cosine transform of 1D or 2D array.
2287
2288The function cv::dct performs a forward or inverse discrete Cosine transform (DCT) of a 1D or 2D
2289floating-point array:
2290- Forward Cosine transform of a 1D vector of N elements:
2291 \f[Y = C^{(N)} \cdot X\f]
2292 where
2293 \f[C^{(N)}_{jk}= \sqrt{\alpha_j/N} \cos \left ( \frac{\pi(2k+1)j}{2N} \right )\f]
2294 and
2295 \f$\alpha_0=1\f$, \f$\alpha_j=2\f$ for *j \> 0*.
2296- Inverse Cosine transform of a 1D vector of N elements:
2297 \f[X = \left (C^{(N)} \right )^{-1} \cdot Y = \left (C^{(N)} \right )^T \cdot Y\f]
2298 (since \f$C^{(N)}\f$ is an orthogonal matrix, \f$C^{(N)} \cdot \left(C^{(N)}\right)^T = I\f$ )
2299- Forward 2D Cosine transform of M x N matrix:
2300 \f[Y = C^{(N)} \cdot X \cdot \left (C^{(N)} \right )^T\f]
2301- Inverse 2D Cosine transform of M x N matrix:
2302 \f[X = \left (C^{(N)} \right )^T \cdot X \cdot C^{(N)}\f]
2303
2304The function chooses the mode of operation by looking at the flags and size of the input array:
2305- If (flags & #DCT_INVERSE) == 0, the function does a forward 1D or 2D transform. Otherwise, it
2306 is an inverse 1D or 2D transform.
2307- If (flags & #DCT_ROWS) != 0, the function performs a 1D transform of each row.
2308- If the array is a single column or a single row, the function performs a 1D transform.
2309- If none of the above is true, the function performs a 2D transform.
2310
2311@note Currently dct supports even-size arrays (2, 4, 6 ...). For data analysis and approximation, you
2312can pad the array when necessary.
2313Also, the function performance depends very much, and not monotonically, on the array size (see
2314getOptimalDFTSize ). In the current implementation DCT of a vector of size N is calculated via DFT
2315of a vector of size N/2 . Thus, the optimal DCT size N1 \>= N can be calculated as:
2316@code
2317 size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); }
2318 N1 = getOptimalDCTSize(N);
2319@endcode
2320@param src input floating-point array.
2321@param dst output array of the same size and type as src .
2322@param flags transformation flags as a combination of cv::DftFlags (DCT_*)
2323@sa dft, getOptimalDFTSize, idct
2324*/
2325CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags = 0);
2326
2327/** @brief Calculates the inverse Discrete Cosine Transform of a 1D or 2D array.
2328
2329idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE).
2330@param src input floating-point single-channel array.
2331@param dst output array of the same size and type as src.
2332@param flags operation flags.
2333@sa dct, dft, idft, getOptimalDFTSize
2334*/
2335CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags = 0);
2336
2337/** @brief Performs the per-element multiplication of two Fourier spectrums.
2338
2339The function cv::mulSpectrums performs the per-element multiplication of the two CCS-packed or complex
2340matrices that are results of a real or complex Fourier transform.
2341
2342The function, together with dft and idft, may be used to calculate convolution (pass conjB=false )
2343or correlation (pass conjB=true ) of two arrays rapidly. When the arrays are complex, they are
2344simply multiplied (per element) with an optional conjugation of the second-array elements. When the
2345arrays are real, they are assumed to be CCS-packed (see dft for details).
2346@param a first input array.
2347@param b second input array of the same size and type as src1 .
2348@param c output array of the same size and type as src1 .
2349@param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that
2350each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value.
2351@param conjB optional flag that conjugates the second input array before the multiplication (true)
2352or not (false).
2353*/
2354CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c,
2355 int flags, bool conjB = false);
2356
2357/** @brief Returns the optimal DFT size for a given vector size.
2358
2359DFT performance is not a monotonic function of a vector size. Therefore, when you calculate
2360convolution of two arrays or perform the spectral analysis of an array, it usually makes sense to
2361pad the input data with zeros to get a bit larger array that can be transformed much faster than the
2362original one. Arrays whose size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process.
2363Though, the arrays whose size is a product of 2's, 3's, and 5's (for example, 300 = 5\*5\*3\*2\*2)
2364are also processed quite efficiently.
2365
2366The function cv::getOptimalDFTSize returns the minimum number N that is greater than or equal to vecsize
2367so that the DFT of a vector of size N can be processed efficiently. In the current implementation N
2368= 2 ^p^ \* 3 ^q^ \* 5 ^r^ for some integer p, q, r.
2369
2370The function returns a negative number if vecsize is too large (very close to INT_MAX ).
2371
2372While the function cannot be used directly to estimate the optimal vector size for DCT transform
2373(since the current DCT implementation supports only even-size vectors), it can be easily processed
2374as getOptimalDFTSize((vecsize+1)/2)\*2.
2375@param vecsize vector size.
2376@sa dft, dct, idft, idct, mulSpectrums
2377*/
2378CV_EXPORTS_W int getOptimalDFTSize(int vecsize);
2379
2380/** @brief Returns the default random number generator.
2381
2382The function cv::theRNG returns the default random number generator. For each thread, there is a
2383separate random number generator, so you can use the function safely in multi-thread environments.
2384If you just need to get a single random number using this generator or initialize an array, you can
2385use randu or randn instead. But if you are going to generate many random numbers inside a loop, it
2386is much faster to use this function to retrieve the generator and then use RNG::operator _Tp() .
2387@sa RNG, randu, randn
2388*/
2389CV_EXPORTS RNG& theRNG();
2390
2391/** @brief Sets state of default random number generator.
2392
2393The function cv::setRNGSeed sets state of default random number generator to custom value.
2394@param seed new state for default random number generator
2395@sa RNG, randu, randn
2396*/
2397CV_EXPORTS_W void setRNGSeed(int seed);
2398
2399/** @brief Generates a single uniformly-distributed random number or an array of random numbers.
2400
2401Non-template variant of the function fills the matrix dst with uniformly-distributed
2402random numbers from the specified range:
2403\f[\texttt{low} _c \leq \texttt{dst} (I)_c < \texttt{high} _c\f]
2404@param dst output array of random numbers; the array must be pre-allocated.
2405@param low inclusive lower boundary of the generated random numbers.
2406@param high exclusive upper boundary of the generated random numbers.
2407@sa RNG, randn, theRNG
2408*/
2409CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high);
2410
2411/** @brief Fills the array with normally distributed random numbers.
2412
2413The function cv::randn fills the matrix dst with normally distributed random numbers with the specified
2414mean vector and the standard deviation matrix. The generated random numbers are clipped to fit the
2415value range of the output array data type.
2416@param dst output array of random numbers; the array must be pre-allocated and have 1 to 4 channels.
2417@param mean mean value (expectation) of the generated random numbers.
2418@param stddev standard deviation of the generated random numbers; it can be either a vector (in
2419which case a diagonal standard deviation matrix is assumed) or a square matrix.
2420@sa RNG, randu
2421*/
2422CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev);
2423
2424/** @brief Shuffles the array elements randomly.
2425
2426The function cv::randShuffle shuffles the specified 1D array by randomly choosing pairs of elements and
2427swapping them. The number of such swap operations will be dst.rows\*dst.cols\*iterFactor .
2428@param dst input/output numerical 1D array.
2429@param iterFactor scale factor that determines the number of random swap operations (see the details
2430below).
2431@param rng optional random number generator used for shuffling; if it is zero, theRNG () is used
2432instead.
2433@sa RNG, sort
2434*/
2435CV_EXPORTS_W void randShuffle(InputOutputArray dst, double iterFactor = 1., RNG* rng = 0);
2436
2437/** @brief Principal Component Analysis
2438
2439The class is used to calculate a special basis for a set of vectors. The
2440basis will consist of eigenvectors of the covariance matrix calculated
2441from the input set of vectors. The class %PCA can also transform
2442vectors to/from the new coordinate space defined by the basis. Usually,
2443in this new coordinate system, each vector from the original set (and
2444any linear combination of such vectors) can be quite accurately
2445approximated by taking its first few components, corresponding to the
2446eigenvectors of the largest eigenvalues of the covariance matrix.
2447Geometrically it means that you calculate a projection of the vector to
2448a subspace formed by a few eigenvectors corresponding to the dominant
2449eigenvalues of the covariance matrix. And usually such a projection is
2450very close to the original vector. So, you can represent the original
2451vector from a high-dimensional space with a much shorter vector
2452consisting of the projected vector's coordinates in the subspace. Such a
2453transformation is also known as Karhunen-Loeve Transform, or KLT.
2454See http://en.wikipedia.org/wiki/Principal_component_analysis
2455
2456The sample below is the function that takes two matrices. The first
2457function stores a set of vectors (a row per vector) that is used to
2458calculate PCA. The second function stores another "test" set of vectors
2459(a row per vector). First, these vectors are compressed with PCA, then
2460reconstructed back, and then the reconstruction error norm is computed
2461and printed for each vector. :
2462
2463@code{.cpp}
2464using namespace cv;
2465
2466PCA compressPCA(const Mat& pcaset, int maxComponents,
2467 const Mat& testset, Mat& compressed)
2468{
2469 PCA pca(pcaset, // pass the data
2470 Mat(), // we do not have a pre-computed mean vector,
2471 // so let the PCA engine to compute it
2472 PCA::DATA_AS_ROW, // indicate that the vectors
2473 // are stored as matrix rows
2474 // (use PCA::DATA_AS_COL if the vectors are
2475 // the matrix columns)
2476 maxComponents // specify, how many principal components to retain
2477 );
2478 // if there is no test data, just return the computed basis, ready-to-use
2479 if( !testset.data )
2480 return pca;
2481 CV_Assert( testset.cols == pcaset.cols );
2482
2483 compressed.create(testset.rows, maxComponents, testset.type());
2484
2485 Mat reconstructed;
2486 for( int i = 0; i < testset.rows; i++ )
2487 {
2488 Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed;
2489 // compress the vector, the result will be stored
2490 // in the i-th row of the output matrix
2491 pca.project(vec, coeffs);
2492 // and then reconstruct it
2493 pca.backProject(coeffs, reconstructed);
2494 // and measure the error
2495 printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2));
2496 }
2497 return pca;
2498}
2499@endcode
2500@sa calcCovarMatrix, mulTransposed, SVD, dft, dct
2501*/
2502class CV_EXPORTS PCA
2503{
2504public:
2505 enum Flags { DATA_AS_ROW = 0, //!< indicates that the input samples are stored as matrix rows
2506 DATA_AS_COL = 1, //!< indicates that the input samples are stored as matrix columns
2507 USE_AVG = 2 //!
2508 };
2509
2510 /** @brief default constructor
2511
2512 The default constructor initializes an empty %PCA structure. The other
2513 constructors initialize the structure and call PCA::operator()().
2514 */
2515 PCA();
2516
2517 /** @overload
2518 @param data input samples stored as matrix rows or matrix columns.
2519 @param mean optional mean value; if the matrix is empty (@c noArray()),
2520 the mean is computed from the data.
2521 @param flags operation flags; currently the parameter is only used to
2522 specify the data layout (PCA::Flags)
2523 @param maxComponents maximum number of components that %PCA should
2524 retain; by default, all the components are retained.
2525 */
2526 PCA(InputArray data, InputArray mean, int flags, int maxComponents = 0);
2527
2528 /** @overload
2529 @param data input samples stored as matrix rows or matrix columns.
2530 @param mean optional mean value; if the matrix is empty (noArray()),
2531 the mean is computed from the data.
2532 @param flags operation flags; currently the parameter is only used to
2533 specify the data layout (PCA::Flags)
2534 @param retainedVariance Percentage of variance that PCA should retain.
2535 Using this parameter will let the PCA decided how many components to
2536 retain but it will always keep at least 2.
2537 */
2538 PCA(InputArray data, InputArray mean, int flags, double retainedVariance);
2539
2540 /** @brief performs %PCA
2541
2542 The operator performs %PCA of the supplied dataset. It is safe to reuse
2543 the same PCA structure for multiple datasets. That is, if the structure
2544 has been previously used with another dataset, the existing internal
2545 data is reclaimed and the new @ref eigenvalues, @ref eigenvectors and @ref
2546 mean are allocated and computed.
2547
2548 The computed @ref eigenvalues are sorted from the largest to the smallest and
2549 the corresponding @ref eigenvectors are stored as eigenvectors rows.
2550
2551 @param data input samples stored as the matrix rows or as the matrix
2552 columns.
2553 @param mean optional mean value; if the matrix is empty (noArray()),
2554 the mean is computed from the data.
2555 @param flags operation flags; currently the parameter is only used to
2556 specify the data layout. (Flags)
2557 @param maxComponents maximum number of components that PCA should
2558 retain; by default, all the components are retained.
2559 */
2560 PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents = 0);
2561
2562 /** @overload
2563 @param data input samples stored as the matrix rows or as the matrix
2564 columns.
2565 @param mean optional mean value; if the matrix is empty (noArray()),
2566 the mean is computed from the data.
2567 @param flags operation flags; currently the parameter is only used to
2568 specify the data layout. (PCA::Flags)
2569 @param retainedVariance Percentage of variance that %PCA should retain.
2570 Using this parameter will let the %PCA decided how many components to
2571 retain but it will always keep at least 2.
2572 */
2573 PCA& operator()(InputArray data, InputArray mean, int flags, double retainedVariance);
2574
2575 /** @brief Projects vector(s) to the principal component subspace.
2576
2577 The methods project one or more vectors to the principal component
2578 subspace, where each vector projection is represented by coefficients in
2579 the principal component basis. The first form of the method returns the
2580 matrix that the second form writes to the result. So the first form can
2581 be used as a part of expression while the second form can be more
2582 efficient in a processing loop.
2583 @param vec input vector(s); must have the same dimensionality and the
2584 same layout as the input data used at %PCA phase, that is, if
2585 DATA_AS_ROW are specified, then `vec.cols==data.cols`
2586 (vector dimensionality) and `vec.rows` is the number of vectors to
2587 project, and the same is true for the PCA::DATA_AS_COL case.
2588 */
2589 Mat project(InputArray vec) const;
2590
2591 /** @overload
2592 @param vec input vector(s); must have the same dimensionality and the
2593 same layout as the input data used at PCA phase, that is, if
2594 DATA_AS_ROW are specified, then `vec.cols==data.cols`
2595 (vector dimensionality) and `vec.rows` is the number of vectors to
2596 project, and the same is true for the PCA::DATA_AS_COL case.
2597 @param result output vectors; in case of PCA::DATA_AS_COL, the
2598 output matrix has as many columns as the number of input vectors, this
2599 means that `result.cols==vec.cols` and the number of rows match the
2600 number of principal components (for example, `maxComponents` parameter
2601 passed to the constructor).
2602 */
2603 void project(InputArray vec, OutputArray result) const;
2604
2605 /** @brief Reconstructs vectors from their PC projections.
2606
2607 The methods are inverse operations to PCA::project. They take PC
2608 coordinates of projected vectors and reconstruct the original vectors.
2609 Unless all the principal components have been retained, the
2610 reconstructed vectors are different from the originals. But typically,
2611 the difference is small if the number of components is large enough (but
2612 still much smaller than the original vector dimensionality). As a
2613 result, PCA is used.
2614 @param vec coordinates of the vectors in the principal component
2615 subspace, the layout and size are the same as of PCA::project output
2616 vectors.
2617 */
2618 Mat backProject(InputArray vec) const;
2619
2620 /** @overload
2621 @param vec coordinates of the vectors in the principal component
2622 subspace, the layout and size are the same as of PCA::project output
2623 vectors.
2624 @param result reconstructed vectors; the layout and size are the same as
2625 of PCA::project input vectors.
2626 */
2627 void backProject(InputArray vec, OutputArray result) const;
2628
2629 /** @brief write PCA objects
2630
2631 Writes @ref eigenvalues @ref eigenvectors and @ref mean to specified FileStorage
2632 */
2633 void write(FileStorage& fs) const;
2634
2635 /** @brief load PCA objects
2636
2637 Loads @ref eigenvalues @ref eigenvectors and @ref mean from specified FileNode
2638 */
2639 void read(const FileNode& fn);
2640
2641 Mat eigenvectors; //!< eigenvectors of the covariation matrix
2642 Mat eigenvalues; //!< eigenvalues of the covariation matrix
2643 Mat mean; //!< mean value subtracted before the projection and added after the back projection
2644};
2645
2646/** @example samples/cpp/pca.cpp
2647An example using %PCA for dimensionality reduction while maintaining an amount of variance
2648*/
2649
2650/** @example samples/cpp/tutorial_code/ml/introduction_to_pca/introduction_to_pca.cpp
2651Check @ref tutorial_introduction_to_pca "the corresponding tutorial" for more details
2652*/
2653
2654/**
2655@brief Linear Discriminant Analysis
2656@todo document this class
2657*/
2658class CV_EXPORTS LDA
2659{
2660public:
2661 /** @brief constructor
2662 Initializes a LDA with num_components (default 0).
2663 */
2664 explicit LDA(int num_components = 0);
2665
2666 /** Initializes and performs a Discriminant Analysis with Fisher's
2667 Optimization Criterion on given data in src and corresponding labels
2668 in labels. If 0 (or less) number of components are given, they are
2669 automatically determined for given data in computation.
2670 */
2671 LDA(InputArrayOfArrays src, InputArray labels, int num_components = 0);
2672
2673 /** Serializes this object to a given filename.
2674 */
2675 void save(const String& filename) const;
2676
2677 /** Deserializes this object from a given filename.
2678 */
2679 void load(const String& filename);
2680
2681 /** Serializes this object to a given cv::FileStorage.
2682 */
2683 void save(FileStorage& fs) const;
2684
2685 /** Deserializes this object from a given cv::FileStorage.
2686 */
2687 void load(const FileStorage& node);
2688
2689 /** destructor
2690 */
2691 ~LDA();
2692
2693 /** Compute the discriminants for data in src (row aligned) and labels.
2694 */
2695 void compute(InputArrayOfArrays src, InputArray labels);
2696
2697 /** Projects samples into the LDA subspace.
2698 src may be one or more row aligned samples.
2699 */
2700 Mat project(InputArray src);
2701
2702 /** Reconstructs projections from the LDA subspace.
2703 src may be one or more row aligned projections.
2704 */
2705 Mat reconstruct(InputArray src);
2706
2707 /** Returns the eigenvectors of this LDA.
2708 */
2709 Mat eigenvectors() const { return _eigenvectors; }
2710
2711 /** Returns the eigenvalues of this LDA.
2712 */
2713 Mat eigenvalues() const { return _eigenvalues; }
2714
2715 static Mat subspaceProject(InputArray W, InputArray mean, InputArray src);
2716 static Mat subspaceReconstruct(InputArray W, InputArray mean, InputArray src);
2717
2718protected:
2719 int _num_components;
2720 Mat _eigenvectors;
2721 Mat _eigenvalues;
2722 void lda(InputArrayOfArrays src, InputArray labels);
2723};
2724
2725/** @brief Singular Value Decomposition
2726
2727Class for computing Singular Value Decomposition of a floating-point
2728matrix. The Singular Value Decomposition is used to solve least-square
2729problems, under-determined linear systems, invert matrices, compute
2730condition numbers, and so on.
2731
2732If you want to compute a condition number of a matrix or an absolute value of
2733its determinant, you do not need `u` and `vt`. You can pass
2734flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that full-size u
2735and vt must be computed, which is not necessary most of the time.
2736
2737@sa invert, solve, eigen, determinant
2738*/
2739class CV_EXPORTS SVD
2740{
2741public:
2742 enum Flags {
2743 /** allow the algorithm to modify the decomposed matrix; it can save space and speed up
2744 processing. currently ignored. */
2745 MODIFY_A = 1,
2746 /** indicates that only a vector of singular values `w` is to be processed, while u and vt
2747 will be set to empty matrices */
2748 NO_UV = 2,
2749 /** when the matrix is not square, by default the algorithm produces u and vt matrices of
2750 sufficiently large size for the further A reconstruction; if, however, FULL_UV flag is
2751 specified, u and vt will be full-size square orthogonal matrices.*/
2752 FULL_UV = 4
2753 };
2754
2755 /** @brief the default constructor
2756
2757 initializes an empty SVD structure
2758 */
2759 SVD();
2760
2761 /** @overload
2762 initializes an empty SVD structure and then calls SVD::operator()
2763 @param src decomposed matrix. The depth has to be CV_32F or CV_64F.
2764 @param flags operation flags (SVD::Flags)
2765 */
2766 SVD( InputArray src, int flags = 0 );
2767
2768 /** @brief the operator that performs SVD. The previously allocated u, w and vt are released.
2769
2770 The operator performs the singular value decomposition of the supplied
2771 matrix. The u,`vt` , and the vector of singular values w are stored in
2772 the structure. The same SVD structure can be reused many times with
2773 different matrices. Each time, if needed, the previous u,`vt` , and w
2774 are reclaimed and the new matrices are created, which is all handled by
2775 Mat::create.
2776 @param src decomposed matrix. The depth has to be CV_32F or CV_64F.
2777 @param flags operation flags (SVD::Flags)
2778 */
2779 SVD& operator ()( InputArray src, int flags = 0 );
2780
2781 /** @brief decomposes matrix and stores the results to user-provided matrices
2782
2783 The methods/functions perform SVD of matrix. Unlike SVD::SVD constructor
2784 and SVD::operator(), they store the results to the user-provided
2785 matrices:
2786
2787 @code{.cpp}
2788 Mat A, w, u, vt;
2789 SVD::compute(A, w, u, vt);
2790 @endcode
2791
2792 @param src decomposed matrix. The depth has to be CV_32F or CV_64F.
2793 @param w calculated singular values
2794 @param u calculated left singular vectors
2795 @param vt transposed matrix of right singular vectors
2796 @param flags operation flags - see SVD::Flags.
2797 */
2798 static void compute( InputArray src, OutputArray w,
2799 OutputArray u, OutputArray vt, int flags = 0 );
2800
2801 /** @overload
2802 computes singular values of a matrix
2803 @param src decomposed matrix. The depth has to be CV_32F or CV_64F.
2804 @param w calculated singular values
2805 @param flags operation flags - see SVD::Flags.
2806 */
2807 static void compute( InputArray src, OutputArray w, int flags = 0 );
2808
2809 /** @brief performs back substitution
2810 */
2811 static void backSubst( InputArray w, InputArray u,
2812 InputArray vt, InputArray rhs,
2813 OutputArray dst );
2814
2815 /** @brief solves an under-determined singular linear system
2816
2817 The method finds a unit-length solution x of a singular linear system
2818 A\*x = 0. Depending on the rank of A, there can be no solutions, a
2819 single solution or an infinite number of solutions. In general, the
2820 algorithm solves the following problem:
2821 \f[dst = \arg \min _{x: \| x \| =1} \| src \cdot x \|\f]
2822 @param src left-hand-side matrix.
2823 @param dst found solution.
2824 */
2825 static void solveZ( InputArray src, OutputArray dst );
2826
2827 /** @brief performs a singular value back substitution.
2828
2829 The method calculates a back substitution for the specified right-hand
2830 side:
2831
2832 \f[\texttt{x} = \texttt{vt} ^T \cdot diag( \texttt{w} )^{-1} \cdot \texttt{u} ^T \cdot \texttt{rhs} \sim \texttt{A} ^{-1} \cdot \texttt{rhs}\f]
2833
2834 Using this technique you can either get a very accurate solution of the
2835 convenient linear system, or the best (in the least-squares terms)
2836 pseudo-solution of an overdetermined linear system.
2837
2838 @param rhs right-hand side of a linear system (u\*w\*v')\*dst = rhs to
2839 be solved, where A has been previously decomposed.
2840
2841 @param dst found solution of the system.
2842
2843 @note Explicit SVD with the further back substitution only makes sense
2844 if you need to solve many linear systems with the same left-hand side
2845 (for example, src ). If all you need is to solve a single system
2846 (possibly with multiple rhs immediately available), simply call solve
2847 add pass #DECOMP_SVD there. It does absolutely the same thing.
2848 */
2849 void backSubst( InputArray rhs, OutputArray dst ) const;
2850
2851 /** @todo document */
2852 template<typename _Tp, int m, int n, int nm> static
2853 void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt );
2854
2855 /** @todo document */
2856 template<typename _Tp, int m, int n, int nm> static
2857 void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w );
2858
2859 /** @todo document */
2860 template<typename _Tp, int m, int n, int nm, int nb> static
2861 void backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst );
2862
2863 Mat u, w, vt;
2864};
2865
2866/** @brief Random Number Generator
2867
2868Random number generator. It encapsulates the state (currently, a 64-bit
2869integer) and has methods to return scalar random values and to fill
2870arrays with random values. Currently it supports uniform and Gaussian
2871(normal) distributions. The generator uses Multiply-With-Carry
2872algorithm, introduced by G. Marsaglia (
2873<http://en.wikipedia.org/wiki/Multiply-with-carry> ).
2874Gaussian-distribution random numbers are generated using the Ziggurat
2875algorithm ( <http://en.wikipedia.org/wiki/Ziggurat_algorithm> ),
2876introduced by G. Marsaglia and W. W. Tsang.
2877*/
2878class CV_EXPORTS RNG
2879{
2880public:
2881 enum { UNIFORM = 0,
2882 NORMAL = 1
2883 };
2884
2885 /** @brief constructor
2886
2887 These are the RNG constructors. The first form sets the state to some
2888 pre-defined value, equal to 2\*\*32-1 in the current implementation. The
2889 second form sets the state to the specified value. If you passed state=0
2890 , the constructor uses the above default value instead to avoid the
2891 singular random number sequence, consisting of all zeros.
2892 */
2893 RNG();
2894 /** @overload
2895 @param state 64-bit value used to initialize the RNG.
2896 */
2897 RNG(uint64 state);
2898 /**The method updates the state using the MWC algorithm and returns the
2899 next 32-bit random number.*/
2900 unsigned next();
2901
2902 /**Each of the methods updates the state using the MWC algorithm and
2903 returns the next random number of the specified type. In case of integer
2904 types, the returned number is from the available value range for the
2905 specified type. In case of floating-point types, the returned value is
2906 from [0,1) range.
2907 */
2908 operator uchar();
2909 /** @overload */
2910 operator schar();
2911 /** @overload */
2912 operator ushort();
2913 /** @overload */
2914 operator short();
2915 /** @overload */
2916 operator unsigned();
2917 /** @overload */
2918 operator int();
2919 /** @overload */
2920 operator float();
2921 /** @overload */
2922 operator double();
2923
2924 /** @brief returns a random integer sampled uniformly from [0, N).
2925
2926 The methods transform the state using the MWC algorithm and return the
2927 next random number. The first form is equivalent to RNG::next . The
2928 second form returns the random number modulo N, which means that the
2929 result is in the range [0, N) .
2930 */
2931 unsigned operator ()();
2932 /** @overload
2933 @param N upper non-inclusive boundary of the returned random number.
2934 */
2935 unsigned operator ()(unsigned N);
2936
2937 /** @brief returns uniformly distributed integer random number from [a,b) range
2938
2939 The methods transform the state using the MWC algorithm and return the
2940 next uniformly-distributed random number of the specified type, deduced
2941 from the input parameter type, from the range [a, b) . There is a nuance
2942 illustrated by the following sample:
2943
2944 @code{.cpp}
2945 RNG rng;
2946
2947 // always produces 0
2948 double a = rng.uniform(0, 1);
2949
2950 // produces double from [0, 1)
2951 double a1 = rng.uniform((double)0, (double)1);
2952
2953 // produces float from [0, 1)
2954 float b = rng.uniform(0.f, 1.f);
2955
2956 // produces double from [0, 1)
2957 double c = rng.uniform(0., 1.);
2958
2959 // may cause compiler error because of ambiguity:
2960 // RNG::uniform(0, (int)0.999999)? or RNG::uniform((double)0, 0.99999)?
2961 double d = rng.uniform(0, 0.999999);
2962 @endcode
2963
2964 The compiler does not take into account the type of the variable to
2965 which you assign the result of RNG::uniform . The only thing that
2966 matters to the compiler is the type of a and b parameters. So, if you
2967 want a floating-point random number, but the range boundaries are
2968 integer numbers, either put dots in the end, if they are constants, or
2969 use explicit type cast operators, as in the a1 initialization above.
2970 @param a lower inclusive boundary of the returned random number.
2971 @param b upper non-inclusive boundary of the returned random number.
2972 */
2973 int uniform(int a, int b);
2974 /** @overload */
2975 float uniform(float a, float b);
2976 /** @overload */
2977 double uniform(double a, double b);
2978
2979 /** @brief Fills arrays with random numbers.
2980
2981 @param mat 2D or N-dimensional matrix; currently matrices with more than
2982 4 channels are not supported by the methods, use Mat::reshape as a
2983 possible workaround.
2984 @param distType distribution type, RNG::UNIFORM or RNG::NORMAL.
2985 @param a first distribution parameter; in case of the uniform
2986 distribution, this is an inclusive lower boundary, in case of the normal
2987 distribution, this is a mean value.
2988 @param b second distribution parameter; in case of the uniform
2989 distribution, this is a non-inclusive upper boundary, in case of the
2990 normal distribution, this is a standard deviation (diagonal of the
2991 standard deviation matrix or the full standard deviation matrix).
2992 @param saturateRange pre-saturation flag; for uniform distribution only;
2993 if true, the method will first convert a and b to the acceptable value
2994 range (according to the mat datatype) and then will generate uniformly
2995 distributed random numbers within the range [saturate(a), saturate(b)),
2996 if saturateRange=false, the method will generate uniformly distributed
2997 random numbers in the original range [a, b) and then will saturate them,
2998 it means, for example, that
2999 <tt>theRNG().fill(mat_8u, RNG::UNIFORM, -DBL_MAX, DBL_MAX)</tt> will likely
3000 produce array mostly filled with 0's and 255's, since the range (0, 255)
3001 is significantly smaller than [-DBL_MAX, DBL_MAX).
3002
3003 Each of the methods fills the matrix with the random values from the
3004 specified distribution. As the new numbers are generated, the RNG state
3005 is updated accordingly. In case of multiple-channel images, every
3006 channel is filled independently, which means that RNG cannot generate
3007 samples from the multi-dimensional Gaussian distribution with
3008 non-diagonal covariance matrix directly. To do that, the method
3009 generates samples from multi-dimensional standard Gaussian distribution
3010 with zero mean and identity covariation matrix, and then transforms them
3011 using transform to get samples from the specified Gaussian distribution.
3012 */
3013 void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange = false );
3014
3015 /** @brief Returns the next random number sampled from the Gaussian distribution
3016 @param sigma standard deviation of the distribution.
3017
3018 The method transforms the state using the MWC algorithm and returns the
3019 next random number from the Gaussian distribution N(0,sigma) . That is,
3020 the mean value of the returned random numbers is zero and the standard
3021 deviation is the specified sigma .
3022 */
3023 double gaussian(double sigma);
3024
3025 uint64 state;
3026
3027 bool operator ==(const RNG& other) const;
3028};
3029
3030/** @brief Mersenne Twister random number generator
3031
3032Inspired by http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c
3033@todo document
3034*/
3035class CV_EXPORTS RNG_MT19937
3036{
3037public:
3038 RNG_MT19937();
3039 RNG_MT19937(unsigned s);
3040 void seed(unsigned s);
3041
3042 unsigned next();
3043
3044 operator int();
3045 operator unsigned();
3046 operator float();
3047 operator double();
3048
3049 unsigned operator ()(unsigned N);
3050 unsigned operator ()();
3051
3052 /** @brief returns uniformly distributed integer random number from [a,b) range*/
3053 int uniform(int a, int b);
3054 /** @brief returns uniformly distributed floating-point random number from [a,b) range*/
3055 float uniform(float a, float b);
3056 /** @brief returns uniformly distributed double-precision floating-point random number from [a,b) range*/
3057 double uniform(double a, double b);
3058
3059private:
3060 enum PeriodParameters {N = 624, M = 397};
3061 unsigned state[N];
3062 int mti;
3063};
3064
3065//! @} core_array
3066
3067//! @addtogroup core_cluster
3068//! @{
3069
3070//! k-means flags
3071enum KmeansFlags {
3072 /** Select random initial centers in each attempt.*/
3073 KMEANS_RANDOM_CENTERS = 0,
3074 /** Use kmeans++ center initialization by Arthur and Vassilvitskii [Arthur2007].*/
3075 KMEANS_PP_CENTERS = 2,
3076 /** During the first (and possibly the only) attempt, use the
3077 user-supplied labels instead of computing them from the initial centers. For the second and
3078 further attempts, use the random or semi-random centers. Use one of KMEANS_\*_CENTERS flag
3079 to specify the exact method.*/
3080 KMEANS_USE_INITIAL_LABELS = 1
3081};
3082
3083/** @example samples/cpp/kmeans.cpp
3084An example on k-means clustering
3085*/
3086
3087/** @brief Finds centers of clusters and groups input samples around the clusters.
3088
3089The function kmeans implements a k-means algorithm that finds the centers of cluster_count clusters
3090and groups the input samples around the clusters. As an output, \f$\texttt{bestLabels}_i\f$ contains a
30910-based cluster index for the sample stored in the \f$i^{th}\f$ row of the samples matrix.
3092
3093@note
3094- (Python) An example on k-means clustering can be found at
3095 opencv_source_code/samples/python/kmeans.py
3096@param data Data for clustering. An array of N-Dimensional points with float coordinates is needed.
3097Examples of this array can be:
3098- Mat points(count, 2, CV_32F);
3099- Mat points(count, 1, CV_32FC2);
3100- Mat points(1, count, CV_32FC2);
3101- std::vector\<cv::Point2f\> points(sampleCount);
3102@param K Number of clusters to split the set by.
3103@param bestLabels Input/output integer array that stores the cluster indices for every sample.
3104@param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or
3105the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster
3106centers moves by less than criteria.epsilon on some iteration, the algorithm stops.
3107@param attempts Flag to specify the number of times the algorithm is executed using different
3108initial labellings. The algorithm returns the labels that yield the best compactness (see the last
3109function parameter).
3110@param flags Flag that can take values of cv::KmeansFlags
3111@param centers Output matrix of the cluster centers, one row per each cluster center.
3112@return The function returns the compactness measure that is computed as
3113\f[\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\f]
3114after every attempt. The best (minimum) value is chosen and the corresponding labels and the
3115compactness value are returned by the function. Basically, you can use only the core of the
3116function, set the number of attempts to 1, initialize labels each time using a custom algorithm,
3117pass them with the ( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best
3118(most-compact) clustering.
3119*/
3120CV_EXPORTS_W double kmeans( InputArray data, int K, InputOutputArray bestLabels,
3121 TermCriteria criteria, int attempts,
3122 int flags, OutputArray centers = noArray() );
3123
3124//! @} core_cluster
3125
3126//! @addtogroup core_basic
3127//! @{
3128
3129/////////////////////////////// Formatted output of cv::Mat ///////////////////////////
3130
3131/** @todo document */
3132class CV_EXPORTS Formatted
3133{
3134public:
3135 virtual const char* next() = 0;
3136 virtual void reset() = 0;
3137 virtual ~Formatted();
3138};
3139
3140/** @todo document */
3141class CV_EXPORTS Formatter
3142{
3143public:
3144 enum FormatType {
3145 FMT_DEFAULT = 0,
3146 FMT_MATLAB = 1,
3147 FMT_CSV = 2,
3148 FMT_PYTHON = 3,
3149 FMT_NUMPY = 4,
3150 FMT_C = 5
3151 };
3152
3153 virtual ~Formatter();
3154
3155 virtual Ptr<Formatted> format(const Mat& mtx) const = 0;
3156
3157 virtual void set16fPrecision(int p = 4) = 0;
3158 virtual void set32fPrecision(int p = 8) = 0;
3159 virtual void set64fPrecision(int p = 16) = 0;
3160 virtual void setMultiline(bool ml = true) = 0;
3161
3162 static Ptr<Formatter> get(Formatter::FormatType fmt = FMT_DEFAULT);
3163
3164};
3165
3166static inline
3167String& operator << (String& out, Ptr<Formatted> fmtd)
3168{
3169 fmtd->reset();
3170 for(const char* str = fmtd->next(); str; str = fmtd->next())
3171 out += cv::String(str);
3172 return out;
3173}
3174
3175static inline
3176String& operator << (String& out, const Mat& mtx)
3177{
3178 return out << Formatter::get()->format(mtx);
3179}
3180
3181//////////////////////////////////////// Algorithm ////////////////////////////////////
3182
3183class CV_EXPORTS Algorithm;
3184
3185template<typename _Tp, typename _EnumTp = void> struct ParamType {};
3186
3187
3188/** @brief This is a base class for all more or less complex algorithms in OpenCV
3189
3190especially for classes of algorithms, for which there can be multiple implementations. The examples
3191are stereo correspondence (for which there are algorithms like block matching, semi-global block
3192matching, graph-cut etc.), background subtraction (which can be done using mixture-of-gaussians
3193models, codebook-based algorithm etc.), optical flow (block matching, Lucas-Kanade, Horn-Schunck
3194etc.).
3195
3196Here is example of SimpleBlobDetector use in your application via Algorithm interface:
3197@snippet snippets/core_various.cpp Algorithm
3198*/
3199class CV_EXPORTS_W Algorithm
3200{
3201public:
3202 Algorithm();
3203 virtual ~Algorithm();
3204
3205 /** @brief Clears the algorithm state
3206 */
3207 CV_WRAP virtual void clear() {}
3208
3209 /** @brief Stores algorithm parameters in a file storage
3210 */
3211 CV_WRAP virtual void write(FileStorage& fs) const { CV_UNUSED(fs); }
3212
3213 /**
3214 * @overload
3215 */
3216 CV_WRAP void write(FileStorage& fs, const String& name) const;
3217#if CV_VERSION_MAJOR < 5
3218 /** @deprecated */
3219 void write(const Ptr<FileStorage>& fs, const String& name = String()) const;
3220#endif
3221
3222 /** @brief Reads algorithm parameters from a file storage
3223 */
3224 CV_WRAP virtual void read(const FileNode& fn) { CV_UNUSED(fn); }
3225
3226 /** @brief Returns true if the Algorithm is empty (e.g. in the very beginning or after unsuccessful read
3227 */
3228 CV_WRAP virtual bool empty() const { return false; }
3229
3230 /** @brief Reads algorithm from the file node
3231
3232 This is static template method of Algorithm. It's usage is following (in the case of SVM):
3233 @code
3234 cv::FileStorage fsRead("example.xml", FileStorage::READ);
3235 Ptr<SVM> svm = Algorithm::read<SVM>(fsRead.root());
3236 @endcode
3237 In order to make this method work, the derived class must overwrite Algorithm::read(const
3238 FileNode& fn) and also have static create() method without parameters
3239 (or with all the optional parameters)
3240 */
3241 template<typename _Tp> static Ptr<_Tp> read(const FileNode& fn)
3242 {
3243 Ptr<_Tp> obj = _Tp::create();
3244 obj->read(fn);
3245 return !obj->empty() ? obj : Ptr<_Tp>();
3246 }
3247
3248 /** @brief Loads algorithm from the file
3249
3250 @param filename Name of the file to read.
3251 @param objname The optional name of the node to read (if empty, the first top-level node will be used)
3252
3253 This is static template method of Algorithm. It's usage is following (in the case of SVM):
3254 @code
3255 Ptr<SVM> svm = Algorithm::load<SVM>("my_svm_model.xml");
3256 @endcode
3257 In order to make this method work, the derived class must overwrite Algorithm::read(const
3258 FileNode& fn).
3259 */
3260 template<typename _Tp> static Ptr<_Tp> load(const String& filename, const String& objname=String())
3261 {
3262 FileStorage fs(filename, FileStorage::READ);
3263 CV_Assert(fs.isOpened());
3264 FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname];
3265 if (fn.empty()) return Ptr<_Tp>();
3266 Ptr<_Tp> obj = _Tp::create();
3267 obj->read(fn);
3268 return !obj->empty() ? obj : Ptr<_Tp>();
3269 }
3270
3271 /** @brief Loads algorithm from a String
3272
3273 @param strModel The string variable containing the model you want to load.
3274 @param objname The optional name of the node to read (if empty, the first top-level node will be used)
3275
3276 This is static template method of Algorithm. It's usage is following (in the case of SVM):
3277 @code
3278 Ptr<SVM> svm = Algorithm::loadFromString<SVM>(myStringModel);
3279 @endcode
3280 */
3281 template<typename _Tp> static Ptr<_Tp> loadFromString(const String& strModel, const String& objname=String())
3282 {
3283 FileStorage fs(strModel, FileStorage::READ + FileStorage::MEMORY);
3284 FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname];
3285 Ptr<_Tp> obj = _Tp::create();
3286 obj->read(fn);
3287 return !obj->empty() ? obj : Ptr<_Tp>();
3288 }
3289
3290 /** Saves the algorithm to a file.
3291 In order to make this method work, the derived class must implement Algorithm::write(FileStorage& fs). */
3292 CV_WRAP virtual void save(const String& filename) const;
3293
3294 /** Returns the algorithm string identifier.
3295 This string is used as top level xml/yml node tag when the object is saved to a file or string. */
3296 CV_WRAP virtual String getDefaultName() const;
3297
3298protected:
3299 void writeFormat(FileStorage& fs) const;
3300};
3301
3302enum struct Param {
3303 INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7,
3304 UNSIGNED_INT=8, UINT64=9, UCHAR=11, SCALAR=12
3305};
3306
3307
3308
3309template<> struct ParamType<bool>
3310{
3311 typedef bool const_param_type;
3312 typedef bool member_type;
3313
3314 static const Param type = Param::BOOLEAN;
3315};
3316
3317template<> struct ParamType<int>
3318{
3319 typedef int const_param_type;
3320 typedef int member_type;
3321
3322 static const Param type = Param::INT;
3323};
3324
3325template<> struct ParamType<double>
3326{
3327 typedef double const_param_type;
3328 typedef double member_type;
3329
3330 static const Param type = Param::REAL;
3331};
3332
3333template<> struct ParamType<String>
3334{
3335 typedef const String& const_param_type;
3336 typedef String member_type;
3337
3338 static const Param type = Param::STRING;
3339};
3340
3341template<> struct ParamType<Mat>
3342{
3343 typedef const Mat& const_param_type;
3344 typedef Mat member_type;
3345
3346 static const Param type = Param::MAT;
3347};
3348
3349template<> struct ParamType<std::vector<Mat> >
3350{
3351 typedef const std::vector<Mat>& const_param_type;
3352 typedef std::vector<Mat> member_type;
3353
3354 static const Param type = Param::MAT_VECTOR;
3355};
3356
3357template<> struct ParamType<Algorithm>
3358{
3359 typedef const Ptr<Algorithm>& const_param_type;
3360 typedef Ptr<Algorithm> member_type;
3361
3362 static const Param type = Param::ALGORITHM;
3363};
3364
3365template<> struct ParamType<float>
3366{
3367 typedef float const_param_type;
3368 typedef float member_type;
3369
3370 static const Param type = Param::FLOAT;
3371};
3372
3373template<> struct ParamType<unsigned>
3374{
3375 typedef unsigned const_param_type;
3376 typedef unsigned member_type;
3377
3378 static const Param type = Param::UNSIGNED_INT;
3379};
3380
3381template<> struct ParamType<uint64>
3382{
3383 typedef uint64 const_param_type;
3384 typedef uint64 member_type;
3385
3386 static const Param type = Param::UINT64;
3387};
3388
3389template<> struct ParamType<uchar>
3390{
3391 typedef uchar const_param_type;
3392 typedef uchar member_type;
3393
3394 static const Param type = Param::UCHAR;
3395};
3396
3397template<> struct ParamType<Scalar>
3398{
3399 typedef const Scalar& const_param_type;
3400 typedef Scalar member_type;
3401
3402 static const Param type = Param::SCALAR;
3403};
3404
3405template<typename _Tp>
3406struct ParamType<_Tp, typename std::enable_if< std::is_enum<_Tp>::value >::type>
3407{
3408 typedef typename std::underlying_type<_Tp>::type const_param_type;
3409 typedef typename std::underlying_type<_Tp>::type member_type;
3410
3411 static const Param type = Param::INT;
3412};
3413
3414//! @} core_basic
3415
3416} //namespace cv
3417
3418#include "opencv2/core/operations.hpp"
3419#include "opencv2/core/cvstd.inl.hpp"
3420#include "opencv2/core/utility.hpp"
3421#include "opencv2/core/optim.hpp"
3422#include "opencv2/core/ovx.hpp"
3423
3424#endif /*OPENCV_CORE_HPP*/
3425

source code of opencv/modules/core/include/opencv2/core.hpp