Path: blob/master/modules/core/include/opencv2/core.hpp
16339 views
/*M///////////////////////////////////////////////////////////////////////////////////////1//2// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.3//4// By downloading, copying, installing or using the software you agree to this license.5// If you do not agree to this license, do not download, install,6// copy or use the software.7//8//9// License Agreement10// For Open Source Computer Vision Library11//12// Copyright (C) 2000-2015, Intel Corporation, all rights reserved.13// Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.14// Copyright (C) 2015, OpenCV Foundation, all rights reserved.15// Copyright (C) 2015, Itseez Inc., all rights reserved.16// Third party copyrights are property of their respective owners.17//18// Redistribution and use in source and binary forms, with or without modification,19// are permitted provided that the following conditions are met:20//21// * Redistribution's of source code must retain the above copyright notice,22// this list of conditions and the following disclaimer.23//24// * Redistribution's in binary form must reproduce the above copyright notice,25// this list of conditions and the following disclaimer in the documentation26// and/or other materials provided with the distribution.27//28// * The name of the copyright holders may not be used to endorse or promote products29// derived from this software without specific prior written permission.30//31// This software is provided by the copyright holders and contributors "as is" and32// any express or implied warranties, including, but not limited to, the implied33// warranties of merchantability and fitness for a particular purpose are disclaimed.34// In no event shall the Intel Corporation or contributors be liable for any direct,35// indirect, incidental, special, exemplary, or consequential damages36// (including, but not limited to, procurement of substitute goods or services;37// loss of use, data, or profits; or business interruption) however caused38// and on any theory of liability, whether in contract, strict liability,39// or tort (including negligence or otherwise) arising in any way out of40// the use of this software, even if advised of the possibility of such damage.41//42//M*/4344#ifndef OPENCV_CORE_HPP45#define OPENCV_CORE_HPP4647#ifndef __cplusplus48# error core.hpp header must be compiled as C++49#endif5051#include "opencv2/core/cvdef.h"52#include "opencv2/core/version.hpp"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"6061/**62@defgroup core Core functionality63@{64@defgroup core_basic Basic structures65@defgroup core_c C structures and operations66@{67@defgroup core_c_glue Connections with C++68@}69@defgroup core_array Operations on arrays70@defgroup core_xml XML/YAML Persistence71@defgroup core_cluster Clustering72@defgroup core_utils Utility and system functions and macros73@{74@defgroup core_utils_sse SSE utilities75@defgroup core_utils_neon NEON utilities76@defgroup core_utils_softfloat Softfloat support77@}78@defgroup core_opengl OpenGL interoperability79@defgroup core_ipp Intel IPP Asynchronous C/C++ Converters80@defgroup core_optim Optimization Algorithms81@defgroup core_directx DirectX interoperability82@defgroup core_eigen Eigen support83@defgroup core_opencl OpenCL support84@defgroup core_va_intel Intel VA-API/OpenCL (CL-VA) interoperability85@defgroup core_hal Hardware Acceleration Layer86@{87@defgroup core_hal_functions Functions88@defgroup core_hal_interface Interface89@defgroup core_hal_intrin Universal intrinsics90@{91@defgroup core_hal_intrin_impl Private implementation helpers92@}93@}94@}95*/9697namespace cv {9899//! @addtogroup core_utils100//! @{101102/*! @brief Class passed to an error.103104This class encapsulates all or almost all necessary105information about the error happened in the program. The exception is106usually constructed and thrown implicitly via CV_Error and CV_Error_ macros.107@see error108*/109class CV_EXPORTS Exception : public std::exception110{111public:112/*!113Default constructor114*/115Exception();116/*!117Full constructor. Normally the constructor is not called explicitly.118Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used.119*/120Exception(int _code, const String& _err, const String& _func, const String& _file, int _line);121virtual ~Exception() throw();122123/*!124\return the error description and the context as a text string.125*/126virtual const char *what() const throw() CV_OVERRIDE;127void formatMessage();128129String msg; ///< the formatted error message130131int code; ///< error code @see CVStatus132String err; ///< error description133String func; ///< function name. Available only when the compiler supports getting it134String file; ///< source file name where the error has occurred135int line; ///< line number in the source file where the error has occurred136};137138/*! @brief Signals an error and raises the exception.139140By default the function prints information about the error to stderr,141then it either stops if cv::setBreakOnError() had been called before or raises the exception.142It is possible to alternate error processing by using #redirectError().143@param exc the exception raisen.144@deprecated drop this version145*/146CV_EXPORTS CV_NORETURN void error(const Exception& exc);147148enum SortFlags { SORT_EVERY_ROW = 0, //!< each matrix row is sorted independently149SORT_EVERY_COLUMN = 1, //!< each matrix column is sorted150//!< independently; this flag and the previous one are151//!< mutually exclusive.152SORT_ASCENDING = 0, //!< each matrix row is sorted in the ascending153//!< order.154SORT_DESCENDING = 16 //!< each matrix row is sorted in the155//!< descending order; this flag and the previous one are also156//!< mutually exclusive.157};158159//! @} core_utils160161//! @addtogroup core162//! @{163164//! Covariation flags165enum CovarFlags {166/** The output covariance matrix is calculated as:167\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]168The covariance matrix will be nsamples x nsamples. Such an unusual covariance matrix is used169for fast PCA of a set of very large vectors (see, for example, the EigenFaces technique for170face recognition). Eigenvalues of this "scrambled" matrix match the eigenvalues of the true171covariance matrix. The "true" eigenvectors can be easily calculated from the eigenvectors of172the "scrambled" covariance matrix. */173COVAR_SCRAMBLED = 0,174/**The output covariance matrix is calculated as:175\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]176covar will be a square matrix of the same size as the total number of elements in each input177vector. One and only one of #COVAR_SCRAMBLED and #COVAR_NORMAL must be specified.*/178COVAR_NORMAL = 1,179/** If the flag is specified, the function does not calculate mean from180the input vectors but, instead, uses the passed mean vector. This is useful if mean has been181pre-calculated or known in advance, or if the covariance matrix is calculated by parts. In182this case, mean is not a mean vector of the input sub-set of vectors but rather the mean183vector of the whole set.*/184COVAR_USE_AVG = 2,185/** If the flag is specified, the covariance matrix is scaled. In the186"normal" mode, scale is 1./nsamples . In the "scrambled" mode, scale is the reciprocal of the187total number of elements in each input vector. By default (if the flag is not specified), the188covariance matrix is not scaled ( scale=1 ).*/189COVAR_SCALE = 4,190/** If the flag is191specified, all the input vectors are stored as rows of the samples matrix. mean should be a192single-row vector in this case.*/193COVAR_ROWS = 8,194/** If the flag is195specified, all the input vectors are stored as columns of the samples matrix. mean should be a196single-column vector in this case.*/197COVAR_COLS = 16198};199200//! k-Means flags201enum KmeansFlags {202/** Select random initial centers in each attempt.*/203KMEANS_RANDOM_CENTERS = 0,204/** Use kmeans++ center initialization by Arthur and Vassilvitskii [Arthur2007].*/205KMEANS_PP_CENTERS = 2,206/** During the first (and possibly the only) attempt, use the207user-supplied labels instead of computing them from the initial centers. For the second and208further attempts, use the random or semi-random centers. Use one of KMEANS_\*_CENTERS flag209to specify the exact method.*/210KMEANS_USE_INITIAL_LABELS = 1211};212213enum ReduceTypes { REDUCE_SUM = 0, //!< the output is the sum of all rows/columns of the matrix.214REDUCE_AVG = 1, //!< the output is the mean vector of all rows/columns of the matrix.215REDUCE_MAX = 2, //!< the output is the maximum (column/row-wise) of all rows/columns of the matrix.216REDUCE_MIN = 3 //!< the output is the minimum (column/row-wise) of all rows/columns of the matrix.217};218219220/** @brief Swaps two matrices221*/222CV_EXPORTS void swap(Mat& a, Mat& b);223/** @overload */224CV_EXPORTS void swap( UMat& a, UMat& b );225226//! @} core227228//! @addtogroup core_array229//! @{230231/** @brief Computes the source location of an extrapolated pixel.232233The function computes and returns the coordinate of a donor pixel corresponding to the specified234extrapolated pixel when using the specified extrapolation border mode. For example, if you use235cv::BORDER_WRAP mode in the horizontal direction, cv::BORDER_REFLECT_101 in the vertical direction and236want to compute value of the "virtual" pixel Point(-5, 100) in a floating-point image img , it237looks like:238@code{.cpp}239float val = img.at<float>(borderInterpolate(100, img.rows, cv::BORDER_REFLECT_101),240borderInterpolate(-5, img.cols, cv::BORDER_WRAP));241@endcode242Normally, the function is not called directly. It is used inside filtering functions and also in243copyMakeBorder.244@param p 0-based coordinate of the extrapolated pixel along one of the axes, likely \<0 or \>= len245@param len Length of the array along the corresponding axis.246@param borderType Border type, one of the #BorderTypes, except for #BORDER_TRANSPARENT and247#BORDER_ISOLATED . When borderType==#BORDER_CONSTANT , the function always returns -1, regardless248of p and len.249250@sa copyMakeBorder251*/252CV_EXPORTS_W int borderInterpolate(int p, int len, int borderType);253254/** @example samples/cpp/tutorial_code/ImgTrans/copyMakeBorder_demo.cpp255An example using copyMakeBorder function.256Check @ref tutorial_copyMakeBorder "the corresponding tutorial" for more details257*/258259/** @brief Forms a border around an image.260261The function copies the source image into the middle of the destination image. The areas to the262left, to the right, above and below the copied source image will be filled with extrapolated263pixels. This is not what filtering functions based on it do (they extrapolate pixels on-fly), but264what other more complex functions, including your own, may do to simplify image boundary handling.265266The function supports the mode when src is already in the middle of dst . In this case, the267function does not copy src itself but simply constructs the border, for example:268269@code{.cpp}270// let border be the same in all directions271int border=2;272// constructs a larger image to fit both the image and the border273Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth());274// select the middle part of it w/o copying data275Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows));276// convert image from RGB to grayscale277cvtColor(rgb, gray, COLOR_RGB2GRAY);278// form a border in-place279copyMakeBorder(gray, gray_buf, border, border,280border, border, BORDER_REPLICATE);281// now do some custom filtering ...282...283@endcode284@note When the source image is a part (ROI) of a bigger image, the function will try to use the285pixels outside of the ROI to form a border. To disable this feature and always do extrapolation, as286if src was not a ROI, use borderType | #BORDER_ISOLATED.287288@param src Source image.289@param dst Destination image of the same type as src and the size Size(src.cols+left+right,290src.rows+top+bottom) .291@param top292@param bottom293@param left294@param right Parameter specifying how many pixels in each direction from the source image rectangle295to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs296to be built.297@param borderType Border type. See borderInterpolate for details.298@param value Border value if borderType==BORDER_CONSTANT .299300@sa borderInterpolate301*/302CV_EXPORTS_W void copyMakeBorder(InputArray src, OutputArray dst,303int top, int bottom, int left, int right,304int borderType, const Scalar& value = Scalar() );305306/** @brief Calculates the per-element sum of two arrays or an array and a scalar.307308The function add calculates:309- Sum of two arrays when both input arrays have the same size and the same number of channels:310\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f]311- Sum of an array and a scalar when src2 is constructed from Scalar or has the same number of312elements as `src1.channels()`:313\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f]314- Sum of a scalar and an array when src1 is constructed from Scalar or has the same number of315elements as `src2.channels()`:316\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} + \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f]317where `I` is a multi-dimensional index of array elements. In case of multi-channel arrays, each318channel is processed independently.319320The first function in the list above can be replaced with matrix expressions:321@code{.cpp}322dst = src1 + src2;323dst += src1; // equivalent to add(dst, src1, dst);324@endcode325The input arrays and the output array can all have the same or different depths. For example, you326can add a 16-bit unsigned array to a 8-bit signed array and store the sum as a 32-bit327floating-point array. Depth of the output array is determined by the dtype parameter. In the second328and third cases above, as well as in the first case, when src1.depth() == src2.depth(), dtype can329be set to the default -1. In this case, the output array will have the same depth as the input330array, be it src1, src2 or both.331@note Saturation is not applied when the output array has the depth CV_32S. You may even get332result of an incorrect sign in the case of overflow.333@param src1 first input array or a scalar.334@param src2 second input array or a scalar.335@param dst output array that has the same size and number of channels as the input array(s); the336depth is defined by dtype or src1/src2.337@param mask optional operation mask - 8-bit single channel array, that specifies elements of the338output array to be changed.339@param dtype optional depth of the output array (see the discussion below).340@sa subtract, addWeighted, scaleAdd, Mat::convertTo341*/342CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst,343InputArray mask = noArray(), int dtype = -1);344345/** @brief Calculates the per-element difference between two arrays or array and a scalar.346347The function subtract calculates:348- Difference between two arrays, when both input arrays have the same size and the same number of349channels:350\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f]351- Difference between an array and a scalar, when src2 is constructed from Scalar or has the same352number of elements as `src1.channels()`:353\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f]354- Difference between a scalar and an array, when src1 is constructed from Scalar or has the same355number of elements as `src2.channels()`:356\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} - \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f]357- The reverse difference between a scalar and an array in the case of `SubRS`:358\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src2} - \texttt{src1}(I) ) \quad \texttt{if mask}(I) \ne0\f]359where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each360channel is processed independently.361362The first function in the list above can be replaced with matrix expressions:363@code{.cpp}364dst = src1 - src2;365dst -= src1; // equivalent to subtract(dst, src1, dst);366@endcode367The input arrays and the output array can all have the same or different depths. For example, you368can subtract to 8-bit unsigned arrays and store the difference in a 16-bit signed array. Depth of369the output array is determined by dtype parameter. In the second and third cases above, as well as370in the first case, when src1.depth() == src2.depth(), dtype can be set to the default -1. In this371case the output array will have the same depth as the input array, be it src1, src2 or both.372@note Saturation is not applied when the output array has the depth CV_32S. You may even get373result of an incorrect sign in the case of overflow.374@param src1 first input array or a scalar.375@param src2 second input array or a scalar.376@param dst output array of the same size and the same number of channels as the input array.377@param mask optional operation mask; this is an 8-bit single channel array that specifies elements378of the output array to be changed.379@param dtype optional depth of the output array380@sa add, addWeighted, scaleAdd, Mat::convertTo381*/382CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst,383InputArray mask = noArray(), int dtype = -1);384385386/** @brief Calculates the per-element scaled product of two arrays.387388The function multiply calculates the per-element product of two arrays:389390\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\f]391392There is also a @ref MatrixExpressions -friendly variant of the first function. See Mat::mul .393394For a not-per-element matrix product, see gemm .395396@note Saturation is not applied when the output array has the depth397CV_32S. You may even get result of an incorrect sign in the case of398overflow.399@param src1 first input array.400@param src2 second input array of the same size and the same type as src1.401@param dst output array of the same size and type as src1.402@param scale optional scale factor.403@param dtype optional depth of the output array404@sa add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare,405Mat::convertTo406*/407CV_EXPORTS_W void multiply(InputArray src1, InputArray src2,408OutputArray dst, double scale = 1, int dtype = -1);409410/** @brief Performs per-element division of two arrays or a scalar by an array.411412The function cv::divide divides one array by another:413\f[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\f]414or a scalar by an array when there is no src1 :415\f[\texttt{dst(I) = saturate(scale/src2(I))}\f]416417Different channels of multi-channel arrays are processed independently.418419For integer types when src2(I) is zero, dst(I) will also be zero.420421@note In case of floating point data there is no special defined behavior for zero src2(I) values.422Regular floating-point division is used.423Expect correct IEEE-754 behaviour for floating-point data (with NaN, Inf result values).424425@note Saturation is not applied when the output array has the depth CV_32S. You may even get426result of an incorrect sign in the case of overflow.427@param src1 first input array.428@param src2 second input array of the same size and type as src1.429@param scale scalar factor.430@param dst output array of the same size and type as src2.431@param dtype optional depth of the output array; if -1, dst will have depth src2.depth(), but in432case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth().433@sa multiply, add, subtract434*/435CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst,436double scale = 1, int dtype = -1);437438/** @overload */439CV_EXPORTS_W void divide(double scale, InputArray src2,440OutputArray dst, int dtype = -1);441442/** @brief Calculates the sum of a scaled array and another array.443444The function scaleAdd is one of the classical primitive linear algebra operations, known as DAXPY445or SAXPY in [BLAS](http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms). It calculates446the sum of a scaled array and another array:447\f[\texttt{dst} (I)= \texttt{scale} \cdot \texttt{src1} (I) + \texttt{src2} (I)\f]448The function can also be emulated with a matrix expression, for example:449@code{.cpp}450Mat A(3, 3, CV_64F);451...452A.row(0) = A.row(1)*2 + A.row(2);453@endcode454@param src1 first input array.455@param alpha scale factor for the first array.456@param src2 second input array of the same size and type as src1.457@param dst output array of the same size and type as src1.458@sa add, addWeighted, subtract, Mat::dot, Mat::convertTo459*/460CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst);461462/** @example samples/cpp/tutorial_code/HighGUI/AddingImagesTrackbar.cpp463Check @ref tutorial_trackbar "the corresponding tutorial" for more details464*/465466/** @brief Calculates the weighted sum of two arrays.467468The 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, each471channel is processed independently.472The function can be replaced with a matrix expression:473@code{.cpp}474dst = src1*alpha + src2*beta + gamma;475@endcode476@note Saturation is not applied when the output array has the depth CV_32S. You may even get477result 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, dtype485can be set to -1, which will be equivalent to src1.depth().486@sa add, subtract, scaleAdd, Mat::convertTo487*/488CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2,489double beta, double gamma, OutputArray dst, int dtype = -1);490491/** @brief Scales, calculates absolute values, and converts the result to 8-bit.492493On each element of the input array, the function convertScaleAbs494performs three operations sequentially: scaling, taking an absolute495value, 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 channel498independently. When the output is not 8-bit, the operation can be499emulated by calling the Mat::convertTo method (or by using matrix500expressions) and then by calculating an absolute value of the result.501For example:502@code{.cpp}503Mat_<float> A(30,30);504randu(A, Scalar(-100), Scalar(100));505Mat_<float> B = A*5 + 3;506B = abs(B);507// Mat_<float> B = abs(A*5+3) will also do the job,508// but it will allocate a temporary matrix509@endcode510@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,517double alpha = 1, double beta = 0);518519/** @brief Converts an array to half precision floating number.520521This 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 or523CV_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.525526@param src input array.527@param dst output array.528*/529CV_EXPORTS_W void convertFp16(InputArray src, OutputArray dst);530531/** @brief Performs a look-up table transform of an array.532533The function LUT fills the output array with values from the look-up table. Indices of the entries534are taken from the input array. That is, the function processes each element of src as follows:535\f[\texttt{dst} (I) \leftarrow \texttt{lut(src(I) + d)}\f]536where537\f[d = \fork{0}{if \(\texttt{src}\) has depth \(\texttt{CV_8U}\)}{128}{if \(\texttt{src}\) has depth \(\texttt{CV_8S}\)}\f]538@param src input array of 8-bit elements.539@param lut look-up table of 256 elements; in case of multi-channel input array, the table should540either have a single channel (in this case the same table is used for all channels) or the same541number of channels as in the input array.542@param dst output array of the same size and number of channels as src, and the same depth as lut.543@sa convertScaleAbs, Mat::convertTo544*/545CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst);546547/** @brief Calculates the sum of array elements.548549The function cv::sum calculates and returns the sum of array elements,550independently for each channel.551@param src input array that must have from 1 to 4 channels.552@sa countNonZero, mean, meanStdDev, norm, minMaxLoc, reduce553*/554CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src);555556/** @brief Counts non-zero array elements.557558The function returns the number of non-zero elements in src :559\f[\sum _{I: \; \texttt{src} (I) \ne0 } 1\f]560@param src single-channel array.561@sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix562*/563CV_EXPORTS_W int countNonZero( InputArray src );564565/** @brief Returns the list of locations of non-zero pixels566567Given a binary matrix (likely returned from an operation such568as threshold(), compare(), >, ==, etc, return all of569the non-zero indices as a cv::Mat or std::vector<cv::Point> (x,y)570For example:571@code{.cpp}572cv::Mat binaryImage; // input, binary image573cv::Mat locations; // output, locations of non-zero pixels574cv::findNonZero(binaryImage, locations);575576// access pixel coordinates577Point pnt = locations.at<Point>(i);578@endcode579or580@code{.cpp}581cv::Mat binaryImage; // input, binary image582vector<Point> locations; // output, locations of non-zero pixels583cv::findNonZero(binaryImage, locations);584585// access pixel coordinates586Point pnt = locations[i];587@endcode588@param src single-channel array589@param idx the output array, type of cv::Mat or std::vector<Point>, corresponding to non-zero indices in the input590*/591CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx );592593/** @brief Calculates an average (mean) of array elements.594595The function cv::mean calculates the mean value M of array elements,596independently for each channel, and return it:597\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]598When all the mask elements are 0's, the function returns Scalar::all(0)599@param src input array that should have from 1 to 4 channels so that the result can be stored in600Scalar_ .601@param mask optional operation mask.602@sa countNonZero, meanStdDev, norm, minMaxLoc603*/604CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask = noArray());605606/** Calculates a mean and standard deviation of array elements.607608The function cv::meanStdDev calculates the mean and the standard deviation M609of array elements independently for each channel and returns it via the610output parameters:611\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]612When all the mask elements are 0's, the function returns613mean=stddev=Scalar::all(0).614@note The calculated standard deviation is only the diagonal of the615complete normalized covariance matrix. If the full matrix is needed, you616can reshape the multi-channel array M x N to the single-channel array617M\*N x mtx.channels() (only possible when the matrix is continuous) and618then pass the matrix to calcCovarMatrix .619@param src input array that should have from 1 to 4 channels so that the results can be stored in620Scalar_ 's.621@param mean output parameter: calculated mean value.622@param stddev output parameter: calculated standard deviation.623@param mask optional operation mask.624@sa countNonZero, mean, norm, minMaxLoc, calcCovarMatrix625*/626CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev,627InputArray mask=noArray());628629/** @brief Calculates the absolute norm of an array.630631This version of #norm calculates the absolute norm of src1. The type of norm to calculate is specified using #NormTypes.632633As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$.634The \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$635is calculated as follows636\f{align*}637\| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\638\| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\639\| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2640\f}641and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is642\f{align*}643\| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\644\| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\645\| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5.646\f}647The 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$.648It 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$.649650651When the mask parameter is specified and it is not empty, the norm is652653If normType is not specified, #NORM_L2 is used.654calculated only over the region specified by the mask.655656Multi-channel input arrays are treated as single-channel arrays, that is,657the results for all channels are combined.658659Hamming norms can only be calculated with CV_8U depth arrays.660661@param src1 first input array.662@param normType type of the norm (see #NormTypes).663@param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type.664*/665CV_EXPORTS_W double norm(InputArray src1, int normType = NORM_L2, InputArray mask = noArray());666667/** @brief Calculates an absolute difference norm or a relative difference norm.668669This version of cv::norm calculates the absolute difference norm670or the relative difference norm of arrays src1 and src2.671The type of norm to calculate is specified using #NormTypes.672673@param src1 first input array.674@param src2 second input array of the same size and the same type as src1.675@param normType type of the norm (see #NormTypes).676@param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type.677*/678CV_EXPORTS_W double norm(InputArray src1, InputArray src2,679int normType = NORM_L2, InputArray mask = noArray());680/** @overload681@param src first input array.682@param normType type of the norm (see #NormTypes).683*/684CV_EXPORTS double norm( const SparseMat& src, int normType );685686/** @brief Computes the Peak Signal-to-Noise Ratio (PSNR) image quality metric.687688This function calculates the Peak Signal-to-Noise Ratio (PSNR) image quality metric in decibels (dB),689between two input arrays src1 and src2. The arrays must have the same type.690691The PSNR is calculated as follows:692693\f[694\texttt{PSNR} = 10 \cdot \log_{10}{\left( \frac{R^2}{MSE} \right) }695\f]696697where R is the maximum integer value of depth (e.g. 255 in the case of CV_8U data)698and MSE is the mean squared error between the two arrays.699700@param src1 first input array.701@param src2 second input array of the same size as src1.702@param R the maximum pixel value (255 by default)703704*/705CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2, double R=255.);706707/** @brief naive nearest neighbor finder708709see http://en.wikipedia.org/wiki/Nearest_neighbor_search710@todo document711*/712CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2,713OutputArray dist, int dtype, OutputArray nidx,714int normType = NORM_L2, int K = 0,715InputArray mask = noArray(), int update = 0,716bool crosscheck = false);717718/** @brief Normalizes the norm or value range of an array.719720The function cv::normalize normalizes scale and shift the input array elements so that721\f[\| \texttt{dst} \| _{L_p}= \texttt{alpha}\f]722(where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that723\f[\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\f]724725when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be726normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this727sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or728min-max but modify the whole array, you can use norm and Mat::convertTo.729730In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this,731the range transformation for sparse matrices is not allowed since it can shift the zero level.732733Possible usage with some positive example data:734@code{.cpp}735vector<double> positiveData = { 2.0, 8.0, 10.0 };736vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax;737738// Norm to probability (total count)739// sum(numbers) = 20.0740// 2.0 0.1 (2.0/20.0)741// 8.0 0.4 (8.0/20.0)742// 10.0 0.5 (10.0/20.0)743normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1);744745// Norm to unit vector: ||positiveData|| = 1.0746// 2.0 0.15747// 8.0 0.62748// 10.0 0.77749normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2);750751// Norm to max element752// 2.0 0.2 (2.0/10.0)753// 8.0 0.8 (8.0/10.0)754// 10.0 1.0 (10.0/10.0)755normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF);756757// Norm to range [0.0;1.0]758// 2.0 0.0 (shift to left border)759// 8.0 0.75 (6.0/8.0)760// 10.0 1.0 (shift to right border)761normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX);762@endcode763764@param src input array.765@param dst output array of the same size as src .766@param alpha norm value to normalize to or the lower range boundary in case of the range767normalization.768@param beta upper range boundary in case of the range normalization; it is not used for the norm769normalization.770@param norm_type normalization type (see cv::NormTypes).771@param dtype when negative, the output array has the same type as src; otherwise, it has the same772number of channels as src and the depth =CV_MAT_DEPTH(dtype).773@param mask optional operation mask.774@sa norm, Mat::convertTo, SparseMat::convertTo775*/776CV_EXPORTS_W void normalize( InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0,777int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray());778779/** @overload780@param src input array.781@param dst output array of the same size as src .782@param alpha norm value to normalize to or the lower range boundary in case of the range783normalization.784@param normType normalization type (see cv::NormTypes).785*/786CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType );787788/** @brief Finds the global minimum and maximum in an array.789790The function cv::minMaxLoc finds the minimum and maximum element values and their positions. The791extremums are searched across the whole array or, if mask is not an empty array, in the specified792array region.793794The function do not work with multi-channel arrays. If you need to find minimum or maximum795elements across all the channels, use Mat::reshape first to reinterpret the array as796single-channel. Or you may extract the particular channel using either extractImageCOI , or797mixChannels , or split .798@param src input single-channel array.799@param minVal pointer to the returned minimum value; NULL is used if not required.800@param maxVal pointer to the returned maximum value; NULL is used if not required.801@param minLoc pointer to the returned minimum location (in 2D case); NULL is used if not required.802@param maxLoc pointer to the returned maximum location (in 2D case); NULL is used if not required.803@param mask optional mask used to select a sub-array.804@sa max, min, compare, inRange, extractImageCOI, mixChannels, split, Mat::reshape805*/806CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal,807CV_OUT double* maxVal = 0, CV_OUT Point* minLoc = 0,808CV_OUT Point* maxLoc = 0, InputArray mask = noArray());809810811/** @brief Finds the global minimum and maximum in an array812813The function cv::minMaxIdx finds the minimum and maximum element values and their positions. The814extremums are searched across the whole array or, if mask is not an empty array, in the specified815array region. The function does not work with multi-channel arrays. If you need to find minimum or816maximum elements across all the channels, use Mat::reshape first to reinterpret the array as817single-channel. Or you may extract the particular channel using either extractImageCOI , or818mixChannels , or split . In case of a sparse matrix, the minimum is found among non-zero elements819only.820@note When minIdx is not NULL, it must have at least 2 elements (as well as maxIdx), even if src is821a single-row or single-column matrix. In OpenCV (following MATLAB) each array has at least 2822dimensions, i.e. single-column matrix is Mx1 matrix (and therefore minIdx/maxIdx will be823(i1,0)/(i2,0)) and single-row matrix is 1xN matrix (and therefore minIdx/maxIdx will be824(0,j1)/(0,j2)).825@param src input single-channel array.826@param minVal pointer to the returned minimum value; NULL is used if not required.827@param maxVal pointer to the returned maximum value; NULL is used if not required.828@param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required;829Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element830in each dimension are stored there sequentially.831@param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required.832@param mask specified array region833*/834CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal = 0,835int* minIdx = 0, int* maxIdx = 0, InputArray mask = noArray());836837/** @overload838@param a input single-channel array.839@param minVal pointer to the returned minimum value; NULL is used if not required.840@param maxVal pointer to the returned maximum value; NULL is used if not required.841@param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required;842Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element843in each dimension are stored there sequentially.844@param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required.845*/846CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal,847double* maxVal, int* minIdx = 0, int* maxIdx = 0);848849/** @brief Reduces a matrix to a vector.850851The function #reduce reduces the matrix to a vector by treating the matrix rows/columns as a set of8521D vectors and performing the specified operation on the vectors until a single row/column is853obtained. For example, the function can be used to compute horizontal and vertical projections of a854raster image. In case of #REDUCE_MAX and #REDUCE_MIN , the output image should have the same type as the source one.855In case of #REDUCE_SUM and #REDUCE_AVG , the output may have a larger element bit-depth to preserve accuracy.856And multi-channel arrays are also supported in these two reduction modes.857858The following code demonstrates its usage for a single channel matrix.859@snippet snippets/core_reduce.cpp example860861And the following code demonstrates its usage for a two-channel matrix.862@snippet snippets/core_reduce.cpp example2863864@param src input 2D matrix.865@param dst output vector. Its size and type is defined by dim and dtype parameters.866@param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to867a single row. 1 means that the matrix is reduced to a single column.868@param rtype reduction operation that could be one of #ReduceTypes869@param dtype when negative, the output vector will have the same type as the input matrix,870otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()).871@sa repeat872*/873CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype = -1);874875/** @brief Creates one multi-channel array out of several single-channel ones.876877The function cv::merge merges several arrays to make a single multi-channel array. That is, each878element of the output array will be a concatenation of the elements of the input arrays, where879elements of i-th input array are treated as mv[i].channels()-element vectors.880881The function cv::split does the reverse operation. If you need to shuffle channels in some other882advanced way, use cv::mixChannels.883884The following example shows how to merge 3 single channel matrices into a single 3-channel matrix.885@snippet snippets/core_merge.cpp example886887@param mv input array of matrices to be merged; all the matrices in mv must have the same888size and the same depth.889@param count number of input matrices when mv is a plain C array; it must be greater than zero.890@param dst output array of the same size and the same depth as mv[0]; The number of channels will891be equal to the parameter count.892@sa mixChannels, split, Mat::reshape893*/894CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst);895896/** @overload897@param mv input vector of matrices to be merged; all the matrices in mv must have the same898size and the same depth.899@param dst output array of the same size and the same depth as mv[0]; The number of channels will900be the total number of channels in the matrix array.901*/902CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst);903904/** @brief Divides a multi-channel array into several single-channel arrays.905906The function cv::split splits a multi-channel array into separate single-channel arrays:907\f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f]908If you need to extract a single channel or do some other sophisticated channel permutation, use909mixChannels .910911The following example demonstrates how to split a 3-channel matrix into 3 single channel matrices.912@snippet snippets/core_split.cpp example913914@param src input multi-channel array.915@param mvbegin output array; the number of arrays must match src.channels(); the arrays themselves are916reallocated, if needed.917@sa merge, mixChannels, cvtColor918*/919CV_EXPORTS void split(const Mat& src, Mat* mvbegin);920921/** @overload922@param m input multi-channel array.923@param mv output vector of arrays; the arrays themselves are reallocated, if needed.924*/925CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv);926927/** @brief Copies specified channels from input arrays to the specified channels of928output arrays.929930The function cv::mixChannels provides an advanced mechanism for shuffling image channels.931932cv::split,cv::merge,cv::extractChannel,cv::insertChannel and some forms of cv::cvtColor are partial cases of cv::mixChannels.933934In the example below, the code splits a 4-channel BGRA image into a 3-channel BGR (with B and R935channels swapped) and a separate alpha-channel image:936@code{.cpp}937Mat bgra( 100, 100, CV_8UC4, Scalar(255,0,0,255) );938Mat bgr( bgra.rows, bgra.cols, CV_8UC3 );939Mat alpha( bgra.rows, bgra.cols, CV_8UC1 );940941// forming an array of matrices is a quite efficient operation,942// because the matrix data is not copied, only the headers943Mat out[] = { bgr, alpha };944// bgra[0] -> bgr[2], bgra[1] -> bgr[1],945// bgra[2] -> bgr[0], bgra[3] -> alpha[0]946int from_to[] = { 0,2, 1,1, 2,0, 3,3 };947mixChannels( &bgra, 1, out, 2, from_to, 4 );948@endcode949@note Unlike many other new-style C++ functions in OpenCV (see the introduction section and950Mat::create ), cv::mixChannels requires the output arrays to be pre-allocated before calling the951function.952@param src input array or vector of matrices; all of the matrices must have the same size and the953same depth.954@param nsrcs number of matrices in `src`.955@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and956depth must be the same as in `src[0]`.957@param ndsts number of matrices in `dst`.958@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is959a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in960dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to961src[0].channels()-1, the second input image channels are indexed from src[0].channels() to962src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image963channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is964filled with zero .965@param npairs number of index pairs in `fromTo`.966@sa split, merge, extractChannel, insertChannel, cvtColor967*/968CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts,969const int* fromTo, size_t npairs);970971/** @overload972@param src input array or vector of matrices; all of the matrices must have the same size and the973same depth.974@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and975depth must be the same as in src[0].976@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is977a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in978dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to979src[0].channels()-1, the second input image channels are indexed from src[0].channels() to980src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image981channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is982filled with zero .983@param npairs number of index pairs in fromTo.984*/985CV_EXPORTS void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst,986const int* fromTo, size_t npairs);987988/** @overload989@param src input array or vector of matrices; all of the matrices must have the same size and the990same depth.991@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and992depth must be the same as in src[0].993@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is994a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in995dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to996src[0].channels()-1, the second input image channels are indexed from src[0].channels() to997src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image998channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is999filled with zero .1000*/1001CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst,1002const std::vector<int>& fromTo);10031004/** @brief Extracts a single channel from src (coi is 0-based index)1005@param src input array1006@param dst output array1007@param coi index of channel to extract1008@sa mixChannels, split1009*/1010CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi);10111012/** @brief Inserts a single channel to dst (coi is 0-based index)1013@param src input array1014@param dst output array1015@param coi index of channel for insertion1016@sa mixChannels, merge1017*/1018CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi);10191020/** @brief Flips a 2D array around vertical, horizontal, or both axes.10211022The function cv::flip flips the array in one of three different ways (row1023and column indices are 0-based):1024\f[\texttt{dst} _{ij} =1025\left\{1026\begin{array}{l l}1027\texttt{src} _{\texttt{src.rows}-i-1,j} & if\; \texttt{flipCode} = 0 \\1028\texttt{src} _{i, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} > 0 \\1029\texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\1030\end{array}1031\right.\f]1032The example scenarios of using the function are the following:1033* Vertical flipping of the image (flipCode == 0) to switch between1034top-left and bottom-left image origin. This is a typical operation1035in video processing on Microsoft Windows\* OS.1036* Horizontal flipping of the image with the subsequent horizontal1037shift and absolute difference calculation to check for a1038vertical-axis symmetry (flipCode \> 0).1039* Simultaneous horizontal and vertical flipping of the image with1040the subsequent shift and absolute difference calculation to check1041for a central symmetry (flipCode \< 0).1042* Reversing the order of point arrays (flipCode \> 0 or1043flipCode == 0).1044@param src input array.1045@param dst output array of the same size and type as src.1046@param flipCode a flag to specify how to flip the array; 0 means1047flipping around the x-axis and positive value (for example, 1) means1048flipping around y-axis. Negative value (for example, -1) means flipping1049around both axes.1050@sa transpose , repeat , completeSymm1051*/1052CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode);10531054enum RotateFlags {1055ROTATE_90_CLOCKWISE = 0, //!<Rotate 90 degrees clockwise1056ROTATE_180 = 1, //!<Rotate 180 degrees clockwise1057ROTATE_90_COUNTERCLOCKWISE = 2, //!<Rotate 270 degrees clockwise1058};1059/** @brief Rotates a 2D array in multiples of 90 degrees.1060The function cv::rotate rotates the array in one of three different ways:1061* Rotate by 90 degrees clockwise (rotateCode = ROTATE_90_CLOCKWISE).1062* Rotate by 180 degrees clockwise (rotateCode = ROTATE_180).1063* Rotate by 270 degrees clockwise (rotateCode = ROTATE_90_COUNTERCLOCKWISE).1064@param src input array.1065@param dst output array of the same type as src. The size is the same with ROTATE_180,1066and the rows and cols are switched for ROTATE_90_CLOCKWISE and ROTATE_90_COUNTERCLOCKWISE.1067@param rotateCode an enum to specify how to rotate the array; see the enum #RotateFlags1068@sa transpose , repeat , completeSymm, flip, RotateFlags1069*/1070CV_EXPORTS_W void rotate(InputArray src, OutputArray dst, int rotateCode);10711072/** @brief Fills the output array with repeated copies of the input array.10731074The function cv::repeat duplicates the input array one or more times along each of the two axes:1075\f[\texttt{dst} _{ij}= \texttt{src} _{i\mod src.rows, \; j\mod src.cols }\f]1076The second variant of the function is more convenient to use with @ref MatrixExpressions.1077@param src input array to replicate.1078@param ny Flag to specify how many times the `src` is repeated along the1079vertical axis.1080@param nx Flag to specify how many times the `src` is repeated along the1081horizontal axis.1082@param dst output array of the same type as `src`.1083@sa cv::reduce1084*/1085CV_EXPORTS_W void repeat(InputArray src, int ny, int nx, OutputArray dst);10861087/** @overload1088@param src input array to replicate.1089@param ny Flag to specify how many times the `src` is repeated along the1090vertical axis.1091@param nx Flag to specify how many times the `src` is repeated along the1092horizontal axis.1093*/1094CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx);10951096/** @brief Applies horizontal concatenation to given matrices.10971098The function horizontally concatenates two or more cv::Mat matrices (with the same number of rows).1099@code{.cpp}1100cv::Mat matArray[] = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)),1101cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)),1102cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),};11031104cv::Mat out;1105cv::hconcat( matArray, 3, out );1106//out:1107//[1, 2, 3;1108// 1, 2, 3;1109// 1, 2, 3;1110// 1, 2, 3]1111@endcode1112@param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth.1113@param nsrc number of matrices in src.1114@param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src.1115@sa cv::vconcat(const Mat*, size_t, OutputArray), @sa cv::vconcat(InputArrayOfArrays, OutputArray) and @sa cv::vconcat(InputArray, InputArray, OutputArray)1116*/1117CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, OutputArray dst);1118/** @overload1119@code{.cpp}1120cv::Mat_<float> A = (cv::Mat_<float>(3, 2) << 1, 4,11212, 5,11223, 6);1123cv::Mat_<float> B = (cv::Mat_<float>(3, 2) << 7, 10,11248, 11,11259, 12);11261127cv::Mat C;1128cv::hconcat(A, B, C);1129//C:1130//[1, 4, 7, 10;1131// 2, 5, 8, 11;1132// 3, 6, 9, 12]1133@endcode1134@param src1 first input array to be considered for horizontal concatenation.1135@param src2 second input array to be considered for horizontal concatenation.1136@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.1137*/1138CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst);1139/** @overload1140@code{.cpp}1141std::vector<cv::Mat> matrices = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)),1142cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)),1143cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),};11441145cv::Mat out;1146cv::hconcat( matrices, out );1147//out:1148//[1, 2, 3;1149// 1, 2, 3;1150// 1, 2, 3;1151// 1, 2, 3]1152@endcode1153@param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth.1154@param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src.1155same depth.1156*/1157CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst);11581159/** @brief Applies vertical concatenation to given matrices.11601161The function vertically concatenates two or more cv::Mat matrices (with the same number of cols).1162@code{.cpp}1163cv::Mat matArray[] = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)),1164cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)),1165cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),};11661167cv::Mat out;1168cv::vconcat( matArray, 3, out );1169//out:1170//[1, 1, 1, 1;1171// 2, 2, 2, 2;1172// 3, 3, 3, 3]1173@endcode1174@param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth.1175@param nsrc number of matrices in src.1176@param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src.1177@sa cv::hconcat(const Mat*, size_t, OutputArray), @sa cv::hconcat(InputArrayOfArrays, OutputArray) and @sa cv::hconcat(InputArray, InputArray, OutputArray)1178*/1179CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst);1180/** @overload1181@code{.cpp}1182cv::Mat_<float> A = (cv::Mat_<float>(3, 2) << 1, 7,11832, 8,11843, 9);1185cv::Mat_<float> B = (cv::Mat_<float>(3, 2) << 4, 10,11865, 11,11876, 12);11881189cv::Mat C;1190cv::vconcat(A, B, C);1191//C:1192//[1, 7;1193// 2, 8;1194// 3, 9;1195// 4, 10;1196// 5, 11;1197// 6, 12]1198@endcode1199@param src1 first input array to be considered for vertical concatenation.1200@param src2 second input array to be considered for vertical concatenation.1201@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.1202*/1203CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst);1204/** @overload1205@code{.cpp}1206std::vector<cv::Mat> matrices = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)),1207cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)),1208cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),};12091210cv::Mat out;1211cv::vconcat( matrices, out );1212//out:1213//[1, 1, 1, 1;1214// 2, 2, 2, 2;1215// 3, 3, 3, 3]1216@endcode1217@param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth1218@param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src.1219same depth.1220*/1221CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst);12221223/** @brief computes bitwise conjunction of the two arrays (dst = src1 & src2)1224Calculates the per-element bit-wise conjunction of two arrays or an1225array and a scalar.12261227The function cv::bitwise_and calculates the per-element bit-wise logical conjunction for:1228* Two arrays when src1 and src2 have the same size:1229\f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]1230* An array and a scalar when src2 is constructed from Scalar or has1231the same number of elements as `src1.channels()`:1232\f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]1233* A scalar and an array when src1 is constructed from Scalar or has1234the same number of elements as `src2.channels()`:1235\f[\texttt{dst} (I) = \texttt{src1} \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]1236In case of floating-point arrays, their machine-specific bit1237representations (usually IEEE754-compliant) are used for the operation.1238In case of multi-channel arrays, each channel is processed1239independently. In the second and third cases above, the scalar is first1240converted to the array type.1241@param src1 first input array or a scalar.1242@param src2 second input array or a scalar.1243@param dst output array that has the same size and type as the input1244arrays.1245@param mask optional operation mask, 8-bit single channel array, that1246specifies elements of the output array to be changed.1247*/1248CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2,1249OutputArray dst, InputArray mask = noArray());12501251/** @brief Calculates the per-element bit-wise disjunction of two arrays or an1252array and a scalar.12531254The function cv::bitwise_or calculates the per-element bit-wise logical disjunction for:1255* Two arrays when src1 and src2 have the same size:1256\f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]1257* An array and a scalar when src2 is constructed from Scalar or has1258the same number of elements as `src1.channels()`:1259\f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]1260* A scalar and an array when src1 is constructed from Scalar or has1261the same number of elements as `src2.channels()`:1262\f[\texttt{dst} (I) = \texttt{src1} \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]1263In case of floating-point arrays, their machine-specific bit1264representations (usually IEEE754-compliant) are used for the operation.1265In case of multi-channel arrays, each channel is processed1266independently. In the second and third cases above, the scalar is first1267converted to the array type.1268@param src1 first input array or a scalar.1269@param src2 second input array or a scalar.1270@param dst output array that has the same size and type as the input1271arrays.1272@param mask optional operation mask, 8-bit single channel array, that1273specifies elements of the output array to be changed.1274*/1275CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2,1276OutputArray dst, InputArray mask = noArray());12771278/** @brief Calculates the per-element bit-wise "exclusive or" operation on two1279arrays or an array and a scalar.12801281The function cv::bitwise_xor calculates the per-element bit-wise logical "exclusive-or"1282operation for:1283* Two arrays when src1 and src2 have the same size:1284\f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]1285* An array and a scalar when src2 is constructed from Scalar or has1286the same number of elements as `src1.channels()`:1287\f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]1288* A scalar and an array when src1 is constructed from Scalar or has1289the same number of elements as `src2.channels()`:1290\f[\texttt{dst} (I) = \texttt{src1} \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]1291In case of floating-point arrays, their machine-specific bit1292representations (usually IEEE754-compliant) are used for the operation.1293In case of multi-channel arrays, each channel is processed1294independently. In the 2nd and 3rd cases above, the scalar is first1295converted to the array type.1296@param src1 first input array or a scalar.1297@param src2 second input array or a scalar.1298@param dst output array that has the same size and type as the input1299arrays.1300@param mask optional operation mask, 8-bit single channel array, that1301specifies elements of the output array to be changed.1302*/1303CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2,1304OutputArray dst, InputArray mask = noArray());13051306/** @brief Inverts every bit of an array.13071308The function cv::bitwise_not calculates per-element bit-wise inversion of the input1309array:1310\f[\texttt{dst} (I) = \neg \texttt{src} (I)\f]1311In case of a floating-point input array, its machine-specific bit1312representation (usually IEEE754-compliant) is used for the operation. In1313case of multi-channel arrays, each channel is processed independently.1314@param src input array.1315@param dst output array that has the same size and type as the input1316array.1317@param mask optional operation mask, 8-bit single channel array, that1318specifies elements of the output array to be changed.1319*/1320CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst,1321InputArray mask = noArray());13221323/** @brief Calculates the per-element absolute difference between two arrays or between an array and a scalar.13241325The function cv::absdiff calculates:1326* Absolute difference between two arrays when they have the same1327size and type:1328\f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\f]1329* Absolute difference between an array and a scalar when the second1330array is constructed from Scalar or has as many elements as the1331number of channels in `src1`:1332\f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2} |)\f]1333* Absolute difference between a scalar and an array when the first1334array is constructed from Scalar or has as many elements as the1335number of channels in `src2`:1336\f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1} - \texttt{src2}(I) |)\f]1337where I is a multi-dimensional index of array elements. In case of1338multi-channel arrays, each channel is processed independently.1339@note Saturation is not applied when the arrays have the depth CV_32S.1340You may even get a negative value in the case of overflow.1341@param src1 first input array or a scalar.1342@param src2 second input array or a scalar.1343@param dst output array that has the same size and type as input arrays.1344@sa cv::abs(const Mat&)1345*/1346CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst);13471348/** @brief This is an overloaded member function, provided for convenience (python)1349Copies the matrix to another one.1350When 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.1351@param src source matrix.1352@param dst Destination matrix. If it does not have a proper size or type before the operation, it is1353reallocated.1354@param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix1355elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels.1356*/13571358void CV_EXPORTS_W copyTo(InputArray src, OutputArray dst, InputArray mask);1359/** @brief Checks if array elements lie between the elements of two other arrays.13601361The function checks the range as follows:1362- For every element of a single-channel input array:1363\f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0\f]1364- For two-channel arrays:1365\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]1366- and so forth.13671368That is, dst (I) is set to 255 (all 1 -bits) if src (I) is within the1369specified 1D, 2D, 3D, ... box and 0 otherwise.13701371When the lower and/or upper boundary parameters are scalars, the indexes1372(I) at lowerb and upperb in the above formulas should be omitted.1373@param src first input array.1374@param lowerb inclusive lower boundary array or a scalar.1375@param upperb inclusive upper boundary array or a scalar.1376@param dst output array of the same size as src and CV_8U type.1377*/1378CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb,1379InputArray upperb, OutputArray dst);13801381/** @brief Performs the per-element comparison of two arrays or an array and scalar value.13821383The function compares:1384* Elements of two arrays when src1 and src2 have the same size:1385\f[\texttt{dst} (I) = \texttt{src1} (I) \,\texttt{cmpop}\, \texttt{src2} (I)\f]1386* Elements of src1 with a scalar src2 when src2 is constructed from1387Scalar or has a single element:1388\f[\texttt{dst} (I) = \texttt{src1}(I) \,\texttt{cmpop}\, \texttt{src2}\f]1389* src1 with elements of src2 when src1 is constructed from Scalar or1390has a single element:1391\f[\texttt{dst} (I) = \texttt{src1} \,\texttt{cmpop}\, \texttt{src2} (I)\f]1392When the comparison result is true, the corresponding element of output1393array is set to 255. The comparison operations can be replaced with the1394equivalent matrix expressions:1395@code{.cpp}1396Mat dst1 = src1 >= src2;1397Mat dst2 = src1 < 8;1398...1399@endcode1400@param src1 first input array or a scalar; when it is an array, it must have a single channel.1401@param src2 second input array or a scalar; when it is an array, it must have a single channel.1402@param dst output array of type ref CV_8U that has the same size and the same number of channels as1403the input arrays.1404@param cmpop a flag, that specifies correspondence between the arrays (cv::CmpTypes)1405@sa checkRange, min, max, threshold1406*/1407CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop);14081409/** @brief Calculates per-element minimum of two arrays or an array and a scalar.14101411The function cv::min calculates the per-element minimum of two arrays:1412\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f]1413or array and a scalar:1414\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{value} )\f]1415@param src1 first input array.1416@param src2 second input array of the same size and type as src1.1417@param dst output array of the same size and type as src1.1418@sa max, compare, inRange, minMaxLoc1419*/1420CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst);1421/** @overload1422needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)1423*/1424CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst);1425/** @overload1426needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)1427*/1428CV_EXPORTS void min(const UMat& src1, const UMat& src2, UMat& dst);14291430/** @brief Calculates per-element maximum of two arrays or an array and a scalar.14311432The function cv::max calculates the per-element maximum of two arrays:1433\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f]1434or array and a scalar:1435\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{value} )\f]1436@param src1 first input array.1437@param src2 second input array of the same size and type as src1 .1438@param dst output array of the same size and type as src1.1439@sa min, compare, inRange, minMaxLoc, @ref MatrixExpressions1440*/1441CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst);1442/** @overload1443needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)1444*/1445CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst);1446/** @overload1447needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)1448*/1449CV_EXPORTS void max(const UMat& src1, const UMat& src2, UMat& dst);14501451/** @brief Calculates a square root of array elements.14521453The function cv::sqrt calculates a square root of each input array element.1454In case of multi-channel arrays, each channel is processed1455independently. The accuracy is approximately the same as of the built-in1456std::sqrt .1457@param src input floating-point array.1458@param dst output array of the same size and type as src.1459*/1460CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst);14611462/** @brief Raises every array element to a power.14631464The function cv::pow raises every element of the input array to power :1465\f[\texttt{dst} (I) = \fork{\texttt{src}(I)^{power}}{if \(\texttt{power}\) is integer}{|\texttt{src}(I)|^{power}}{otherwise}\f]14661467So, for a non-integer power exponent, the absolute values of input array1468elements are used. However, it is possible to get true values for1469negative values using some extra operations. In the example below,1470computing the 5th root of array src shows:1471@code{.cpp}1472Mat mask = src < 0;1473pow(src, 1./5, dst);1474subtract(Scalar::all(0), dst, dst, mask);1475@endcode1476For some values of power, such as integer values, 0.5 and -0.5,1477specialized faster algorithms are used.14781479Special values (NaN, Inf) are not handled.1480@param src input array.1481@param power exponent of power.1482@param dst output array of the same size and type as src.1483@sa sqrt, exp, log, cartToPolar, polarToCart1484*/1485CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst);14861487/** @brief Calculates the exponent of every array element.14881489The function cv::exp calculates the exponent of every element of the input1490array:1491\f[\texttt{dst} [I] = e^{ src(I) }\f]14921493The maximum relative error is about 7e-6 for single-precision input and1494less than 1e-10 for double-precision input. Currently, the function1495converts denormalized values to zeros on output. Special values (NaN,1496Inf) are not handled.1497@param src input array.1498@param dst output array of the same size and type as src.1499@sa log , cartToPolar , polarToCart , phase , pow , sqrt , magnitude1500*/1501CV_EXPORTS_W void exp(InputArray src, OutputArray dst);15021503/** @brief Calculates the natural logarithm of every array element.15041505The function cv::log calculates the natural logarithm of every element of the input array:1506\f[\texttt{dst} (I) = \log (\texttt{src}(I)) \f]15071508Output on zero, negative and special (NaN, Inf) values is undefined.15091510@param src input array.1511@param dst output array of the same size and type as src .1512@sa exp, cartToPolar, polarToCart, phase, pow, sqrt, magnitude1513*/1514CV_EXPORTS_W void log(InputArray src, OutputArray dst);15151516/** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle.15171518The function cv::polarToCart calculates the Cartesian coordinates of each 2D1519vector represented by the corresponding elements of magnitude and angle:1520\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]15211522The relative accuracy of the estimated coordinates is about 1e-6.1523@param magnitude input floating-point array of magnitudes of 2D vectors;1524it can be an empty matrix (=Mat()), in this case, the function assumes1525that all the magnitudes are =1; if it is not empty, it must have the1526same size and type as angle.1527@param angle input floating-point array of angles of 2D vectors.1528@param x output array of x-coordinates of 2D vectors; it has the same1529size and type as angle.1530@param y output array of y-coordinates of 2D vectors; it has the same1531size and type as angle.1532@param angleInDegrees when true, the input angles are measured in1533degrees, otherwise, they are measured in radians.1534@sa cartToPolar, magnitude, phase, exp, log, pow, sqrt1535*/1536CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle,1537OutputArray x, OutputArray y, bool angleInDegrees = false);15381539/** @brief Calculates the magnitude and angle of 2D vectors.15401541The function cv::cartToPolar calculates either the magnitude, angle, or both1542for every 2D vector (x(I),y(I)):1543\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]15441545The angles are calculated with accuracy about 0.3 degrees. For the point1546(0,0), the angle is set to 0.1547@param x array of x-coordinates; this must be a single-precision or1548double-precision floating-point array.1549@param y array of y-coordinates, that must have the same size and same type as x.1550@param magnitude output array of magnitudes of the same size and type as x.1551@param angle output array of angles that has the same size and type as1552x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees).1553@param angleInDegrees a flag, indicating whether the angles are measured1554in radians (which is by default), or in degrees.1555@sa Sobel, Scharr1556*/1557CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y,1558OutputArray magnitude, OutputArray angle,1559bool angleInDegrees = false);15601561/** @brief Calculates the rotation angle of 2D vectors.15621563The function cv::phase calculates the rotation angle of each 2D vector that1564is formed from the corresponding elements of x and y :1565\f[\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f]15661567The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 ,1568the corresponding angle(I) is set to 0.1569@param x input floating-point array of x-coordinates of 2D vectors.1570@param y input array of y-coordinates of 2D vectors; it must have the1571same size and the same type as x.1572@param angle output array of vector angles; it has the same size and1573same type as x .1574@param angleInDegrees when true, the function calculates the angle in1575degrees, otherwise, they are measured in radians.1576*/1577CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle,1578bool angleInDegrees = false);15791580/** @brief Calculates the magnitude of 2D vectors.15811582The function cv::magnitude calculates the magnitude of 2D vectors formed1583from the corresponding elements of x and y arrays:1584\f[\texttt{dst} (I) = \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}\f]1585@param x floating-point array of x-coordinates of the vectors.1586@param y floating-point array of y-coordinates of the vectors; it must1587have the same size as x.1588@param magnitude output array of the same size and type as x.1589@sa cartToPolar, polarToCart, phase, sqrt1590*/1591CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude);15921593/** @brief Checks every element of an input array for invalid values.15941595The function cv::checkRange checks that every array element is neither NaN nor infinite. When minVal \>1596-DBL_MAX and maxVal \< DBL_MAX, the function also checks that each value is between minVal and1597maxVal. In case of multi-channel arrays, each channel is processed independently. If some values1598are out of range, position of the first outlier is stored in pos (when pos != NULL). Then, the1599function either returns false (when quiet=true) or throws an exception.1600@param a input array.1601@param quiet a flag, indicating whether the functions quietly return false when the array elements1602are out of range or they throw an exception.1603@param pos optional output parameter, when not NULL, must be a pointer to array of src.dims1604elements.1605@param minVal inclusive lower boundary of valid values range.1606@param maxVal exclusive upper boundary of valid values range.1607*/1608CV_EXPORTS_W bool checkRange(InputArray a, bool quiet = true, CV_OUT Point* pos = 0,1609double minVal = -DBL_MAX, double maxVal = DBL_MAX);16101611/** @brief converts NaN's to the given number1612*/1613CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0);16141615/** @brief Performs generalized matrix multiplication.16161617The function cv::gemm performs generalized matrix multiplication similar to the1618gemm functions in BLAS level 3. For example,1619`gemm(src1, src2, alpha, src3, beta, dst, GEMM_1_T + GEMM_3_T)`1620corresponds to1621\f[\texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T\f]16221623In case of complex (two-channel) data, performed a complex matrix1624multiplication.16251626The function can be replaced with a matrix expression. For example, the1627above call can be replaced with:1628@code{.cpp}1629dst = alpha*src1.t()*src2 + beta*src3.t();1630@endcode1631@param src1 first multiplied input matrix that could be real(CV_32FC1,1632CV_64FC1) or complex(CV_32FC2, CV_64FC2).1633@param src2 second multiplied input matrix of the same type as src1.1634@param alpha weight of the matrix product.1635@param src3 third optional delta matrix added to the matrix product; it1636should have the same type as src1 and src2.1637@param beta weight of src3.1638@param dst output matrix; it has the proper size and the same type as1639input matrices.1640@param flags operation flags (cv::GemmFlags)1641@sa mulTransposed , transform1642*/1643CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha,1644InputArray src3, double beta, OutputArray dst, int flags = 0);16451646/** @brief Calculates the product of a matrix and its transposition.16471648The function cv::mulTransposed calculates the product of src and its1649transposition:1650\f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} )^T ( \texttt{src} - \texttt{delta} )\f]1651if aTa=true , and1652\f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} ) ( \texttt{src} - \texttt{delta} )^T\f]1653otherwise. The function is used to calculate the covariance matrix. With1654zero delta, it can be used as a faster substitute for general matrix1655product A\*B when B=A'1656@param src input single-channel matrix. Note that unlike gemm, the1657function can multiply not only floating-point matrices.1658@param dst output square matrix.1659@param aTa Flag specifying the multiplication ordering. See the1660description below.1661@param delta Optional delta matrix subtracted from src before the1662multiplication. When the matrix is empty ( delta=noArray() ), it is1663assumed to be zero, that is, nothing is subtracted. If it has the same1664size as src , it is simply subtracted. Otherwise, it is "repeated" (see1665repeat ) to cover the full src and then subtracted. Type of the delta1666matrix, when it is not empty, must be the same as the type of created1667output matrix. See the dtype parameter description below.1668@param scale Optional scale factor for the matrix product.1669@param dtype Optional type of the output matrix. When it is negative,1670the output matrix will have the same type as src . Otherwise, it will be1671type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F .1672@sa calcCovarMatrix, gemm, repeat, reduce1673*/1674CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa,1675InputArray delta = noArray(),1676double scale = 1, int dtype = -1 );16771678/** @brief Transposes a matrix.16791680The function cv::transpose transposes the matrix src :1681\f[\texttt{dst} (i,j) = \texttt{src} (j,i)\f]1682@note No complex conjugation is done in case of a complex matrix. It1683should be done separately if needed.1684@param src input array.1685@param dst output array of the same type as src.1686*/1687CV_EXPORTS_W void transpose(InputArray src, OutputArray dst);16881689/** @brief Performs the matrix transformation of every array element.16901691The function cv::transform performs the matrix transformation of every1692element of the array src and stores the results in dst :1693\f[\texttt{dst} (I) = \texttt{m} \cdot \texttt{src} (I)\f]1694(when m.cols=src.channels() ), or1695\f[\texttt{dst} (I) = \texttt{m} \cdot [ \texttt{src} (I); 1]\f]1696(when m.cols=src.channels()+1 )16971698Every element of the N -channel array src is interpreted as N -element1699vector that is transformed using the M x N or M x (N+1) matrix m to1700M-element vector - the corresponding element of the output array dst .17011702The function may be used for geometrical transformation of1703N -dimensional points, arbitrary linear color space transformation (such1704as various kinds of RGB to YUV transforms), shuffling the image1705channels, and so forth.1706@param src input array that must have as many channels (1 to 4) as1707m.cols or m.cols-1.1708@param dst output array of the same size and depth as src; it has as1709many channels as m.rows.1710@param m transformation 2x2 or 2x3 floating-point matrix.1711@sa perspectiveTransform, getAffineTransform, estimateAffine2D, warpAffine, warpPerspective1712*/1713CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m );17141715/** @brief Performs the perspective matrix transformation of vectors.17161717The function cv::perspectiveTransform transforms every element of src by1718treating it as a 2D or 3D vector, in the following way:1719\f[(x, y, z) \rightarrow (x'/w, y'/w, z'/w)\f]1720where1721\f[(x', y', z', w') = \texttt{mat} \cdot \begin{bmatrix} x & y & z & 1 \end{bmatrix}\f]1722and1723\f[w = \fork{w'}{if \(w' \ne 0\)}{\infty}{otherwise}\f]17241725Here a 3D vector transformation is shown. In case of a 2D vector1726transformation, the z component is omitted.17271728@note The function transforms a sparse set of 2D or 3D vectors. If you1729want to transform an image using perspective transformation, use1730warpPerspective . If you have an inverse problem, that is, you want to1731compute the most probable perspective transformation out of several1732pairs of corresponding points, you can use getPerspectiveTransform or1733findHomography .1734@param src input two-channel or three-channel floating-point array; each1735element is a 2D/3D vector to be transformed.1736@param dst output array of the same size and type as src.1737@param m 3x3 or 4x4 floating-point transformation matrix.1738@sa transform, warpPerspective, getPerspectiveTransform, findHomography1739*/1740CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m );17411742/** @brief Copies the lower or the upper half of a square matrix to its another half.17431744The function cv::completeSymm copies the lower or the upper half of a square matrix to1745its another half. The matrix diagonal remains unchanged:1746- \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i > j\f$ if1747lowerToUpper=false1748- \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i < j\f$ if1749lowerToUpper=true17501751@param m input-output floating-point square matrix.1752@param lowerToUpper operation flag; if true, the lower half is copied to1753the upper half. Otherwise, the upper half is copied to the lower half.1754@sa flip, transpose1755*/1756CV_EXPORTS_W void completeSymm(InputOutputArray m, bool lowerToUpper = false);17571758/** @brief Initializes a scaled identity matrix.17591760The function cv::setIdentity initializes a scaled identity matrix:1761\f[\texttt{mtx} (i,j)= \fork{\texttt{value}}{ if \(i=j\)}{0}{otherwise}\f]17621763The function can also be emulated using the matrix initializers and the1764matrix expressions:1765@code1766Mat A = Mat::eye(4, 3, CV_32F)*5;1767// A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]]1768@endcode1769@param mtx matrix to initialize (not necessarily square).1770@param s value to assign to diagonal elements.1771@sa Mat::zeros, Mat::ones, Mat::setTo, Mat::operator=1772*/1773CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s = Scalar(1));17741775/** @brief Returns the determinant of a square floating-point matrix.17761777The function cv::determinant calculates and returns the determinant of the1778specified matrix. For small matrices ( mtx.cols=mtx.rows\<=3 ), the1779direct method is used. For larger matrices, the function uses LU1780factorization with partial pivoting.17811782For symmetric positively-determined matrices, it is also possible to use1783eigen decomposition to calculate the determinant.1784@param mtx input matrix that must have CV_32FC1 or CV_64FC1 type and1785square size.1786@sa trace, invert, solve, eigen, @ref MatrixExpressions1787*/1788CV_EXPORTS_W double determinant(InputArray mtx);17891790/** @brief Returns the trace of a matrix.17911792The function cv::trace returns the sum of the diagonal elements of the1793matrix mtx .1794\f[\mathrm{tr} ( \texttt{mtx} ) = \sum _i \texttt{mtx} (i,i)\f]1795@param mtx input matrix.1796*/1797CV_EXPORTS_W Scalar trace(InputArray mtx);17981799/** @brief Finds the inverse or pseudo-inverse of a matrix.18001801The function cv::invert inverts the matrix src and stores the result in dst1802. When the matrix src is singular or non-square, the function calculates1803the pseudo-inverse matrix (the dst matrix) so that norm(src\*dst - I) is1804minimal, where I is an identity matrix.18051806In case of the #DECOMP_LU method, the function returns non-zero value if1807the inverse has been successfully calculated and 0 if src is singular.18081809In case of the #DECOMP_SVD method, the function returns the inverse1810condition number of src (the ratio of the smallest singular value to the1811largest singular value) and 0 if src is singular. The SVD method1812calculates a pseudo-inverse matrix if src is singular.18131814Similarly to #DECOMP_LU, the method #DECOMP_CHOLESKY works only with1815non-singular square matrices that should also be symmetrical and1816positively defined. In this case, the function stores the inverted1817matrix in dst and returns non-zero. Otherwise, it returns 0.18181819@param src input floating-point M x N matrix.1820@param dst output matrix of N x M size and the same type as src.1821@param flags inversion method (cv::DecompTypes)1822@sa solve, SVD1823*/1824CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags = DECOMP_LU);18251826/** @brief Solves one or more linear systems or least-squares problems.18271828The function cv::solve solves a linear system or least-squares problem (the1829latter is possible with SVD or QR methods, or by specifying the flag1830#DECOMP_NORMAL ):1831\f[\texttt{dst} = \arg \min _X \| \texttt{src1} \cdot \texttt{X} - \texttt{src2} \|\f]18321833If #DECOMP_LU or #DECOMP_CHOLESKY method is used, the function returns 11834if src1 (or \f$\texttt{src1}^T\texttt{src1}\f$ ) is non-singular. Otherwise,1835it returns 0. In the latter case, dst is not valid. Other methods find a1836pseudo-solution in case of a singular left-hand side part.18371838@note If you want to find a unity-norm solution of an under-defined1839singular system \f$\texttt{src1}\cdot\texttt{dst}=0\f$ , the function solve1840will not do the work. Use SVD::solveZ instead.18411842@param src1 input matrix on the left-hand side of the system.1843@param src2 input matrix on the right-hand side of the system.1844@param dst output solution.1845@param flags solution (matrix inversion) method (#DecompTypes)1846@sa invert, SVD, eigen1847*/1848CV_EXPORTS_W bool solve(InputArray src1, InputArray src2,1849OutputArray dst, int flags = DECOMP_LU);18501851/** @brief Sorts each row or each column of a matrix.18521853The function cv::sort sorts each matrix row or each matrix column in1854ascending or descending order. So you should pass two operation flags to1855get desired behaviour. If you want to sort matrix rows or columns1856lexicographically, you can use STL std::sort generic function with the1857proper comparison predicate.18581859@param src input single-channel array.1860@param dst output array of the same size and type as src.1861@param flags operation flags, a combination of #SortFlags1862@sa sortIdx, randShuffle1863*/1864CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags);18651866/** @brief Sorts each row or each column of a matrix.18671868The function cv::sortIdx sorts each matrix row or each matrix column in the1869ascending or descending order. So you should pass two operation flags to1870get desired behaviour. Instead of reordering the elements themselves, it1871stores the indices of sorted elements in the output array. For example:1872@code1873Mat A = Mat::eye(3,3,CV_32F), B;1874sortIdx(A, B, SORT_EVERY_ROW + SORT_ASCENDING);1875// B will probably contain1876// (because of equal elements in A some permutations are possible):1877// [[1, 2, 0], [0, 2, 1], [0, 1, 2]]1878@endcode1879@param src input single-channel array.1880@param dst output integer array of the same size as src.1881@param flags operation flags that could be a combination of cv::SortFlags1882@sa sort, randShuffle1883*/1884CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags);18851886/** @brief Finds the real roots of a cubic equation.18871888The function solveCubic finds the real roots of a cubic equation:1889- if coeffs is a 4-element vector:1890\f[\texttt{coeffs} [0] x^3 + \texttt{coeffs} [1] x^2 + \texttt{coeffs} [2] x + \texttt{coeffs} [3] = 0\f]1891- if coeffs is a 3-element vector:1892\f[x^3 + \texttt{coeffs} [0] x^2 + \texttt{coeffs} [1] x + \texttt{coeffs} [2] = 0\f]18931894The roots are stored in the roots array.1895@param coeffs equation coefficients, an array of 3 or 4 elements.1896@param roots output array of real roots that has 1 or 3 elements.1897@return number of real roots. It can be 0, 1 or 2.1898*/1899CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots);19001901/** @brief Finds the real or complex roots of a polynomial equation.19021903The function cv::solvePoly finds real and complex roots of a polynomial equation:1904\f[\texttt{coeffs} [n] x^{n} + \texttt{coeffs} [n-1] x^{n-1} + ... + \texttt{coeffs} [1] x + \texttt{coeffs} [0] = 0\f]1905@param coeffs array of polynomial coefficients.1906@param roots output (complex) array of roots.1907@param maxIters maximum number of iterations the algorithm does.1908*/1909CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters = 300);19101911/** @brief Calculates eigenvalues and eigenvectors of a symmetric matrix.19121913The function cv::eigen calculates just eigenvalues, or eigenvalues and eigenvectors of the symmetric1914matrix src:1915@code1916src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t()1917@endcode19181919@note Use cv::eigenNonSymmetric for calculation of real eigenvalues and eigenvectors of non-symmetric matrix.19201921@param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical1922(src ^T^ == src).1923@param eigenvalues output vector of eigenvalues of the same type as src; the eigenvalues are stored1924in the descending order.1925@param eigenvectors output matrix of eigenvectors; it has the same size and type as src; the1926eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding1927eigenvalues.1928@sa eigenNonSymmetric, completeSymm , PCA1929*/1930CV_EXPORTS_W bool eigen(InputArray src, OutputArray eigenvalues,1931OutputArray eigenvectors = noArray());19321933/** @brief Calculates eigenvalues and eigenvectors of a non-symmetric matrix (real eigenvalues only).19341935@note Assumes real eigenvalues.19361937The function calculates eigenvalues and eigenvectors (optional) of the square matrix src:1938@code1939src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t()1940@endcode19411942@param src input matrix (CV_32FC1 or CV_64FC1 type).1943@param eigenvalues output vector of eigenvalues (type is the same type as src).1944@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.1945@sa eigen1946*/1947CV_EXPORTS_W void eigenNonSymmetric(InputArray src, OutputArray eigenvalues,1948OutputArray eigenvectors);19491950/** @brief Calculates the covariance matrix of a set of vectors.19511952The function cv::calcCovarMatrix calculates the covariance matrix and, optionally, the mean vector of1953the set of input vectors.1954@param samples samples stored as separate matrices1955@param nsamples number of samples1956@param covar output covariance matrix of the type ctype and square size.1957@param mean input or output (depending on the flags) array as the average value of the input vectors.1958@param flags operation flags as a combination of #CovarFlags1959@param ctype type of the matrixl; it equals 'CV_64F' by default.1960@sa PCA, mulTransposed, Mahalanobis1961@todo InputArrayOfArrays1962*/1963CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean,1964int flags, int ctype = CV_64F);19651966/** @overload1967@note use #COVAR_ROWS or #COVAR_COLS flag1968@param samples samples stored as rows/columns of a single matrix.1969@param covar output covariance matrix of the type ctype and square size.1970@param mean input or output (depending on the flags) array as the average value of the input vectors.1971@param flags operation flags as a combination of #CovarFlags1972@param ctype type of the matrixl; it equals 'CV_64F' by default.1973*/1974CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar,1975InputOutputArray mean, int flags, int ctype = CV_64F);19761977/** wrap PCA::operator() */1978CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean,1979OutputArray eigenvectors, int maxComponents = 0);19801981/** wrap PCA::operator() and add eigenvalues output parameter */1982CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean,1983OutputArray eigenvectors, OutputArray eigenvalues,1984int maxComponents = 0);19851986/** wrap PCA::operator() */1987CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean,1988OutputArray eigenvectors, double retainedVariance);19891990/** wrap PCA::operator() and add eigenvalues output parameter */1991CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean,1992OutputArray eigenvectors, OutputArray eigenvalues,1993double retainedVariance);19941995/** wrap PCA::project */1996CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean,1997InputArray eigenvectors, OutputArray result);19981999/** wrap PCA::backProject */2000CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean,2001InputArray eigenvectors, OutputArray result);20022003/** wrap SVD::compute */2004CV_EXPORTS_W void SVDecomp( InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags = 0 );20052006/** wrap SVD::backSubst */2007CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt,2008InputArray rhs, OutputArray dst );20092010/** @brief Calculates the Mahalanobis distance between two vectors.20112012The function cv::Mahalanobis calculates and returns the weighted distance between two vectors:2013\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]2014The covariance matrix may be calculated using the #calcCovarMatrix function and then inverted using2015the invert function (preferably using the #DECOMP_SVD method, as the most accurate).2016@param v1 first 1D input vector.2017@param v2 second 1D input vector.2018@param icovar inverse covariance matrix.2019*/2020CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar);20212022/** @brief Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array.20232024The function cv::dft performs one of the following:2025- Forward the Fourier transform of a 1D vector of N elements:2026\f[Y = F^{(N)} \cdot X,\f]2027where \f$F^{(N)}_{jk}=\exp(-2\pi i j k/N)\f$ and \f$i=\sqrt{-1}\f$2028- Inverse the Fourier transform of a 1D vector of N elements:2029\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]2030where \f$F^*=\left(\textrm{Re}(F^{(N)})-\textrm{Im}(F^{(N)})\right)^T\f$2031- Forward the 2D Fourier transform of a M x N matrix:2032\f[Y = F^{(M)} \cdot X \cdot F^{(N)}\f]2033- Inverse the 2D Fourier transform of a M x N matrix:2034\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]20352036In case of real (single-channel) data, the output spectrum of the forward Fourier transform or input2037spectrum of the inverse Fourier transform can be represented in a packed format called *CCS*2038(complex-conjugate-symmetrical). It was borrowed from IPL (Intel\* Image Processing Library). Here2039is how 2D *CCS* spectrum looks:2040\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]20412042In case of 1D transform of a real vector, the output looks like the first row of the matrix above.20432044So, the function chooses an operation mode depending on the flags and size of the input array:2045- If #DFT_ROWS is set or the input array has a single row or single column, the function2046performs a 1D forward or inverse transform of each row of a matrix when #DFT_ROWS is set.2047Otherwise, it performs a 2D transform.2048- If the input array is real and #DFT_INVERSE is not set, the function performs a forward 1D or20492D transform:2050- When #DFT_COMPLEX_OUTPUT is set, the output is a complex matrix of the same size as2051input.2052- When #DFT_COMPLEX_OUTPUT is not set, the output is a real matrix of the same size as2053input. In case of 2D transform, it uses the packed format as shown above. In case of a2054single 1D transform, it looks like the first row of the matrix above. In case of2055multiple 1D transforms (when using the #DFT_ROWS flag), each row of the output matrix2056looks like the first row of the matrix above.2057- If the input array is complex and either #DFT_INVERSE or #DFT_REAL_OUTPUT are not set, the2058output is a complex array of the same size as input. The function performs a forward or2059inverse 1D or 2D transform of the whole input array or each row of the input array2060independently, depending on the flags DFT_INVERSE and DFT_ROWS.2061- When #DFT_INVERSE is set and the input array is real, or it is complex but #DFT_REAL_OUTPUT2062is set, the output is a real array of the same size as input. The function performs a 1D or 2D2063inverse transformation of the whole input array or each individual row, depending on the flags2064#DFT_INVERSE and #DFT_ROWS.20652066If #DFT_SCALE is set, the scaling is done after the transformation.20672068Unlike dct , the function supports arrays of arbitrary size. But only those arrays are processed2069efficiently, whose sizes can be factorized in a product of small prime numbers (2, 3, and 5 in the2070current implementation). Such an efficient DFT size can be calculated using the getOptimalDFTSize2071method.20722073The sample below illustrates how to calculate a DFT-based convolution of two 2D real arrays:2074@code2075void convolveDFT(InputArray A, InputArray B, OutputArray C)2076{2077// reallocate the output array if needed2078C.create(abs(A.rows - B.rows)+1, abs(A.cols - B.cols)+1, A.type());2079Size dftSize;2080// calculate the size of DFT transform2081dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1);2082dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1);20832084// allocate temporary buffers and initialize them with 0's2085Mat tempA(dftSize, A.type(), Scalar::all(0));2086Mat tempB(dftSize, B.type(), Scalar::all(0));20872088// copy A and B to the top-left corners of tempA and tempB, respectively2089Mat roiA(tempA, Rect(0,0,A.cols,A.rows));2090A.copyTo(roiA);2091Mat roiB(tempB, Rect(0,0,B.cols,B.rows));2092B.copyTo(roiB);20932094// now transform the padded A & B in-place;2095// use "nonzeroRows" hint for faster processing2096dft(tempA, tempA, 0, A.rows);2097dft(tempB, tempB, 0, B.rows);20982099// multiply the spectrums;2100// the function handles packed spectrum representations well2101mulSpectrums(tempA, tempB, tempA);21022103// transform the product back from the frequency domain.2104// Even though all the result rows will be non-zero,2105// you need only the first C.rows of them, and thus you2106// pass nonzeroRows == C.rows2107dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows);21082109// now copy the result back to C.2110tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C);21112112// all the temporary buffers will be deallocated automatically2113}2114@endcode2115To optimize this sample, consider the following approaches:2116- Since nonzeroRows != 0 is passed to the forward transform calls and since A and B are copied to2117the top-left corners of tempA and tempB, respectively, it is not necessary to clear the whole2118tempA and tempB. It is only necessary to clear the tempA.cols - A.cols ( tempB.cols - B.cols)2119rightmost columns of the matrices.2120- This DFT-based convolution does not have to be applied to the whole big arrays, especially if B2121is significantly smaller than A or vice versa. Instead, you can calculate convolution by parts.2122To do this, you need to split the output array C into multiple tiles. For each tile, estimate2123which parts of A and B are required to calculate convolution in this tile. If the tiles in C are2124too small, the speed will decrease a lot because of repeated work. In the ultimate case, when2125each tile in C is a single pixel, the algorithm becomes equivalent to the naive convolution2126algorithm. If the tiles are too big, the temporary arrays tempA and tempB become too big and2127there is also a slowdown because of bad cache locality. So, there is an optimal tile size2128somewhere in the middle.2129- If different tiles in C can be calculated in parallel and, thus, the convolution is done by2130parts, the loop can be threaded.21312132All of the above improvements have been implemented in #matchTemplate and #filter2D . Therefore, by2133using them, you can get the performance even better than with the above theoretically optimal2134implementation. Though, those two functions actually calculate cross-correlation, not convolution,2135so you need to "flip" the second convolution operand B vertically and horizontally using flip .2136@note2137- An example using the discrete fourier transform can be found at2138opencv_source_code/samples/cpp/dft.cpp2139- (Python) An example using the dft functionality to perform Wiener deconvolution can be found2140at opencv_source/samples/python/deconvolution.py2141- (Python) An example rearranging the quadrants of a Fourier image can be found at2142opencv_source/samples/python/dft.py2143@param src input array that could be real or complex.2144@param dst output array whose size and type depends on the flags .2145@param flags transformation flags, representing a combination of the #DftFlags2146@param nonzeroRows when the parameter is not zero, the function assumes that only the first2147nonzeroRows rows of the input array (#DFT_INVERSE is not set) or only the first nonzeroRows of the2148output array (#DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the2149rows more efficiently and save some time; this technique is very useful for calculating array2150cross-correlation or convolution using DFT.2151@sa dct , getOptimalDFTSize , mulSpectrums, filter2D , matchTemplate , flip , cartToPolar ,2152magnitude , phase2153*/2154CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0);21552156/** @brief Calculates the inverse Discrete Fourier Transform of a 1D or 2D array.21572158idft(src, dst, flags) is equivalent to dft(src, dst, flags | #DFT_INVERSE) .2159@note None of dft and idft scales the result by default. So, you should pass #DFT_SCALE to one of2160dft or idft explicitly to make these transforms mutually inverse.2161@sa dft, dct, idct, mulSpectrums, getOptimalDFTSize2162@param src input floating-point real or complex array.2163@param dst output array whose size and type depend on the flags.2164@param flags operation flags (see dft and #DftFlags).2165@param nonzeroRows number of dst rows to process; the rest of the rows have undefined content (see2166the convolution sample in dft description.2167*/2168CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0);21692170/** @brief Performs a forward or inverse discrete Cosine transform of 1D or 2D array.21712172The function cv::dct performs a forward or inverse discrete Cosine transform (DCT) of a 1D or 2D2173floating-point array:2174- Forward Cosine transform of a 1D vector of N elements:2175\f[Y = C^{(N)} \cdot X\f]2176where2177\f[C^{(N)}_{jk}= \sqrt{\alpha_j/N} \cos \left ( \frac{\pi(2k+1)j}{2N} \right )\f]2178and2179\f$\alpha_0=1\f$, \f$\alpha_j=2\f$ for *j \> 0*.2180- Inverse Cosine transform of a 1D vector of N elements:2181\f[X = \left (C^{(N)} \right )^{-1} \cdot Y = \left (C^{(N)} \right )^T \cdot Y\f]2182(since \f$C^{(N)}\f$ is an orthogonal matrix, \f$C^{(N)} \cdot \left(C^{(N)}\right)^T = I\f$ )2183- Forward 2D Cosine transform of M x N matrix:2184\f[Y = C^{(N)} \cdot X \cdot \left (C^{(N)} \right )^T\f]2185- Inverse 2D Cosine transform of M x N matrix:2186\f[X = \left (C^{(N)} \right )^T \cdot X \cdot C^{(N)}\f]21872188The function chooses the mode of operation by looking at the flags and size of the input array:2189- If (flags & #DCT_INVERSE) == 0 , the function does a forward 1D or 2D transform. Otherwise, it2190is an inverse 1D or 2D transform.2191- If (flags & #DCT_ROWS) != 0 , the function performs a 1D transform of each row.2192- If the array is a single column or a single row, the function performs a 1D transform.2193- If none of the above is true, the function performs a 2D transform.21942195@note Currently dct supports even-size arrays (2, 4, 6 ...). For data analysis and approximation, you2196can pad the array when necessary.2197Also, the function performance depends very much, and not monotonically, on the array size (see2198getOptimalDFTSize ). In the current implementation DCT of a vector of size N is calculated via DFT2199of a vector of size N/2 . Thus, the optimal DCT size N1 \>= N can be calculated as:2200@code2201size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); }2202N1 = getOptimalDCTSize(N);2203@endcode2204@param src input floating-point array.2205@param dst output array of the same size and type as src .2206@param flags transformation flags as a combination of cv::DftFlags (DCT_*)2207@sa dft , getOptimalDFTSize , idct2208*/2209CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags = 0);22102211/** @brief Calculates the inverse Discrete Cosine Transform of a 1D or 2D array.22122213idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE).2214@param src input floating-point single-channel array.2215@param dst output array of the same size and type as src.2216@param flags operation flags.2217@sa dct, dft, idft, getOptimalDFTSize2218*/2219CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags = 0);22202221/** @brief Performs the per-element multiplication of two Fourier spectrums.22222223The function cv::mulSpectrums performs the per-element multiplication of the two CCS-packed or complex2224matrices that are results of a real or complex Fourier transform.22252226The function, together with dft and idft , may be used to calculate convolution (pass conjB=false )2227or correlation (pass conjB=true ) of two arrays rapidly. When the arrays are complex, they are2228simply multiplied (per element) with an optional conjugation of the second-array elements. When the2229arrays are real, they are assumed to be CCS-packed (see dft for details).2230@param a first input array.2231@param b second input array of the same size and type as src1 .2232@param c output array of the same size and type as src1 .2233@param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that2234each 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.2235@param conjB optional flag that conjugates the second input array before the multiplication (true)2236or not (false).2237*/2238CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c,2239int flags, bool conjB = false);22402241/** @brief Returns the optimal DFT size for a given vector size.22422243DFT performance is not a monotonic function of a vector size. Therefore, when you calculate2244convolution of two arrays or perform the spectral analysis of an array, it usually makes sense to2245pad the input data with zeros to get a bit larger array that can be transformed much faster than the2246original one. Arrays whose size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process.2247Though, the arrays whose size is a product of 2's, 3's, and 5's (for example, 300 = 5\*5\*3\*2\*2)2248are also processed quite efficiently.22492250The function cv::getOptimalDFTSize returns the minimum number N that is greater than or equal to vecsize2251so that the DFT of a vector of size N can be processed efficiently. In the current implementation N2252= 2 ^p^ \* 3 ^q^ \* 5 ^r^ for some integer p, q, r.22532254The function returns a negative number if vecsize is too large (very close to INT_MAX ).22552256While the function cannot be used directly to estimate the optimal vector size for DCT transform2257(since the current DCT implementation supports only even-size vectors), it can be easily processed2258as getOptimalDFTSize((vecsize+1)/2)\*2.2259@param vecsize vector size.2260@sa dft , dct , idft , idct , mulSpectrums2261*/2262CV_EXPORTS_W int getOptimalDFTSize(int vecsize);22632264/** @brief Returns the default random number generator.22652266The function cv::theRNG returns the default random number generator. For each thread, there is a2267separate random number generator, so you can use the function safely in multi-thread environments.2268If you just need to get a single random number using this generator or initialize an array, you can2269use randu or randn instead. But if you are going to generate many random numbers inside a loop, it2270is much faster to use this function to retrieve the generator and then use RNG::operator _Tp() .2271@sa RNG, randu, randn2272*/2273CV_EXPORTS RNG& theRNG();22742275/** @brief Sets state of default random number generator.22762277The function cv::setRNGSeed sets state of default random number generator to custom value.2278@param seed new state for default random number generator2279@sa RNG, randu, randn2280*/2281CV_EXPORTS_W void setRNGSeed(int seed);22822283/** @brief Generates a single uniformly-distributed random number or an array of random numbers.22842285Non-template variant of the function fills the matrix dst with uniformly-distributed2286random numbers from the specified range:2287\f[\texttt{low} _c \leq \texttt{dst} (I)_c < \texttt{high} _c\f]2288@param dst output array of random numbers; the array must be pre-allocated.2289@param low inclusive lower boundary of the generated random numbers.2290@param high exclusive upper boundary of the generated random numbers.2291@sa RNG, randn, theRNG2292*/2293CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high);22942295/** @brief Fills the array with normally distributed random numbers.22962297The function cv::randn fills the matrix dst with normally distributed random numbers with the specified2298mean vector and the standard deviation matrix. The generated random numbers are clipped to fit the2299value range of the output array data type.2300@param dst output array of random numbers; the array must be pre-allocated and have 1 to 4 channels.2301@param mean mean value (expectation) of the generated random numbers.2302@param stddev standard deviation of the generated random numbers; it can be either a vector (in2303which case a diagonal standard deviation matrix is assumed) or a square matrix.2304@sa RNG, randu2305*/2306CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev);23072308/** @brief Shuffles the array elements randomly.23092310The function cv::randShuffle shuffles the specified 1D array by randomly choosing pairs of elements and2311swapping them. The number of such swap operations will be dst.rows\*dst.cols\*iterFactor .2312@param dst input/output numerical 1D array.2313@param iterFactor scale factor that determines the number of random swap operations (see the details2314below).2315@param rng optional random number generator used for shuffling; if it is zero, theRNG () is used2316instead.2317@sa RNG, sort2318*/2319CV_EXPORTS_W void randShuffle(InputOutputArray dst, double iterFactor = 1., RNG* rng = 0);23202321/** @brief Principal Component Analysis23222323The class is used to calculate a special basis for a set of vectors. The2324basis will consist of eigenvectors of the covariance matrix calculated2325from the input set of vectors. The class %PCA can also transform2326vectors to/from the new coordinate space defined by the basis. Usually,2327in this new coordinate system, each vector from the original set (and2328any linear combination of such vectors) can be quite accurately2329approximated by taking its first few components, corresponding to the2330eigenvectors of the largest eigenvalues of the covariance matrix.2331Geometrically it means that you calculate a projection of the vector to2332a subspace formed by a few eigenvectors corresponding to the dominant2333eigenvalues of the covariance matrix. And usually such a projection is2334very close to the original vector. So, you can represent the original2335vector from a high-dimensional space with a much shorter vector2336consisting of the projected vector's coordinates in the subspace. Such a2337transformation is also known as Karhunen-Loeve Transform, or KLT.2338See http://en.wikipedia.org/wiki/Principal_component_analysis23392340The sample below is the function that takes two matrices. The first2341function stores a set of vectors (a row per vector) that is used to2342calculate PCA. The second function stores another "test" set of vectors2343(a row per vector). First, these vectors are compressed with PCA, then2344reconstructed back, and then the reconstruction error norm is computed2345and printed for each vector. :23462347@code{.cpp}2348using namespace cv;23492350PCA compressPCA(const Mat& pcaset, int maxComponents,2351const Mat& testset, Mat& compressed)2352{2353PCA pca(pcaset, // pass the data2354Mat(), // we do not have a pre-computed mean vector,2355// so let the PCA engine to compute it2356PCA::DATA_AS_ROW, // indicate that the vectors2357// are stored as matrix rows2358// (use PCA::DATA_AS_COL if the vectors are2359// the matrix columns)2360maxComponents // specify, how many principal components to retain2361);2362// if there is no test data, just return the computed basis, ready-to-use2363if( !testset.data )2364return pca;2365CV_Assert( testset.cols == pcaset.cols );23662367compressed.create(testset.rows, maxComponents, testset.type());23682369Mat reconstructed;2370for( int i = 0; i < testset.rows; i++ )2371{2372Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed;2373// compress the vector, the result will be stored2374// in the i-th row of the output matrix2375pca.project(vec, coeffs);2376// and then reconstruct it2377pca.backProject(coeffs, reconstructed);2378// and measure the error2379printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2));2380}2381return pca;2382}2383@endcode2384@sa calcCovarMatrix, mulTransposed, SVD, dft, dct2385*/2386class CV_EXPORTS PCA2387{2388public:2389enum Flags { DATA_AS_ROW = 0, //!< indicates that the input samples are stored as matrix rows2390DATA_AS_COL = 1, //!< indicates that the input samples are stored as matrix columns2391USE_AVG = 2 //!2392};23932394/** @brief default constructor23952396The default constructor initializes an empty %PCA structure. The other2397constructors initialize the structure and call PCA::operator()().2398*/2399PCA();24002401/** @overload2402@param data input samples stored as matrix rows or matrix columns.2403@param mean optional mean value; if the matrix is empty (@c noArray()),2404the mean is computed from the data.2405@param flags operation flags; currently the parameter is only used to2406specify the data layout (PCA::Flags)2407@param maxComponents maximum number of components that %PCA should2408retain; by default, all the components are retained.2409*/2410PCA(InputArray data, InputArray mean, int flags, int maxComponents = 0);24112412/** @overload2413@param data input samples stored as matrix rows or matrix columns.2414@param mean optional mean value; if the matrix is empty (noArray()),2415the mean is computed from the data.2416@param flags operation flags; currently the parameter is only used to2417specify the data layout (PCA::Flags)2418@param retainedVariance Percentage of variance that PCA should retain.2419Using this parameter will let the PCA decided how many components to2420retain but it will always keep at least 2.2421*/2422PCA(InputArray data, InputArray mean, int flags, double retainedVariance);24232424/** @brief performs %PCA24252426The operator performs %PCA of the supplied dataset. It is safe to reuse2427the same PCA structure for multiple datasets. That is, if the structure2428has been previously used with another dataset, the existing internal2429data is reclaimed and the new @ref eigenvalues, @ref eigenvectors and @ref2430mean are allocated and computed.24312432The computed @ref eigenvalues are sorted from the largest to the smallest and2433the corresponding @ref eigenvectors are stored as eigenvectors rows.24342435@param data input samples stored as the matrix rows or as the matrix2436columns.2437@param mean optional mean value; if the matrix is empty (noArray()),2438the mean is computed from the data.2439@param flags operation flags; currently the parameter is only used to2440specify the data layout. (Flags)2441@param maxComponents maximum number of components that PCA should2442retain; by default, all the components are retained.2443*/2444PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents = 0);24452446/** @overload2447@param data input samples stored as the matrix rows or as the matrix2448columns.2449@param mean optional mean value; if the matrix is empty (noArray()),2450the mean is computed from the data.2451@param flags operation flags; currently the parameter is only used to2452specify the data layout. (PCA::Flags)2453@param retainedVariance Percentage of variance that %PCA should retain.2454Using this parameter will let the %PCA decided how many components to2455retain but it will always keep at least 2.2456*/2457PCA& operator()(InputArray data, InputArray mean, int flags, double retainedVariance);24582459/** @brief Projects vector(s) to the principal component subspace.24602461The methods project one or more vectors to the principal component2462subspace, where each vector projection is represented by coefficients in2463the principal component basis. The first form of the method returns the2464matrix that the second form writes to the result. So the first form can2465be used as a part of expression while the second form can be more2466efficient in a processing loop.2467@param vec input vector(s); must have the same dimensionality and the2468same layout as the input data used at %PCA phase, that is, if2469DATA_AS_ROW are specified, then `vec.cols==data.cols`2470(vector dimensionality) and `vec.rows` is the number of vectors to2471project, and the same is true for the PCA::DATA_AS_COL case.2472*/2473Mat project(InputArray vec) const;24742475/** @overload2476@param vec input vector(s); must have the same dimensionality and the2477same layout as the input data used at PCA phase, that is, if2478DATA_AS_ROW are specified, then `vec.cols==data.cols`2479(vector dimensionality) and `vec.rows` is the number of vectors to2480project, and the same is true for the PCA::DATA_AS_COL case.2481@param result output vectors; in case of PCA::DATA_AS_COL, the2482output matrix has as many columns as the number of input vectors, this2483means that `result.cols==vec.cols` and the number of rows match the2484number of principal components (for example, `maxComponents` parameter2485passed to the constructor).2486*/2487void project(InputArray vec, OutputArray result) const;24882489/** @brief Reconstructs vectors from their PC projections.24902491The methods are inverse operations to PCA::project. They take PC2492coordinates of projected vectors and reconstruct the original vectors.2493Unless all the principal components have been retained, the2494reconstructed vectors are different from the originals. But typically,2495the difference is small if the number of components is large enough (but2496still much smaller than the original vector dimensionality). As a2497result, PCA is used.2498@param vec coordinates of the vectors in the principal component2499subspace, the layout and size are the same as of PCA::project output2500vectors.2501*/2502Mat backProject(InputArray vec) const;25032504/** @overload2505@param vec coordinates of the vectors in the principal component2506subspace, the layout and size are the same as of PCA::project output2507vectors.2508@param result reconstructed vectors; the layout and size are the same as2509of PCA::project input vectors.2510*/2511void backProject(InputArray vec, OutputArray result) const;25122513/** @brief write PCA objects25142515Writes @ref eigenvalues @ref eigenvectors and @ref mean to specified FileStorage2516*/2517void write(FileStorage& fs) const;25182519/** @brief load PCA objects25202521Loads @ref eigenvalues @ref eigenvectors and @ref mean from specified FileNode2522*/2523void read(const FileNode& fn);25242525Mat eigenvectors; //!< eigenvectors of the covariation matrix2526Mat eigenvalues; //!< eigenvalues of the covariation matrix2527Mat mean; //!< mean value subtracted before the projection and added after the back projection2528};25292530/** @example samples/cpp/pca.cpp2531An example using %PCA for dimensionality reduction while maintaining an amount of variance2532*/25332534/** @example samples/cpp/tutorial_code/ml/introduction_to_pca/introduction_to_pca.cpp2535Check @ref tutorial_introduction_to_pca "the corresponding tutorial" for more details2536*/25372538/**2539@brief Linear Discriminant Analysis2540@todo document this class2541*/2542class CV_EXPORTS LDA2543{2544public:2545/** @brief constructor2546Initializes a LDA with num_components (default 0).2547*/2548explicit LDA(int num_components = 0);25492550/** Initializes and performs a Discriminant Analysis with Fisher's2551Optimization Criterion on given data in src and corresponding labels2552in labels. If 0 (or less) number of components are given, they are2553automatically determined for given data in computation.2554*/2555LDA(InputArrayOfArrays src, InputArray labels, int num_components = 0);25562557/** Serializes this object to a given filename.2558*/2559void save(const String& filename) const;25602561/** Deserializes this object from a given filename.2562*/2563void load(const String& filename);25642565/** Serializes this object to a given cv::FileStorage.2566*/2567void save(FileStorage& fs) const;25682569/** Deserializes this object from a given cv::FileStorage.2570*/2571void load(const FileStorage& node);25722573/** destructor2574*/2575~LDA();25762577/** Compute the discriminants for data in src (row aligned) and labels.2578*/2579void compute(InputArrayOfArrays src, InputArray labels);25802581/** Projects samples into the LDA subspace.2582src may be one or more row aligned samples.2583*/2584Mat project(InputArray src);25852586/** Reconstructs projections from the LDA subspace.2587src may be one or more row aligned projections.2588*/2589Mat reconstruct(InputArray src);25902591/** Returns the eigenvectors of this LDA.2592*/2593Mat eigenvectors() const { return _eigenvectors; }25942595/** Returns the eigenvalues of this LDA.2596*/2597Mat eigenvalues() const { return _eigenvalues; }25982599static Mat subspaceProject(InputArray W, InputArray mean, InputArray src);2600static Mat subspaceReconstruct(InputArray W, InputArray mean, InputArray src);26012602protected:2603int _num_components;2604Mat _eigenvectors;2605Mat _eigenvalues;2606void lda(InputArrayOfArrays src, InputArray labels);2607};26082609/** @brief Singular Value Decomposition26102611Class for computing Singular Value Decomposition of a floating-point2612matrix. The Singular Value Decomposition is used to solve least-square2613problems, under-determined linear systems, invert matrices, compute2614condition numbers, and so on.26152616If you want to compute a condition number of a matrix or an absolute value of2617its determinant, you do not need `u` and `vt`. You can pass2618flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that full-size u2619and vt must be computed, which is not necessary most of the time.26202621@sa invert, solve, eigen, determinant2622*/2623class CV_EXPORTS SVD2624{2625public:2626enum Flags {2627/** allow the algorithm to modify the decomposed matrix; it can save space and speed up2628processing. currently ignored. */2629MODIFY_A = 1,2630/** indicates that only a vector of singular values `w` is to be processed, while u and vt2631will be set to empty matrices */2632NO_UV = 2,2633/** when the matrix is not square, by default the algorithm produces u and vt matrices of2634sufficiently large size for the further A reconstruction; if, however, FULL_UV flag is2635specified, u and vt will be full-size square orthogonal matrices.*/2636FULL_UV = 42637};26382639/** @brief the default constructor26402641initializes an empty SVD structure2642*/2643SVD();26442645/** @overload2646initializes an empty SVD structure and then calls SVD::operator()2647@param src decomposed matrix. The depth has to be CV_32F or CV_64F.2648@param flags operation flags (SVD::Flags)2649*/2650SVD( InputArray src, int flags = 0 );26512652/** @brief the operator that performs SVD. The previously allocated u, w and vt are released.26532654The operator performs the singular value decomposition of the supplied2655matrix. The u,`vt` , and the vector of singular values w are stored in2656the structure. The same SVD structure can be reused many times with2657different matrices. Each time, if needed, the previous u,`vt` , and w2658are reclaimed and the new matrices are created, which is all handled by2659Mat::create.2660@param src decomposed matrix. The depth has to be CV_32F or CV_64F.2661@param flags operation flags (SVD::Flags)2662*/2663SVD& operator ()( InputArray src, int flags = 0 );26642665/** @brief decomposes matrix and stores the results to user-provided matrices26662667The methods/functions perform SVD of matrix. Unlike SVD::SVD constructor2668and SVD::operator(), they store the results to the user-provided2669matrices:26702671@code{.cpp}2672Mat A, w, u, vt;2673SVD::compute(A, w, u, vt);2674@endcode26752676@param src decomposed matrix. The depth has to be CV_32F or CV_64F.2677@param w calculated singular values2678@param u calculated left singular vectors2679@param vt transposed matrix of right singular vectors2680@param flags operation flags - see SVD::Flags.2681*/2682static void compute( InputArray src, OutputArray w,2683OutputArray u, OutputArray vt, int flags = 0 );26842685/** @overload2686computes singular values of a matrix2687@param src decomposed matrix. The depth has to be CV_32F or CV_64F.2688@param w calculated singular values2689@param flags operation flags - see SVD::Flags.2690*/2691static void compute( InputArray src, OutputArray w, int flags = 0 );26922693/** @brief performs back substitution2694*/2695static void backSubst( InputArray w, InputArray u,2696InputArray vt, InputArray rhs,2697OutputArray dst );26982699/** @brief solves an under-determined singular linear system27002701The method finds a unit-length solution x of a singular linear system2702A\*x = 0. Depending on the rank of A, there can be no solutions, a2703single solution or an infinite number of solutions. In general, the2704algorithm solves the following problem:2705\f[dst = \arg \min _{x: \| x \| =1} \| src \cdot x \|\f]2706@param src left-hand-side matrix.2707@param dst found solution.2708*/2709static void solveZ( InputArray src, OutputArray dst );27102711/** @brief performs a singular value back substitution.27122713The method calculates a back substitution for the specified right-hand2714side:27152716\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]27172718Using this technique you can either get a very accurate solution of the2719convenient linear system, or the best (in the least-squares terms)2720pseudo-solution of an overdetermined linear system.27212722@param rhs right-hand side of a linear system (u\*w\*v')\*dst = rhs to2723be solved, where A has been previously decomposed.27242725@param dst found solution of the system.27262727@note Explicit SVD with the further back substitution only makes sense2728if you need to solve many linear systems with the same left-hand side2729(for example, src ). If all you need is to solve a single system2730(possibly with multiple rhs immediately available), simply call solve2731add pass #DECOMP_SVD there. It does absolutely the same thing.2732*/2733void backSubst( InputArray rhs, OutputArray dst ) const;27342735/** @todo document */2736template<typename _Tp, int m, int n, int nm> static2737void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt );27382739/** @todo document */2740template<typename _Tp, int m, int n, int nm> static2741void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w );27422743/** @todo document */2744template<typename _Tp, int m, int n, int nm, int nb> static2745void 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 );27462747Mat u, w, vt;2748};27492750/** @brief Random Number Generator27512752Random number generator. It encapsulates the state (currently, a 64-bit2753integer) and has methods to return scalar random values and to fill2754arrays with random values. Currently it supports uniform and Gaussian2755(normal) distributions. The generator uses Multiply-With-Carry2756algorithm, introduced by G. Marsaglia (2757<http://en.wikipedia.org/wiki/Multiply-with-carry> ).2758Gaussian-distribution random numbers are generated using the Ziggurat2759algorithm ( <http://en.wikipedia.org/wiki/Ziggurat_algorithm> ),2760introduced by G. Marsaglia and W. W. Tsang.2761*/2762class CV_EXPORTS RNG2763{2764public:2765enum { UNIFORM = 0,2766NORMAL = 12767};27682769/** @brief constructor27702771These are the RNG constructors. The first form sets the state to some2772pre-defined value, equal to 2\*\*32-1 in the current implementation. The2773second form sets the state to the specified value. If you passed state=02774, the constructor uses the above default value instead to avoid the2775singular random number sequence, consisting of all zeros.2776*/2777RNG();2778/** @overload2779@param state 64-bit value used to initialize the RNG.2780*/2781RNG(uint64 state);2782/**The method updates the state using the MWC algorithm and returns the2783next 32-bit random number.*/2784unsigned next();27852786/**Each of the methods updates the state using the MWC algorithm and2787returns the next random number of the specified type. In case of integer2788types, the returned number is from the available value range for the2789specified type. In case of floating-point types, the returned value is2790from [0,1) range.2791*/2792operator uchar();2793/** @overload */2794operator schar();2795/** @overload */2796operator ushort();2797/** @overload */2798operator short();2799/** @overload */2800operator unsigned();2801/** @overload */2802operator int();2803/** @overload */2804operator float();2805/** @overload */2806operator double();28072808/** @brief returns a random integer sampled uniformly from [0, N).28092810The methods transform the state using the MWC algorithm and return the2811next random number. The first form is equivalent to RNG::next . The2812second form returns the random number modulo N , which means that the2813result is in the range [0, N) .2814*/2815unsigned operator ()();2816/** @overload2817@param N upper non-inclusive boundary of the returned random number.2818*/2819unsigned operator ()(unsigned N);28202821/** @brief returns uniformly distributed integer random number from [a,b) range28222823The methods transform the state using the MWC algorithm and return the2824next uniformly-distributed random number of the specified type, deduced2825from the input parameter type, from the range [a, b) . There is a nuance2826illustrated by the following sample:28272828@code{.cpp}2829RNG rng;28302831// always produces 02832double a = rng.uniform(0, 1);28332834// produces double from [0, 1)2835double a1 = rng.uniform((double)0, (double)1);28362837// produces float from [0, 1)2838float b = rng.uniform(0.f, 1.f);28392840// produces double from [0, 1)2841double c = rng.uniform(0., 1.);28422843// may cause compiler error because of ambiguity:2844// RNG::uniform(0, (int)0.999999)? or RNG::uniform((double)0, 0.99999)?2845double d = rng.uniform(0, 0.999999);2846@endcode28472848The compiler does not take into account the type of the variable to2849which you assign the result of RNG::uniform . The only thing that2850matters to the compiler is the type of a and b parameters. So, if you2851want a floating-point random number, but the range boundaries are2852integer numbers, either put dots in the end, if they are constants, or2853use explicit type cast operators, as in the a1 initialization above.2854@param a lower inclusive boundary of the returned random number.2855@param b upper non-inclusive boundary of the returned random number.2856*/2857int uniform(int a, int b);2858/** @overload */2859float uniform(float a, float b);2860/** @overload */2861double uniform(double a, double b);28622863/** @brief Fills arrays with random numbers.28642865@param mat 2D or N-dimensional matrix; currently matrices with more than28664 channels are not supported by the methods, use Mat::reshape as a2867possible workaround.2868@param distType distribution type, RNG::UNIFORM or RNG::NORMAL.2869@param a first distribution parameter; in case of the uniform2870distribution, this is an inclusive lower boundary, in case of the normal2871distribution, this is a mean value.2872@param b second distribution parameter; in case of the uniform2873distribution, this is a non-inclusive upper boundary, in case of the2874normal distribution, this is a standard deviation (diagonal of the2875standard deviation matrix or the full standard deviation matrix).2876@param saturateRange pre-saturation flag; for uniform distribution only;2877if true, the method will first convert a and b to the acceptable value2878range (according to the mat datatype) and then will generate uniformly2879distributed random numbers within the range [saturate(a), saturate(b)),2880if saturateRange=false, the method will generate uniformly distributed2881random numbers in the original range [a, b) and then will saturate them,2882it means, for example, that2883<tt>theRNG().fill(mat_8u, RNG::UNIFORM, -DBL_MAX, DBL_MAX)</tt> will likely2884produce array mostly filled with 0's and 255's, since the range (0, 255)2885is significantly smaller than [-DBL_MAX, DBL_MAX).28862887Each of the methods fills the matrix with the random values from the2888specified distribution. As the new numbers are generated, the RNG state2889is updated accordingly. In case of multiple-channel images, every2890channel is filled independently, which means that RNG cannot generate2891samples from the multi-dimensional Gaussian distribution with2892non-diagonal covariance matrix directly. To do that, the method2893generates samples from multi-dimensional standard Gaussian distribution2894with zero mean and identity covariation matrix, and then transforms them2895using transform to get samples from the specified Gaussian distribution.2896*/2897void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange = false );28982899/** @brief Returns the next random number sampled from the Gaussian distribution2900@param sigma standard deviation of the distribution.29012902The method transforms the state using the MWC algorithm and returns the2903next random number from the Gaussian distribution N(0,sigma) . That is,2904the mean value of the returned random numbers is zero and the standard2905deviation is the specified sigma .2906*/2907double gaussian(double sigma);29082909uint64 state;29102911bool operator ==(const RNG& other) const;2912};29132914/** @brief Mersenne Twister random number generator29152916Inspired by http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c2917@todo document2918*/2919class CV_EXPORTS RNG_MT199372920{2921public:2922RNG_MT19937();2923RNG_MT19937(unsigned s);2924void seed(unsigned s);29252926unsigned next();29272928operator int();2929operator unsigned();2930operator float();2931operator double();29322933unsigned operator ()(unsigned N);2934unsigned operator ()();29352936/** @brief returns uniformly distributed integer random number from [a,b) range*/2937int uniform(int a, int b);2938/** @brief returns uniformly distributed floating-point random number from [a,b) range*/2939float uniform(float a, float b);2940/** @brief returns uniformly distributed double-precision floating-point random number from [a,b) range*/2941double uniform(double a, double b);29422943private:2944enum PeriodParameters {N = 624, M = 397};2945unsigned state[N];2946int mti;2947};29482949//! @} core_array29502951//! @addtogroup core_cluster2952//! @{29532954/** @example samples/cpp/kmeans.cpp2955An example on K-means clustering2956*/29572958/** @brief Finds centers of clusters and groups input samples around the clusters.29592960The function kmeans implements a k-means algorithm that finds the centers of cluster_count clusters2961and groups the input samples around the clusters. As an output, \f$\texttt{labels}_i\f$ contains a29620-based cluster index for the sample stored in the \f$i^{th}\f$ row of the samples matrix.29632964@note2965- (Python) An example on K-means clustering can be found at2966opencv_source_code/samples/python/kmeans.py2967@param data Data for clustering. An array of N-Dimensional points with float coordinates is needed.2968Examples of this array can be:2969- Mat points(count, 2, CV_32F);2970- Mat points(count, 1, CV_32FC2);2971- Mat points(1, count, CV_32FC2);2972- std::vector\<cv::Point2f\> points(sampleCount);2973@param K Number of clusters to split the set by.2974@param bestLabels Input/output integer array that stores the cluster indices for every sample.2975@param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or2976the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster2977centers moves by less than criteria.epsilon on some iteration, the algorithm stops.2978@param attempts Flag to specify the number of times the algorithm is executed using different2979initial labellings. The algorithm returns the labels that yield the best compactness (see the last2980function parameter).2981@param flags Flag that can take values of cv::KmeansFlags2982@param centers Output matrix of the cluster centers, one row per each cluster center.2983@return The function returns the compactness measure that is computed as2984\f[\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\f]2985after every attempt. The best (minimum) value is chosen and the corresponding labels and the2986compactness value are returned by the function. Basically, you can use only the core of the2987function, set the number of attempts to 1, initialize labels each time using a custom algorithm,2988pass them with the ( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best2989(most-compact) clustering.2990*/2991CV_EXPORTS_W double kmeans( InputArray data, int K, InputOutputArray bestLabels,2992TermCriteria criteria, int attempts,2993int flags, OutputArray centers = noArray() );29942995//! @} core_cluster29962997//! @addtogroup core_basic2998//! @{29993000/////////////////////////////// Formatted output of cv::Mat ///////////////////////////30013002/** @todo document */3003class CV_EXPORTS Formatted3004{3005public:3006virtual const char* next() = 0;3007virtual void reset() = 0;3008virtual ~Formatted();3009};30103011/** @todo document */3012class CV_EXPORTS Formatter3013{3014public:3015enum FormatType {3016FMT_DEFAULT = 0,3017FMT_MATLAB = 1,3018FMT_CSV = 2,3019FMT_PYTHON = 3,3020FMT_NUMPY = 4,3021FMT_C = 53022};30233024virtual ~Formatter();30253026virtual Ptr<Formatted> format(const Mat& mtx) const = 0;30273028virtual void set16fPrecision(int p = 4) = 0;3029virtual void set32fPrecision(int p = 8) = 0;3030virtual void set64fPrecision(int p = 16) = 0;3031virtual void setMultiline(bool ml = true) = 0;30323033static Ptr<Formatter> get(Formatter::FormatType fmt = FMT_DEFAULT);30343035};30363037static inline3038String& operator << (String& out, Ptr<Formatted> fmtd)3039{3040fmtd->reset();3041for(const char* str = fmtd->next(); str; str = fmtd->next())3042out += cv::String(str);3043return out;3044}30453046static inline3047String& operator << (String& out, const Mat& mtx)3048{3049return out << Formatter::get()->format(mtx);3050}30513052//////////////////////////////////////// Algorithm ////////////////////////////////////30533054class CV_EXPORTS Algorithm;30553056template<typename _Tp, typename _EnumTp = void> struct ParamType {};305730583059/** @brief This is a base class for all more or less complex algorithms in OpenCV30603061especially for classes of algorithms, for which there can be multiple implementations. The examples3062are stereo correspondence (for which there are algorithms like block matching, semi-global block3063matching, graph-cut etc.), background subtraction (which can be done using mixture-of-gaussians3064models, codebook-based algorithm etc.), optical flow (block matching, Lucas-Kanade, Horn-Schunck3065etc.).30663067Here is example of SimpleBlobDetector use in your application via Algorithm interface:3068@snippet snippets/core_various.cpp Algorithm3069*/3070class CV_EXPORTS_W Algorithm3071{3072public:3073Algorithm();3074virtual ~Algorithm();30753076/** @brief Clears the algorithm state3077*/3078CV_WRAP virtual void clear() {}30793080/** @brief Stores algorithm parameters in a file storage3081*/3082virtual void write(FileStorage& fs) const { CV_UNUSED(fs); }30833084/** @brief simplified API for language bindings3085* @overload3086*/3087CV_WRAP void write(const Ptr<FileStorage>& fs, const String& name = String()) const;30883089/** @brief Reads algorithm parameters from a file storage3090*/3091CV_WRAP virtual void read(const FileNode& fn) { CV_UNUSED(fn); }30923093/** @brief Returns true if the Algorithm is empty (e.g. in the very beginning or after unsuccessful read3094*/3095CV_WRAP virtual bool empty() const { return false; }30963097/** @brief Reads algorithm from the file node30983099This is static template method of Algorithm. It's usage is following (in the case of SVM):3100@code3101cv::FileStorage fsRead("example.xml", FileStorage::READ);3102Ptr<SVM> svm = Algorithm::read<SVM>(fsRead.root());3103@endcode3104In order to make this method work, the derived class must overwrite Algorithm::read(const3105FileNode& fn) and also have static create() method without parameters3106(or with all the optional parameters)3107*/3108template<typename _Tp> static Ptr<_Tp> read(const FileNode& fn)3109{3110Ptr<_Tp> obj = _Tp::create();3111obj->read(fn);3112return !obj->empty() ? obj : Ptr<_Tp>();3113}31143115/** @brief Loads algorithm from the file31163117@param filename Name of the file to read.3118@param objname The optional name of the node to read (if empty, the first top-level node will be used)31193120This is static template method of Algorithm. It's usage is following (in the case of SVM):3121@code3122Ptr<SVM> svm = Algorithm::load<SVM>("my_svm_model.xml");3123@endcode3124In order to make this method work, the derived class must overwrite Algorithm::read(const3125FileNode& fn).3126*/3127template<typename _Tp> static Ptr<_Tp> load(const String& filename, const String& objname=String())3128{3129FileStorage fs(filename, FileStorage::READ);3130CV_Assert(fs.isOpened());3131FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname];3132if (fn.empty()) return Ptr<_Tp>();3133Ptr<_Tp> obj = _Tp::create();3134obj->read(fn);3135return !obj->empty() ? obj : Ptr<_Tp>();3136}31373138/** @brief Loads algorithm from a String31393140@param strModel The string variable containing the model you want to load.3141@param objname The optional name of the node to read (if empty, the first top-level node will be used)31423143This is static template method of Algorithm. It's usage is following (in the case of SVM):3144@code3145Ptr<SVM> svm = Algorithm::loadFromString<SVM>(myStringModel);3146@endcode3147*/3148template<typename _Tp> static Ptr<_Tp> loadFromString(const String& strModel, const String& objname=String())3149{3150FileStorage fs(strModel, FileStorage::READ + FileStorage::MEMORY);3151FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname];3152Ptr<_Tp> obj = _Tp::create();3153obj->read(fn);3154return !obj->empty() ? obj : Ptr<_Tp>();3155}31563157/** Saves the algorithm to a file.3158In order to make this method work, the derived class must implement Algorithm::write(FileStorage& fs). */3159CV_WRAP virtual void save(const String& filename) const;31603161/** Returns the algorithm string identifier.3162This string is used as top level xml/yml node tag when the object is saved to a file or string. */3163CV_WRAP virtual String getDefaultName() const;31643165protected:3166void writeFormat(FileStorage& fs) const;3167};31683169enum struct Param {3170INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7,3171UNSIGNED_INT=8, UINT64=9, UCHAR=11, SCALAR=123172};3173317431753176template<> struct ParamType<bool>3177{3178typedef bool const_param_type;3179typedef bool member_type;31803181static const Param type = Param::BOOLEAN;3182};31833184template<> struct ParamType<int>3185{3186typedef int const_param_type;3187typedef int member_type;31883189static const Param type = Param::INT;3190};31913192template<> struct ParamType<double>3193{3194typedef double const_param_type;3195typedef double member_type;31963197static const Param type = Param::REAL;3198};31993200template<> struct ParamType<String>3201{3202typedef const String& const_param_type;3203typedef String member_type;32043205static const Param type = Param::STRING;3206};32073208template<> struct ParamType<Mat>3209{3210typedef const Mat& const_param_type;3211typedef Mat member_type;32123213static const Param type = Param::MAT;3214};32153216template<> struct ParamType<std::vector<Mat> >3217{3218typedef const std::vector<Mat>& const_param_type;3219typedef std::vector<Mat> member_type;32203221static const Param type = Param::MAT_VECTOR;3222};32233224template<> struct ParamType<Algorithm>3225{3226typedef const Ptr<Algorithm>& const_param_type;3227typedef Ptr<Algorithm> member_type;32283229static const Param type = Param::ALGORITHM;3230};32313232template<> struct ParamType<float>3233{3234typedef float const_param_type;3235typedef float member_type;32363237static const Param type = Param::FLOAT;3238};32393240template<> struct ParamType<unsigned>3241{3242typedef unsigned const_param_type;3243typedef unsigned member_type;32443245static const Param type = Param::UNSIGNED_INT;3246};32473248template<> struct ParamType<uint64>3249{3250typedef uint64 const_param_type;3251typedef uint64 member_type;32523253static const Param type = Param::UINT64;3254};32553256template<> struct ParamType<uchar>3257{3258typedef uchar const_param_type;3259typedef uchar member_type;32603261static const Param type = Param::UCHAR;3262};32633264template<> struct ParamType<Scalar>3265{3266typedef const Scalar& const_param_type;3267typedef Scalar member_type;32683269static const Param type = Param::SCALAR;3270};32713272template<typename _Tp>3273struct ParamType<_Tp, typename std::enable_if< std::is_enum<_Tp>::value >::type>3274{3275typedef typename std::underlying_type<_Tp>::type const_param_type;3276typedef typename std::underlying_type<_Tp>::type member_type;32773278static const Param type = Param::INT;3279};32803281//! @} core_basic32823283} //namespace cv32843285#include "opencv2/core/operations.hpp"3286#include "opencv2/core/cvstd.inl.hpp"3287#include "opencv2/core/utility.hpp"3288#include "opencv2/core/optim.hpp"3289#include "opencv2/core/ovx.hpp"32903291#endif /*OPENCV_CORE_HPP*/329232933294