Renesas / opencv-lib

Dependents:   RZ_A2M_Mbed_samples

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers core.hpp Source File

core.hpp

00001 /*M///////////////////////////////////////////////////////////////////////////////////////
00002 //
00003 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
00004 //
00005 //  By downloading, copying, installing or using the software you agree to this license.
00006 //  If you do not agree to this license, do not download, install,
00007 //  copy or use the software.
00008 //
00009 //
00010 //                           License Agreement
00011 //                For Open Source Computer Vision Library
00012 //
00013 // Copyright (C) 2000-2015, Intel Corporation, all rights reserved.
00014 // Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
00015 // Copyright (C) 2015, OpenCV Foundation, all rights reserved.
00016 // Copyright (C) 2015, Itseez Inc., all rights reserved.
00017 // Third party copyrights are property of their respective owners.
00018 //
00019 // Redistribution and use in source and binary forms, with or without modification,
00020 // are permitted provided that the following conditions are met:
00021 //
00022 //   * Redistribution's of source code must retain the above copyright notice,
00023 //     this list of conditions and the following disclaimer.
00024 //
00025 //   * Redistribution's in binary form must reproduce the above copyright notice,
00026 //     this list of conditions and the following disclaimer in the documentation
00027 //     and/or other materials provided with the distribution.
00028 //
00029 //   * The name of the copyright holders may not be used to endorse or promote products
00030 //     derived from this software without specific prior written permission.
00031 //
00032 // This software is provided by the copyright holders and contributors "as is" and
00033 // any express or implied warranties, including, but not limited to, the implied
00034 // warranties of merchantability and fitness for a particular purpose are disclaimed.
00035 // In no event shall the Intel Corporation or contributors be liable for any direct,
00036 // indirect, incidental, special, exemplary, or consequential damages
00037 // (including, but not limited to, procurement of substitute goods or services;
00038 // loss of use, data, or profits; or business interruption) however caused
00039 // and on any theory of liability, whether in contract, strict liability,
00040 // or tort (including negligence or otherwise) arising in any way out of
00041 // the use of this software, even if advised of the possibility of such damage.
00042 //
00043 //M*/
00044 
00045 #ifndef OPENCV_CORE_HPP
00046 #define OPENCV_CORE_HPP
00047 
00048 #ifndef __cplusplus
00049 #  error core.hpp header must be compiled as C++
00050 #endif
00051 
00052 #include "opencv2/core/cvdef.h"
00053 #include "opencv2/core/version.hpp"
00054 #include "opencv2/core/base.hpp"
00055 #include "opencv2/core/cvstd.hpp"
00056 #include "opencv2/core/traits.hpp"
00057 #include "opencv2/core/matx.hpp"
00058 #include "opencv2/core/types.hpp"
00059 #include "opencv2/core/mat.hpp"
00060 #include "opencv2/core/persistence.hpp"
00061 
00062 /**
00063 @defgroup core Core functionality
00064 @{
00065     @defgroup core_basic Basic structures
00066     @defgroup core_c C structures and operations
00067     @{
00068         @defgroup core_c_glue Connections with C++
00069     @}
00070     @defgroup core_array Operations on arrays
00071     @defgroup core_xml XML/YAML Persistence
00072     @defgroup core_cluster Clustering
00073     @defgroup core_utils Utility and system functions and macros
00074     @{
00075         @defgroup core_utils_sse SSE utilities
00076         @defgroup core_utils_neon NEON utilities
00077     @}
00078     @defgroup core_opengl OpenGL interoperability
00079     @defgroup core_ipp Intel IPP Asynchronous C/C++ Converters
00080     @defgroup core_optim Optimization Algorithms
00081     @defgroup core_directx DirectX interoperability
00082     @defgroup core_eigen Eigen support
00083     @defgroup core_opencl OpenCL support
00084     @defgroup core_va_intel Intel VA-API/OpenCL (CL-VA) interoperability
00085     @defgroup core_hal Hardware Acceleration Layer
00086     @{
00087         @defgroup core_hal_functions Functions
00088         @defgroup core_hal_interface Interface
00089         @defgroup core_hal_intrin Universal intrinsics
00090         @{
00091             @defgroup core_hal_intrin_impl Private implementation helpers
00092         @}
00093     @}
00094 @}
00095  */
00096 
00097 namespace cv {
00098 
00099 //! @addtogroup core_utils
00100 //! @{
00101 
00102 /*! @brief Class passed to an error.
00103 
00104 This class encapsulates all or almost all necessary
00105 information about the error happened in the program. The exception is
00106 usually constructed and thrown implicitly via CV_Error and CV_Error_ macros.
00107 @see error
00108  */
00109 class CV_EXPORTS Exception : public std::exception
00110 {
00111 public:
00112     /*!
00113      Default constructor
00114      */
00115     Exception();
00116     /*!
00117      Full constructor. Normally the constuctor is not called explicitly.
00118      Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used.
00119     */
00120     Exception(int _code, const String& _err, const String& _func, const String& _file, int _line);
00121     virtual ~Exception() throw();
00122 
00123     /*!
00124      \return the error description and the context as a text string.
00125     */
00126     virtual const char *what() const throw();
00127     void formatMessage();
00128 
00129     String msg; ///< the formatted error message
00130 
00131     int code; ///< error code @see CVStatus
00132     String err; ///< error description
00133     String func; ///< function name. Available only when the compiler supports getting it
00134     String file; ///< source file name where the error has occured
00135     int line; ///< line number in the source file where the error has occured
00136 };
00137 
00138 /*! @brief Signals an error and raises the exception.
00139 
00140 By default the function prints information about the error to stderr,
00141 then it either stops if cv::setBreakOnError() had been called before or raises the exception.
00142 It is possible to alternate error processing by using cv::redirectError().
00143 @param exc the exception raisen.
00144 @deprecated drop this version
00145  */
00146 CV_EXPORTS void error( const Exception& exc );
00147 
00148 enum SortFlags  { SORT_EVERY_ROW    = 0, //!< each matrix row is sorted independently
00149                  SORT_EVERY_COLUMN = 1, //!< each matrix column is sorted
00150                                         //!< independently; this flag and the previous one are
00151                                         //!< mutually exclusive.
00152                  SORT_ASCENDING    = 0, //!< each matrix row is sorted in the ascending
00153                                         //!< order.
00154                  SORT_DESCENDING   = 16 //!< each matrix row is sorted in the
00155                                         //!< descending order; this flag and the previous one are also
00156                                         //!< mutually exclusive.
00157                };
00158 
00159 //! @} core_utils
00160 
00161 //! @addtogroup core
00162 //! @{
00163 
00164 //! Covariation flags
00165 enum CovarFlags {
00166     /** The output covariance matrix is calculated as:
00167        \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]
00168        The covariance matrix will be nsamples x nsamples. Such an unusual covariance matrix is used
00169        for fast PCA of a set of very large vectors (see, for example, the EigenFaces technique for
00170        face recognition). Eigenvalues of this "scrambled" matrix match the eigenvalues of the true
00171        covariance matrix. The "true" eigenvectors can be easily calculated from the eigenvectors of
00172        the "scrambled" covariance matrix. */
00173     COVAR_SCRAMBLED = 0,
00174     /**The output covariance matrix is calculated as:
00175         \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]
00176         covar will be a square matrix of the same size as the total number of elements in each input
00177         vector. One and only one of COVAR_SCRAMBLED and COVAR_NORMAL must be specified.*/
00178     COVAR_NORMAL    = 1,
00179     /** If the flag is specified, the function does not calculate mean from
00180         the input vectors but, instead, uses the passed mean vector. This is useful if mean has been
00181         pre-calculated or known in advance, or if the covariance matrix is calculated by parts. In
00182         this case, mean is not a mean vector of the input sub-set of vectors but rather the mean
00183         vector of the whole set.*/
00184     COVAR_USE_AVG   = 2,
00185     /** If the flag is specified, the covariance matrix is scaled. In the
00186         "normal" mode, scale is 1./nsamples . In the "scrambled" mode, scale is the reciprocal of the
00187         total number of elements in each input vector. By default (if the flag is not specified), the
00188         covariance matrix is not scaled ( scale=1 ).*/
00189     COVAR_SCALE     = 4,
00190     /** If the flag is
00191         specified, all the input vectors are stored as rows of the samples matrix. mean should be a
00192         single-row vector in this case.*/
00193     COVAR_ROWS      = 8,
00194     /** If the flag is
00195         specified, all the input vectors are stored as columns of the samples matrix. mean should be a
00196         single-column vector in this case.*/
00197     COVAR_COLS      = 16
00198 };
00199 
00200 //! k-Means flags
00201 enum KmeansFlags {
00202     /** Select random initial centers in each attempt.*/
00203     KMEANS_RANDOM_CENTERS     = 0,
00204     /** Use kmeans++ center initialization by Arthur and Vassilvitskii [Arthur2007].*/
00205     KMEANS_PP_CENTERS         = 2,
00206     /** During the first (and possibly the only) attempt, use the
00207         user-supplied labels instead of computing them from the initial centers. For the second and
00208         further attempts, use the random or semi-random centers. Use one of KMEANS_\*_CENTERS flag
00209         to specify the exact method.*/
00210     KMEANS_USE_INITIAL_LABELS = 1
00211 };
00212 
00213 //! type of line
00214 enum LineTypes {
00215     FILLED  = -1,
00216     LINE_4  = 4, //!< 4-connected line
00217     LINE_8  = 8, //!< 8-connected line
00218     LINE_AA = 16 //!< antialiased line
00219 };
00220 
00221 //! Only a subset of Hershey fonts
00222 //! <http://sources.isc.org/utils/misc/hershey-font.txt> are supported
00223 enum HersheyFonts {
00224     FONT_HERSHEY_SIMPLEX        = 0, //!< normal size sans-serif font
00225     FONT_HERSHEY_PLAIN          = 1, //!< small size sans-serif font
00226     FONT_HERSHEY_DUPLEX         = 2, //!< normal size sans-serif font (more complex than FONT_HERSHEY_SIMPLEX)
00227     FONT_HERSHEY_COMPLEX        = 3, //!< normal size serif font
00228     FONT_HERSHEY_TRIPLEX        = 4, //!< normal size serif font (more complex than FONT_HERSHEY_COMPLEX)
00229     FONT_HERSHEY_COMPLEX_SMALL  = 5, //!< smaller version of FONT_HERSHEY_COMPLEX
00230     FONT_HERSHEY_SCRIPT_SIMPLEX = 6, //!< hand-writing style font
00231     FONT_HERSHEY_SCRIPT_COMPLEX = 7, //!< more complex variant of FONT_HERSHEY_SCRIPT_SIMPLEX
00232     FONT_ITALIC                 = 16 //!< flag for italic font
00233 };
00234 
00235 enum ReduceTypes  { REDUCE_SUM = 0, //!< the output is the sum of all rows/columns of the matrix.
00236                    REDUCE_AVG = 1, //!< the output is the mean vector of all rows/columns of the matrix.
00237                    REDUCE_MAX = 2, //!< the output is the maximum (column/row-wise) of all rows/columns of the matrix.
00238                    REDUCE_MIN = 3  //!< the output is the minimum (column/row-wise) of all rows/columns of the matrix.
00239                  };
00240 
00241 
00242 /** @brief Swaps two matrices
00243 */
00244 CV_EXPORTS void swap(Mat& a, Mat& b);
00245 /** @overload */
00246 CV_EXPORTS void swap( UMat& a, UMat& b );
00247 
00248 //! @} core
00249 
00250 //! @addtogroup core_array
00251 //! @{
00252 
00253 /** @brief Computes the source location of an extrapolated pixel.
00254 
00255 The function computes and returns the coordinate of a donor pixel corresponding to the specified
00256 extrapolated pixel when using the specified extrapolation border mode. For example, if you use
00257 cv::BORDER_WRAP mode in the horizontal direction, cv::BORDER_REFLECT_101 in the vertical direction and
00258 want to compute value of the "virtual" pixel Point(-5, 100) in a floating-point image img , it
00259 looks like:
00260 @code{.cpp}
00261     float val = img.at<float>(borderInterpolate(100, img.rows, cv::BORDER_REFLECT_101),
00262                               borderInterpolate(-5, img.cols, cv::BORDER_WRAP));
00263 @endcode
00264 Normally, the function is not called directly. It is used inside filtering functions and also in
00265 copyMakeBorder.
00266 @param p 0-based coordinate of the extrapolated pixel along one of the axes, likely <0 or >= len
00267 @param len Length of the array along the corresponding axis.
00268 @param borderType Border type, one of the cv::BorderTypes, except for cv::BORDER_TRANSPARENT and
00269 cv::BORDER_ISOLATED . When borderType==cv::BORDER_CONSTANT , the function always returns -1, regardless
00270 of p and len.
00271 
00272 @sa copyMakeBorder
00273 */
00274 CV_EXPORTS_W int borderInterpolate(int p, int len, int borderType);
00275 
00276 /** @brief Forms a border around an image.
00277 
00278 The function copies the source image into the middle of the destination image. The areas to the
00279 left, to the right, above and below the copied source image will be filled with extrapolated
00280 pixels. This is not what filtering functions based on it do (they extrapolate pixels on-fly), but
00281 what other more complex functions, including your own, may do to simplify image boundary handling.
00282 
00283 The function supports the mode when src is already in the middle of dst . In this case, the
00284 function does not copy src itself but simply constructs the border, for example:
00285 
00286 @code{.cpp}
00287     // let border be the same in all directions
00288     int border=2;
00289     // constructs a larger image to fit both the image and the border
00290     Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth());
00291     // select the middle part of it w/o copying data
00292     Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows));
00293     // convert image from RGB to grayscale
00294     cvtColor(rgb, gray, COLOR_RGB2GRAY);
00295     // form a border in-place
00296     copyMakeBorder(gray, gray_buf, border, border,
00297                    border, border, BORDER_REPLICATE);
00298     // now do some custom filtering ...
00299     ...
00300 @endcode
00301 @note When the source image is a part (ROI) of a bigger image, the function will try to use the
00302 pixels outside of the ROI to form a border. To disable this feature and always do extrapolation, as
00303 if src was not a ROI, use borderType | BORDER_ISOLATED.
00304 
00305 @param src Source image.
00306 @param dst Destination image of the same type as src and the size Size(src.cols+left+right,
00307 src.rows+top+bottom) .
00308 @param top
00309 @param bottom
00310 @param left
00311 @param right Parameter specifying how many pixels in each direction from the source image rectangle
00312 to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs
00313 to be built.
00314 @param borderType Border type. See borderInterpolate for details.
00315 @param value Border value if borderType==BORDER_CONSTANT .
00316 
00317 @sa  borderInterpolate
00318 */
00319 CV_EXPORTS_W void copyMakeBorder(InputArray src, OutputArray dst,
00320                                  int top, int bottom, int left, int right,
00321                                  int borderType, const Scalar& value = Scalar() );
00322 
00323 /** @brief Calculates the per-element sum of two arrays or an array and a scalar.
00324 
00325 The function add calculates:
00326 - Sum of two arrays when both input arrays have the same size and the same number of channels:
00327 \f[\texttt{dst}(I) =  \texttt{saturate} ( \texttt{src1}(I) +  \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f]
00328 - Sum of an array and a scalar when src2 is constructed from Scalar or has the same number of
00329 elements as `src1.channels()`:
00330 \f[\texttt{dst}(I) =  \texttt{saturate} ( \texttt{src1}(I) +  \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f]
00331 - Sum of a scalar and an array when src1 is constructed from Scalar or has the same number of
00332 elements as `src2.channels()`:
00333 \f[\texttt{dst}(I) =  \texttt{saturate} ( \texttt{src1} +  \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f]
00334 where `I` is a multi-dimensional index of array elements. In case of multi-channel arrays, each
00335 channel is processed independently.
00336 
00337 The first function in the list above can be replaced with matrix expressions:
00338 @code{.cpp}
00339     dst = src1 + src2;
00340     dst += src1; // equivalent to add(dst, src1, dst);
00341 @endcode
00342 The input arrays and the output array can all have the same or different depths. For example, you
00343 can add a 16-bit unsigned array to a 8-bit signed array and store the sum as a 32-bit
00344 floating-point array. Depth of the output array is determined by the dtype parameter. In the second
00345 and third cases above, as well as in the first case, when src1.depth() == src2.depth(), dtype can
00346 be set to the default -1. In this case, the output array will have the same depth as the input
00347 array, be it src1, src2 or both.
00348 @note Saturation is not applied when the output array has the depth CV_32S. You may even get
00349 result of an incorrect sign in the case of overflow.
00350 @param src1 first input array or a scalar.
00351 @param src2 second input array or a scalar.
00352 @param dst output array that has the same size and number of channels as the input array(s); the
00353 depth is defined by dtype or src1/src2.
00354 @param mask optional operation mask - 8-bit single channel array, that specifies elements of the
00355 output array to be changed.
00356 @param dtype optional depth of the output array (see the discussion below).
00357 @sa subtract, addWeighted, scaleAdd, Mat::convertTo
00358 */
00359 CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst,
00360                       InputArray mask = noArray(), int dtype = -1);
00361 
00362 /** @brief Calculates the per-element difference between two arrays or array and a scalar.
00363 
00364 The function subtract calculates:
00365 - Difference between two arrays, when both input arrays have the same size and the same number of
00366 channels:
00367     \f[\texttt{dst}(I) =  \texttt{saturate} ( \texttt{src1}(I) -  \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f]
00368 - Difference between an array and a scalar, when src2 is constructed from Scalar or has the same
00369 number of elements as `src1.channels()`:
00370     \f[\texttt{dst}(I) =  \texttt{saturate} ( \texttt{src1}(I) -  \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f]
00371 - Difference between a scalar and an array, when src1 is constructed from Scalar or has the same
00372 number of elements as `src2.channels()`:
00373     \f[\texttt{dst}(I) =  \texttt{saturate} ( \texttt{src1} -  \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f]
00374 - The reverse difference between a scalar and an array in the case of `SubRS`:
00375     \f[\texttt{dst}(I) =  \texttt{saturate} ( \texttt{src2} -  \texttt{src1}(I) ) \quad \texttt{if mask}(I) \ne0\f]
00376 where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each
00377 channel is processed independently.
00378 
00379 The first function in the list above can be replaced with matrix expressions:
00380 @code{.cpp}
00381     dst = src1 - src2;
00382     dst -= src1; // equivalent to subtract(dst, src1, dst);
00383 @endcode
00384 The input arrays and the output array can all have the same or different depths. For example, you
00385 can subtract to 8-bit unsigned arrays and store the difference in a 16-bit signed array. Depth of
00386 the output array is determined by dtype parameter. In the second and third cases above, as well as
00387 in the first case, when src1.depth() == src2.depth(), dtype can be set to the default -1. In this
00388 case the output array will have the same depth as the input array, be it src1, src2 or both.
00389 @note Saturation is not applied when the output array has the depth CV_32S. You may even get
00390 result of an incorrect sign in the case of overflow.
00391 @param src1 first input array or a scalar.
00392 @param src2 second input array or a scalar.
00393 @param dst output array of the same size and the same number of channels as the input array.
00394 @param mask optional operation mask; this is an 8-bit single channel array that specifies elements
00395 of the output array to be changed.
00396 @param dtype optional depth of the output array
00397 @sa  add, addWeighted, scaleAdd, Mat::convertTo
00398   */
00399 CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst,
00400                            InputArray mask = noArray(), int dtype = -1);
00401 
00402 
00403 /** @brief Calculates the per-element scaled product of two arrays.
00404 
00405 The function multiply calculates the per-element product of two arrays:
00406 
00407 \f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I)  \cdot \texttt{src2} (I))\f]
00408 
00409 There is also a @ref MatrixExpressions -friendly variant of the first function. See Mat::mul .
00410 
00411 For a not-per-element matrix product, see gemm .
00412 
00413 @note Saturation is not applied when the output array has the depth
00414 CV_32S. You may even get result of an incorrect sign in the case of
00415 overflow.
00416 @param src1 first input array.
00417 @param src2 second input array of the same size and the same type as src1.
00418 @param dst output array of the same size and type as src1.
00419 @param scale optional scale factor.
00420 @param dtype optional depth of the output array
00421 @sa add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare,
00422 Mat::convertTo
00423 */
00424 CV_EXPORTS_W void multiply(InputArray src1, InputArray src2,
00425                            OutputArray dst, double scale = 1, int dtype = -1);
00426 
00427 /** @brief Performs per-element division of two arrays or a scalar by an array.
00428 
00429 The function cv::divide divides one array by another:
00430 \f[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\f]
00431 or a scalar by an array when there is no src1 :
00432 \f[\texttt{dst(I) = saturate(scale/src2(I))}\f]
00433 
00434 When src2(I) is zero, dst(I) will also be zero. Different channels of
00435 multi-channel arrays are processed independently.
00436 
00437 @note Saturation is not applied when the output array has the depth CV_32S. You may even get
00438 result of an incorrect sign in the case of overflow.
00439 @param src1 first input array.
00440 @param src2 second input array of the same size and type as src1.
00441 @param scale scalar factor.
00442 @param dst output array of the same size and type as src2.
00443 @param dtype optional depth of the output array; if -1, dst will have depth src2.depth(), but in
00444 case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth().
00445 @sa  multiply, add, subtract
00446 */
00447 CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst,
00448                          double scale = 1, int dtype = -1);
00449 
00450 /** @overload */
00451 CV_EXPORTS_W void divide(double scale, InputArray src2,
00452                          OutputArray dst, int dtype = -1);
00453 
00454 /** @brief Calculates the sum of a scaled array and another array.
00455 
00456 The function scaleAdd is one of the classical primitive linear algebra operations, known as DAXPY
00457 or SAXPY in [BLAS](http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms). It calculates
00458 the sum of a scaled array and another array:
00459 \f[\texttt{dst} (I)= \texttt{scale} \cdot \texttt{src1} (I) +  \texttt{src2} (I)\f]
00460 The function can also be emulated with a matrix expression, for example:
00461 @code{.cpp}
00462     Mat A(3, 3, CV_64F);
00463     ...
00464     A.row(0) = A.row(1)*2 + A.row(2);
00465 @endcode
00466 @param src1 first input array.
00467 @param alpha scale factor for the first array.
00468 @param src2 second input array of the same size and type as src1.
00469 @param dst output array of the same size and type as src1.
00470 @sa add, addWeighted, subtract, Mat::dot, Mat::convertTo
00471 */
00472 CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst);
00473 
00474 /** @brief Calculates the weighted sum of two arrays.
00475 
00476 The function addWeighted calculates the weighted sum of two arrays as follows:
00477 \f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} +  \texttt{src2} (I)* \texttt{beta} +  \texttt{gamma} )\f]
00478 where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each
00479 channel is processed independently.
00480 The function can be replaced with a matrix expression:
00481 @code{.cpp}
00482     dst = src1*alpha + src2*beta + gamma;
00483 @endcode
00484 @note Saturation is not applied when the output array has the depth CV_32S. You may even get
00485 result of an incorrect sign in the case of overflow.
00486 @param src1 first input array.
00487 @param alpha weight of the first array elements.
00488 @param src2 second input array of the same size and channel number as src1.
00489 @param beta weight of the second array elements.
00490 @param gamma scalar added to each sum.
00491 @param dst output array that has the same size and number of channels as the input arrays.
00492 @param dtype optional depth of the output array; when both input arrays have the same depth, dtype
00493 can be set to -1, which will be equivalent to src1.depth().
00494 @sa  add, subtract, scaleAdd, Mat::convertTo
00495 */
00496 CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2,
00497                               double beta, double gamma, OutputArray dst, int dtype = -1);
00498 
00499 /** @brief Scales, calculates absolute values, and converts the result to 8-bit.
00500 
00501 On each element of the input array, the function convertScaleAbs
00502 performs three operations sequentially: scaling, taking an absolute
00503 value, conversion to an unsigned 8-bit type:
00504 \f[\texttt{dst} (I)= \texttt{saturate\_cast<uchar>} (| \texttt{src} (I)* \texttt{alpha} +  \texttt{beta} |)\f]
00505 In case of multi-channel arrays, the function processes each channel
00506 independently. When the output is not 8-bit, the operation can be
00507 emulated by calling the Mat::convertTo method (or by using matrix
00508 expressions) and then by calculating an absolute value of the result.
00509 For example:
00510 @code{.cpp}
00511     Mat_<float> A(30,30);
00512     randu(A, Scalar(-100), Scalar(100));
00513     Mat_<float> B = A*5 + 3;
00514     B = abs(B);
00515     // Mat_<float> B = abs(A*5+3) will also do the job,
00516     // but it will allocate a temporary matrix
00517 @endcode
00518 @param src input array.
00519 @param dst output array.
00520 @param alpha optional scale factor.
00521 @param beta optional delta added to the scaled values.
00522 @sa  Mat::convertTo, cv::abs(const Mat&)
00523 */
00524 CV_EXPORTS_W void convertScaleAbs(InputArray src, OutputArray dst,
00525                                   double alpha = 1, double beta = 0);
00526 
00527 /** @brief Converts an array to half precision floating number.
00528 
00529 This function converts FP32 (single precision floating point) from/to FP16 (half precision floating point).  The input array has to have type of CV_32F or
00530 CV_16S to represent the bit depth.  If the input array is neither of them, the function will raise an error.
00531 The format of half precision floating point is defined in IEEE 754-2008.
00532 
00533 @param src input array.
00534 @param dst output array.
00535 */
00536 CV_EXPORTS_W void convertFp16(InputArray src, OutputArray dst);
00537 
00538 /** @brief Performs a look-up table transform of an array.
00539 
00540 The function LUT fills the output array with values from the look-up table. Indices of the entries
00541 are taken from the input array. That is, the function processes each element of src as follows:
00542 \f[\texttt{dst} (I)  \leftarrow \texttt{lut(src(I) + d)}\f]
00543 where
00544 \f[d =  \fork{0}{if \(\texttt{src}\) has depth \(\texttt{CV_8U}\)}{128}{if \(\texttt{src}\) has depth \(\texttt{CV_8S}\)}\f]
00545 @param src input array of 8-bit elements.
00546 @param lut look-up table of 256 elements; in case of multi-channel input array, the table should
00547 either have a single channel (in this case the same table is used for all channels) or the same
00548 number of channels as in the input array.
00549 @param dst output array of the same size and number of channels as src, and the same depth as lut.
00550 @sa  convertScaleAbs, Mat::convertTo
00551 */
00552 CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst);
00553 
00554 /** @brief Calculates the sum of array elements.
00555 
00556 The function cv::sum calculates and returns the sum of array elements,
00557 independently for each channel.
00558 @param src input array that must have from 1 to 4 channels.
00559 @sa  countNonZero, mean, meanStdDev, norm, minMaxLoc, reduce
00560 */
00561 CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src);
00562 
00563 /** @brief Counts non-zero array elements.
00564 
00565 The function returns the number of non-zero elements in src :
00566 \f[\sum _{I: \; \texttt{src} (I) \ne0 } 1\f]
00567 @param src single-channel array.
00568 @sa  mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix
00569 */
00570 CV_EXPORTS_W int countNonZero( InputArray src );
00571 
00572 /** @brief Returns the list of locations of non-zero pixels
00573 
00574 Given a binary matrix (likely returned from an operation such
00575 as threshold(), compare(), >, ==, etc, return all of
00576 the non-zero indices as a cv::Mat or std::vector<cv::Point> (x,y)
00577 For example:
00578 @code{.cpp}
00579     cv::Mat binaryImage; // input, binary image
00580     cv::Mat locations;   // output, locations of non-zero pixels
00581     cv::findNonZero(binaryImage, locations);
00582 
00583     // access pixel coordinates
00584     Point pnt = locations.at<Point>(i);
00585 @endcode
00586 or
00587 @code{.cpp}
00588     cv::Mat binaryImage; // input, binary image
00589     vector<Point> locations;   // output, locations of non-zero pixels
00590     cv::findNonZero(binaryImage, locations);
00591 
00592     // access pixel coordinates
00593     Point pnt = locations[i];
00594 @endcode
00595 @param src single-channel array (type CV_8UC1)
00596 @param idx the output array, type of cv::Mat or std::vector<Point>, corresponding to non-zero indices in the input
00597 */
00598 CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx );
00599 
00600 /** @brief Calculates an average (mean) of array elements.
00601 
00602 The function cv::mean calculates the mean value M of array elements,
00603 independently for each channel, and return it:
00604 \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]
00605 When all the mask elements are 0's, the function returns Scalar::all(0)
00606 @param src input array that should have from 1 to 4 channels so that the result can be stored in
00607 Scalar_ .
00608 @param mask optional operation mask.
00609 @sa  countNonZero, meanStdDev, norm, minMaxLoc
00610 */
00611 CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask = noArray());
00612 
00613 /** Calculates a mean and standard deviation of array elements.
00614 
00615 The function cv::meanStdDev calculates the mean and the standard deviation M
00616 of array elements independently for each channel and returns it via the
00617 output parameters:
00618 \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]
00619 When all the mask elements are 0's, the function returns
00620 mean=stddev=Scalar::all(0).
00621 @note The calculated standard deviation is only the diagonal of the
00622 complete normalized covariance matrix. If the full matrix is needed, you
00623 can reshape the multi-channel array M x N to the single-channel array
00624 M\*N x mtx.channels() (only possible when the matrix is continuous) and
00625 then pass the matrix to calcCovarMatrix .
00626 @param src input array that should have from 1 to 4 channels so that the results can be stored in
00627 Scalar_ 's.
00628 @param mean output parameter: calculated mean value.
00629 @param stddev output parameter: calculateded standard deviation.
00630 @param mask optional operation mask.
00631 @sa  countNonZero, mean, norm, minMaxLoc, calcCovarMatrix
00632 */
00633 CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev,
00634                              InputArray mask=noArray());
00635 
00636 /** @brief Calculates an absolute array norm, an absolute difference norm, or a
00637 relative difference norm.
00638 
00639 The function cv::norm calculates an absolute norm of src1 (when there is no
00640 src2 ):
00641 
00642 \f[norm =  \forkthree{\|\texttt{src1}\|_{L_{\infty}} =  \max _I | \texttt{src1} (I)|}{if  \(\texttt{normType} = \texttt{NORM_INF}\) }
00643 { \| \texttt{src1} \| _{L_1} =  \sum _I | \texttt{src1} (I)|}{if  \(\texttt{normType} = \texttt{NORM_L1}\) }
00644 { \| \texttt{src1} \| _{L_2} =  \sqrt{\sum_I \texttt{src1}(I)^2} }{if  \(\texttt{normType} = \texttt{NORM_L2}\) }\f]
00645 
00646 or an absolute or relative difference norm if src2 is there:
00647 
00648 \f[norm =  \forkthree{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} =  \max _I | \texttt{src1} (I) -  \texttt{src2} (I)|}{if  \(\texttt{normType} = \texttt{NORM_INF}\) }
00649 { \| \texttt{src1} - \texttt{src2} \| _{L_1} =  \sum _I | \texttt{src1} (I) -  \texttt{src2} (I)|}{if  \(\texttt{normType} = \texttt{NORM_L1}\) }
00650 { \| \texttt{src1} - \texttt{src2} \| _{L_2} =  \sqrt{\sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2} }{if  \(\texttt{normType} = \texttt{NORM_L2}\) }\f]
00651 
00652 or
00653 
00654 \f[norm =  \forkthree{\frac{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}}    }{\|\texttt{src2}\|_{L_{\infty}} }}{if  \(\texttt{normType} = \texttt{NORM_RELATIVE_INF}\) }
00655 { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_1} }{\|\texttt{src2}\|_{L_1}} }{if  \(\texttt{normType} = \texttt{NORM_RELATIVE_L1}\) }
00656 { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}} }{if  \(\texttt{normType} = \texttt{NORM_RELATIVE_L2}\) }\f]
00657 
00658 The function cv::norm returns the calculated norm.
00659 
00660 When the mask parameter is specified and it is not empty, the norm is
00661 calculated only over the region specified by the mask.
00662 
00663 A multi-channel input arrays are treated as a single-channel, that is,
00664 the results for all channels are combined.
00665 
00666 @param src1 first input array.
00667 @param normType type of the norm (see cv::NormTypes).
00668 @param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type.
00669 */
00670 CV_EXPORTS_W double norm(InputArray src1, int normType = NORM_L2, InputArray mask = noArray());
00671 
00672 /** @overload
00673 @param src1 first input array.
00674 @param src2 second input array of the same size and the same type as src1.
00675 @param normType type of the norm (cv::NormTypes).
00676 @param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type.
00677 */
00678 CV_EXPORTS_W double norm(InputArray src1, InputArray src2,
00679                          int normType = NORM_L2, InputArray mask = noArray());
00680 /** @overload
00681 @param src first input array.
00682 @param normType type of the norm (see cv::NormTypes).
00683 */
00684 CV_EXPORTS double norm( const SparseMat& src, int normType );
00685 
00686 /** @brief computes PSNR image/video quality metric
00687 
00688 see http://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio for details
00689 @todo document
00690   */
00691 CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2);
00692 
00693 /** @brief naive nearest neighbor finder
00694 
00695 see http://en.wikipedia.org/wiki/Nearest_neighbor_search
00696 @todo document
00697   */
00698 CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2,
00699                                 OutputArray dist, int dtype, OutputArray nidx,
00700                                 int normType = NORM_L2, int K = 0,
00701                                 InputArray mask = noArray(), int update = 0,
00702                                 bool crosscheck = false);
00703 
00704 /** @brief Normalizes the norm or value range of an array.
00705 
00706 The function cv::normalize normalizes scale and shift the input array elements so that
00707 \f[\| \texttt{dst} \| _{L_p}= \texttt{alpha}\f]
00708 (where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that
00709 \f[\min _I  \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I  \texttt{dst} (I)= \texttt{beta}\f]
00710 
00711 when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be
00712 normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this
00713 sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or
00714 min-max but modify the whole array, you can use norm and Mat::convertTo.
00715 
00716 In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this,
00717 the range transformation for sparse matrices is not allowed since it can shift the zero level.
00718 
00719 Possible usage with some positive example data:
00720 @code{.cpp}
00721     vector<double> positiveData = { 2.0, 8.0, 10.0 };
00722     vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax;
00723 
00724     // Norm to probability (total count)
00725     // sum(numbers) = 20.0
00726     // 2.0      0.1     (2.0/20.0)
00727     // 8.0      0.4     (8.0/20.0)
00728     // 10.0     0.5     (10.0/20.0)
00729     normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1);
00730 
00731     // Norm to unit vector: ||positiveData|| = 1.0
00732     // 2.0      0.15
00733     // 8.0      0.62
00734     // 10.0     0.77
00735     normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2);
00736 
00737     // Norm to max element
00738     // 2.0      0.2     (2.0/10.0)
00739     // 8.0      0.8     (8.0/10.0)
00740     // 10.0     1.0     (10.0/10.0)
00741     normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF);
00742 
00743     // Norm to range [0.0;1.0]
00744     // 2.0      0.0     (shift to left border)
00745     // 8.0      0.75    (6.0/8.0)
00746     // 10.0     1.0     (shift to right border)
00747     normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX);
00748 @endcode
00749 
00750 @param src input array.
00751 @param dst output array of the same size as src .
00752 @param alpha norm value to normalize to or the lower range boundary in case of the range
00753 normalization.
00754 @param beta upper range boundary in case of the range normalization; it is not used for the norm
00755 normalization.
00756 @param norm_type normalization type (see cv::NormTypes).
00757 @param dtype when negative, the output array has the same type as src; otherwise, it has the same
00758 number of channels as src and the depth =CV_MAT_DEPTH(dtype).
00759 @param mask optional operation mask.
00760 @sa norm, Mat::convertTo, SparseMat::convertTo
00761 */
00762 CV_EXPORTS_W void normalize( InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0,
00763                              int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray());
00764 
00765 /** @overload
00766 @param src input array.
00767 @param dst output array of the same size as src .
00768 @param alpha norm value to normalize to or the lower range boundary in case of the range
00769 normalization.
00770 @param normType normalization type (see cv::NormTypes).
00771 */
00772 CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType );
00773 
00774 /** @brief Finds the global minimum and maximum in an array.
00775 
00776 The function cv::minMaxLoc finds the minimum and maximum element values and their positions. The
00777 extremums are searched across the whole array or, if mask is not an empty array, in the specified
00778 array region.
00779 
00780 The function do not work with multi-channel arrays. If you need to find minimum or maximum
00781 elements across all the channels, use Mat::reshape first to reinterpret the array as
00782 single-channel. Or you may extract the particular channel using either extractImageCOI , or
00783 mixChannels , or split .
00784 @param src input single-channel array.
00785 @param minVal pointer to the returned minimum value; NULL is used if not required.
00786 @param maxVal pointer to the returned maximum value; NULL is used if not required.
00787 @param minLoc pointer to the returned minimum location (in 2D case); NULL is used if not required.
00788 @param maxLoc pointer to the returned maximum location (in 2D case); NULL is used if not required.
00789 @param mask optional mask used to select a sub-array.
00790 @sa max, min, compare, inRange, extractImageCOI, mixChannels, split, Mat::reshape
00791 */
00792 CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal,
00793                             CV_OUT double* maxVal = 0, CV_OUT Point* minLoc = 0,
00794                             CV_OUT Point* maxLoc = 0, InputArray mask = noArray());
00795 
00796 
00797 /** @brief Finds the global minimum and maximum in an array
00798 
00799 The function cv::minMaxIdx finds the minimum and maximum element values and their positions. The
00800 extremums are searched across the whole array or, if mask is not an empty array, in the specified
00801 array region. The function does not work with multi-channel arrays. If you need to find minimum or
00802 maximum elements across all the channels, use Mat::reshape first to reinterpret the array as
00803 single-channel. Or you may extract the particular channel using either extractImageCOI , or
00804 mixChannels , or split . In case of a sparse matrix, the minimum is found among non-zero elements
00805 only.
00806 @note When minIdx is not NULL, it must have at least 2 elements (as well as maxIdx), even if src is
00807 a single-row or single-column matrix. In OpenCV (following MATLAB) each array has at least 2
00808 dimensions, i.e. single-column matrix is Mx1 matrix (and therefore minIdx/maxIdx will be
00809 (i1,0)/(i2,0)) and single-row matrix is 1xN matrix (and therefore minIdx/maxIdx will be
00810 (0,j1)/(0,j2)).
00811 @param src input single-channel array.
00812 @param minVal pointer to the returned minimum value; NULL is used if not required.
00813 @param maxVal pointer to the returned maximum value; NULL is used if not required.
00814 @param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required;
00815 Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element
00816 in each dimension are stored there sequentially.
00817 @param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required.
00818 @param mask specified array region
00819 */
00820 CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal = 0,
00821                           int* minIdx = 0, int* maxIdx = 0, InputArray mask = noArray());
00822 
00823 /** @overload
00824 @param a input single-channel array.
00825 @param minVal pointer to the returned minimum value; NULL is used if not required.
00826 @param maxVal pointer to the returned maximum value; NULL is used if not required.
00827 @param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required;
00828 Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element
00829 in each dimension are stored there sequentially.
00830 @param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required.
00831 */
00832 CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal,
00833                           double* maxVal, int* minIdx = 0, int* maxIdx = 0);
00834 
00835 /** @brief Reduces a matrix to a vector.
00836 
00837 The function cv::reduce reduces the matrix to a vector by treating the matrix rows/columns as a set of
00838 1D vectors and performing the specified operation on the vectors until a single row/column is
00839 obtained. For example, the function can be used to compute horizontal and vertical projections of a
00840 raster image. In case of REDUCE_MAX and REDUCE_MIN , the output image should have the same type as the source one.
00841 In case of REDUCE_SUM and REDUCE_AVG , the output may have a larger element bit-depth to preserve accuracy.
00842 And multi-channel arrays are also supported in these two reduction modes.
00843 @param src input 2D matrix.
00844 @param dst output vector. Its size and type is defined by dim and dtype parameters.
00845 @param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to
00846 a single row. 1 means that the matrix is reduced to a single column.
00847 @param rtype reduction operation that could be one of cv::ReduceTypes
00848 @param dtype when negative, the output vector will have the same type as the input matrix,
00849 otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()).
00850 @sa repeat
00851 */
00852 CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype = -1);
00853 
00854 /** @brief Creates one multi-channel array out of several single-channel ones.
00855 
00856 The function cv::merge merges several arrays to make a single multi-channel array. That is, each
00857 element of the output array will be a concatenation of the elements of the input arrays, where
00858 elements of i-th input array are treated as mv[i].channels()-element vectors.
00859 
00860 The function cv::split does the reverse operation. If you need to shuffle channels in some other
00861 advanced way, use cv::mixChannels.
00862 @param mv input array of matrices to be merged; all the matrices in mv must have the same
00863 size and the same depth.
00864 @param count number of input matrices when mv is a plain C array; it must be greater than zero.
00865 @param dst output array of the same size and the same depth as mv[0]; The number of channels will
00866 be equal to the parameter count.
00867 @sa  mixChannels, split, Mat::reshape
00868 */
00869 CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst);
00870 
00871 /** @overload
00872 @param mv input vector of matrices to be merged; all the matrices in mv must have the same
00873 size and the same depth.
00874 @param dst output array of the same size and the same depth as mv[0]; The number of channels will
00875 be the total number of channels in the matrix array.
00876   */
00877 CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst);
00878 
00879 /** @brief Divides a multi-channel array into several single-channel arrays.
00880 
00881 The function cv::split splits a multi-channel array into separate single-channel arrays:
00882 \f[\texttt{mv} [c](I) =  \texttt{src} (I)_c\f]
00883 If you need to extract a single channel or do some other sophisticated channel permutation, use
00884 mixChannels .
00885 @param src input multi-channel array.
00886 @param mvbegin output array; the number of arrays must match src.channels(); the arrays themselves are
00887 reallocated, if needed.
00888 @sa merge, mixChannels, cvtColor
00889 */
00890 CV_EXPORTS void split(const Mat& src, Mat* mvbegin);
00891 
00892 /** @overload
00893 @param m input multi-channel array.
00894 @param mv output vector of arrays; the arrays themselves are reallocated, if needed.
00895 */
00896 CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv);
00897 
00898 /** @brief Copies specified channels from input arrays to the specified channels of
00899 output arrays.
00900 
00901 The function cv::mixChannels provides an advanced mechanism for shuffling image channels.
00902 
00903 cv::split,cv::merge,cv::extractChannel,cv::insertChannel and some forms of cv::cvtColor are partial cases of cv::mixChannels.
00904 
00905 In the example below, the code splits a 4-channel BGRA image into a 3-channel BGR (with B and R
00906 channels swapped) and a separate alpha-channel image:
00907 @code{.cpp}
00908     Mat bgra( 100, 100, CV_8UC4, Scalar(255,0,0,255) );
00909     Mat bgr( bgra.rows, bgra.cols, CV_8UC3 );
00910     Mat alpha( bgra.rows, bgra.cols, CV_8UC1 );
00911 
00912     // forming an array of matrices is a quite efficient operation,
00913     // because the matrix data is not copied, only the headers
00914     Mat out[] = { bgr, alpha };
00915     // bgra[0] -> bgr[2], bgra[1] -> bgr[1],
00916     // bgra[2] -> bgr[0], bgra[3] -> alpha[0]
00917     int from_to[] = { 0,2, 1,1, 2,0, 3,3 };
00918     mixChannels( &bgra, 1, out, 2, from_to, 4 );
00919 @endcode
00920 @note Unlike many other new-style C++ functions in OpenCV (see the introduction section and
00921 Mat::create ), cv::mixChannels requires the output arrays to be pre-allocated before calling the
00922 function.
00923 @param src input array or vector of matrices; all of the matrices must have the same size and the
00924 same depth.
00925 @param nsrcs number of matrices in `src`.
00926 @param dst output array or vector of matrices; all the matrices **must be allocated**; their size and
00927 depth must be the same as in `src[0]`.
00928 @param ndsts number of matrices in `dst`.
00929 @param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is
00930 a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in
00931 dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to
00932 src[0].channels()-1, the second input image channels are indexed from src[0].channels() to
00933 src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image
00934 channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is
00935 filled with zero .
00936 @param npairs number of index pairs in `fromTo`.
00937 @sa split, merge, extractChannel, insertChannel, cvtColor
00938 */
00939 CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts,
00940                             const int* fromTo, size_t npairs);
00941 
00942 /** @overload
00943 @param src input array or vector of matrices; all of the matrices must have the same size and the
00944 same depth.
00945 @param dst output array or vector of matrices; all the matrices **must be allocated**; their size and
00946 depth must be the same as in src[0].
00947 @param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is
00948 a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in
00949 dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to
00950 src[0].channels()-1, the second input image channels are indexed from src[0].channels() to
00951 src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image
00952 channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is
00953 filled with zero .
00954 @param npairs number of index pairs in fromTo.
00955 */
00956 CV_EXPORTS void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst,
00957                             const int* fromTo, size_t npairs);
00958 
00959 /** @overload
00960 @param src input array or vector of matrices; all of the matrices must have the same size and the
00961 same depth.
00962 @param dst output array or vector of matrices; all the matrices **must be allocated**; their size and
00963 depth must be the same as in src[0].
00964 @param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is
00965 a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in
00966 dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to
00967 src[0].channels()-1, the second input image channels are indexed from src[0].channels() to
00968 src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image
00969 channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is
00970 filled with zero .
00971 */
00972 CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst,
00973                               const std::vector<int>& fromTo);
00974 
00975 /** @brief Extracts a single channel from src (coi is 0-based index)
00976 @param src input array
00977 @param dst output array
00978 @param coi index of channel to extract
00979 @sa mixChannels, split
00980 */
00981 CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi);
00982 
00983 /** @brief Inserts a single channel to dst (coi is 0-based index)
00984 @param src input array
00985 @param dst output array
00986 @param coi index of channel for insertion
00987 @sa mixChannels, merge
00988 */
00989 CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi);
00990 
00991 /** @brief Flips a 2D array around vertical, horizontal, or both axes.
00992 
00993 The function cv::flip flips the array in one of three different ways (row
00994 and column indices are 0-based):
00995 \f[\texttt{dst} _{ij} =
00996 \left\{
00997 \begin{array}{l l}
00998 \texttt{src} _{\texttt{src.rows}-i-1,j} & if\;  \texttt{flipCode} = 0 \\
00999 \texttt{src} _{i, \texttt{src.cols} -j-1} & if\;  \texttt{flipCode} > 0 \\
01000 \texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\
01001 \end{array}
01002 \right.\f]
01003 The example scenarios of using the function are the following:
01004 *   Vertical flipping of the image (flipCode == 0) to switch between
01005     top-left and bottom-left image origin. This is a typical operation
01006     in video processing on Microsoft Windows\* OS.
01007 *   Horizontal flipping of the image with the subsequent horizontal
01008     shift and absolute difference calculation to check for a
01009     vertical-axis symmetry (flipCode > 0).
01010 *   Simultaneous horizontal and vertical flipping of the image with
01011     the subsequent shift and absolute difference calculation to check
01012     for a central symmetry (flipCode < 0).
01013 *   Reversing the order of point arrays (flipCode > 0 or
01014     flipCode == 0).
01015 @param src input array.
01016 @param dst output array of the same size and type as src.
01017 @param flipCode a flag to specify how to flip the array; 0 means
01018 flipping around the x-axis and positive value (for example, 1) means
01019 flipping around y-axis. Negative value (for example, -1) means flipping
01020 around both axes.
01021 @sa transpose , repeat , completeSymm
01022 */
01023 CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode);
01024 
01025 enum RotateFlags {
01026     ROTATE_90_CLOCKWISE = 0, //Rotate 90 degrees clockwise
01027     ROTATE_180 = 1, //Rotate 180 degrees clockwise
01028     ROTATE_90_COUNTERCLOCKWISE = 2, //Rotate 270 degrees clockwise
01029 };
01030 /** @brief Rotates a 2D array in multiples of 90 degrees.
01031 The function rotate rotates the array in one of three different ways:
01032 *   Rotate by 90 degrees clockwise (rotateCode = ROTATE_90).
01033 *   Rotate by 180 degrees clockwise (rotateCode = ROTATE_180).
01034 *   Rotate by 270 degrees clockwise (rotateCode = ROTATE_270).
01035 @param src input array.
01036 @param dst output array of the same type as src.  The size is the same with ROTATE_180,
01037 and the rows and cols are switched for ROTATE_90 and ROTATE_270.
01038 @param rotateCode an enum to specify how to rotate the array; see the enum RotateFlags
01039 @sa transpose , repeat , completeSymm, flip, RotateFlags
01040 */
01041 CV_EXPORTS_W void rotate(InputArray src, OutputArray dst, int rotateCode);
01042 
01043 /** @brief Fills the output array with repeated copies of the input array.
01044 
01045 The function cv::repeat duplicates the input array one or more times along each of the two axes:
01046 \f[\texttt{dst} _{ij}= \texttt{src} _{i\mod src.rows, \; j\mod src.cols }\f]
01047 The second variant of the function is more convenient to use with @ref MatrixExpressions.
01048 @param src input array to replicate.
01049 @param ny Flag to specify how many times the `src` is repeated along the
01050 vertical axis.
01051 @param nx Flag to specify how many times the `src` is repeated along the
01052 horizontal axis.
01053 @param dst output array of the same type as `src`.
01054 @sa cv::reduce
01055 */
01056 CV_EXPORTS_W void repeat(InputArray src, int ny, int nx, OutputArray dst);
01057 
01058 /** @overload
01059 @param src input array to replicate.
01060 @param ny Flag to specify how many times the `src` is repeated along the
01061 vertical axis.
01062 @param nx Flag to specify how many times the `src` is repeated along the
01063 horizontal axis.
01064   */
01065 CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx);
01066 
01067 /** @brief Applies horizontal concatenation to given matrices.
01068 
01069 The function horizontally concatenates two or more cv::Mat matrices (with the same number of rows).
01070 @code{.cpp}
01071     cv::Mat matArray[] = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)),
01072                            cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)),
01073                            cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),};
01074 
01075     cv::Mat out;
01076     cv::hconcat( matArray, 3, out );
01077     //out:
01078     //[1, 2, 3;
01079     // 1, 2, 3;
01080     // 1, 2, 3;
01081     // 1, 2, 3]
01082 @endcode
01083 @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth.
01084 @param nsrc number of matrices in src.
01085 @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src.
01086 @sa cv::vconcat(const Mat*, size_t, OutputArray), @sa cv::vconcat(InputArrayOfArrays, OutputArray) and @sa cv::vconcat(InputArray, InputArray, OutputArray)
01087 */
01088 CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, OutputArray dst);
01089 /** @overload
01090  @code{.cpp}
01091     cv::Mat_<float> A = (cv::Mat_<float>(3, 2) << 1, 4,
01092                                                   2, 5,
01093                                                   3, 6);
01094     cv::Mat_<float> B = (cv::Mat_<float>(3, 2) << 7, 10,
01095                                                   8, 11,
01096                                                   9, 12);
01097 
01098     cv::Mat C;
01099     cv::hconcat(A, B, C);
01100     //C:
01101     //[1, 4, 7, 10;
01102     // 2, 5, 8, 11;
01103     // 3, 6, 9, 12]
01104  @endcode
01105  @param src1 first input array to be considered for horizontal concatenation.
01106  @param src2 second input array to be considered for horizontal concatenation.
01107  @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.
01108  */
01109 CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst);
01110 /** @overload
01111  @code{.cpp}
01112     std::vector<cv::Mat> matrices = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)),
01113                                       cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)),
01114                                       cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),};
01115 
01116     cv::Mat out;
01117     cv::hconcat( matrices, out );
01118     //out:
01119     //[1, 2, 3;
01120     // 1, 2, 3;
01121     // 1, 2, 3;
01122     // 1, 2, 3]
01123  @endcode
01124  @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth.
01125  @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src.
01126 same depth.
01127  */
01128 CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst);
01129 
01130 /** @brief Applies vertical concatenation to given matrices.
01131 
01132 The function vertically concatenates two or more cv::Mat matrices (with the same number of cols).
01133 @code{.cpp}
01134     cv::Mat matArray[] = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)),
01135                            cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)),
01136                            cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),};
01137 
01138     cv::Mat out;
01139     cv::vconcat( matArray, 3, out );
01140     //out:
01141     //[1,   1,   1,   1;
01142     // 2,   2,   2,   2;
01143     // 3,   3,   3,   3]
01144 @endcode
01145 @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth.
01146 @param nsrc number of matrices in src.
01147 @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src.
01148 @sa cv::hconcat(const Mat*, size_t, OutputArray), @sa cv::hconcat(InputArrayOfArrays, OutputArray) and @sa cv::hconcat(InputArray, InputArray, OutputArray)
01149 */
01150 CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst);
01151 /** @overload
01152  @code{.cpp}
01153     cv::Mat_<float> A = (cv::Mat_<float>(3, 2) << 1, 7,
01154                                                   2, 8,
01155                                                   3, 9);
01156     cv::Mat_<float> B = (cv::Mat_<float>(3, 2) << 4, 10,
01157                                                   5, 11,
01158                                                   6, 12);
01159 
01160     cv::Mat C;
01161     cv::vconcat(A, B, C);
01162     //C:
01163     //[1, 7;
01164     // 2, 8;
01165     // 3, 9;
01166     // 4, 10;
01167     // 5, 11;
01168     // 6, 12]
01169  @endcode
01170  @param src1 first input array to be considered for vertical concatenation.
01171  @param src2 second input array to be considered for vertical concatenation.
01172  @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.
01173  */
01174 CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst);
01175 /** @overload
01176  @code{.cpp}
01177     std::vector<cv::Mat> matrices = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)),
01178                                       cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)),
01179                                       cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),};
01180 
01181     cv::Mat out;
01182     cv::vconcat( matrices, out );
01183     //out:
01184     //[1,   1,   1,   1;
01185     // 2,   2,   2,   2;
01186     // 3,   3,   3,   3]
01187  @endcode
01188  @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth
01189  @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src.
01190 same depth.
01191  */
01192 CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst);
01193 
01194 /** @brief computes bitwise conjunction of the two arrays (dst = src1 & src2)
01195 Calculates the per-element bit-wise conjunction of two arrays or an
01196 array and a scalar.
01197 
01198 The function cv::bitwise_and calculates the per-element bit-wise logical conjunction for:
01199 *   Two arrays when src1 and src2 have the same size:
01200     \f[\texttt{dst} (I) =  \texttt{src1} (I)  \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
01201 *   An array and a scalar when src2 is constructed from Scalar or has
01202     the same number of elements as `src1.channels()`:
01203     \f[\texttt{dst} (I) =  \texttt{src1} (I)  \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]
01204 *   A scalar and an array when src1 is constructed from Scalar or has
01205     the same number of elements as `src2.channels()`:
01206     \f[\texttt{dst} (I) =  \texttt{src1}  \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
01207 In case of floating-point arrays, their machine-specific bit
01208 representations (usually IEEE754-compliant) are used for the operation.
01209 In case of multi-channel arrays, each channel is processed
01210 independently. In the second and third cases above, the scalar is first
01211 converted to the array type.
01212 @param src1 first input array or a scalar.
01213 @param src2 second input array or a scalar.
01214 @param dst output array that has the same size and type as the input
01215 arrays.
01216 @param mask optional operation mask, 8-bit single channel array, that
01217 specifies elements of the output array to be changed.
01218 */
01219 CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2,
01220                               OutputArray dst, InputArray mask = noArray());
01221 
01222 /** @brief Calculates the per-element bit-wise disjunction of two arrays or an
01223 array and a scalar.
01224 
01225 The function cv::bitwise_or calculates the per-element bit-wise logical disjunction for:
01226 *   Two arrays when src1 and src2 have the same size:
01227     \f[\texttt{dst} (I) =  \texttt{src1} (I)  \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
01228 *   An array and a scalar when src2 is constructed from Scalar or has
01229     the same number of elements as `src1.channels()`:
01230     \f[\texttt{dst} (I) =  \texttt{src1} (I)  \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]
01231 *   A scalar and an array when src1 is constructed from Scalar or has
01232     the same number of elements as `src2.channels()`:
01233     \f[\texttt{dst} (I) =  \texttt{src1}  \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
01234 In case of floating-point arrays, their machine-specific bit
01235 representations (usually IEEE754-compliant) are used for the operation.
01236 In case of multi-channel arrays, each channel is processed
01237 independently. In the second and third cases above, the scalar is first
01238 converted to the array type.
01239 @param src1 first input array or a scalar.
01240 @param src2 second input array or a scalar.
01241 @param dst output array that has the same size and type as the input
01242 arrays.
01243 @param mask optional operation mask, 8-bit single channel array, that
01244 specifies elements of the output array to be changed.
01245 */
01246 CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2,
01247                              OutputArray dst, InputArray mask = noArray());
01248 
01249 /** @brief Calculates the per-element bit-wise "exclusive or" operation on two
01250 arrays or an array and a scalar.
01251 
01252 The function cv::bitwise_xor calculates the per-element bit-wise logical "exclusive-or"
01253 operation for:
01254 *   Two arrays when src1 and src2 have the same size:
01255     \f[\texttt{dst} (I) =  \texttt{src1} (I)  \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
01256 *   An array and a scalar when src2 is constructed from Scalar or has
01257     the same number of elements as `src1.channels()`:
01258     \f[\texttt{dst} (I) =  \texttt{src1} (I)  \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]
01259 *   A scalar and an array when src1 is constructed from Scalar or has
01260     the same number of elements as `src2.channels()`:
01261     \f[\texttt{dst} (I) =  \texttt{src1}  \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
01262 In case of floating-point arrays, their machine-specific bit
01263 representations (usually IEEE754-compliant) are used for the operation.
01264 In case of multi-channel arrays, each channel is processed
01265 independently. In the 2nd and 3rd cases above, the scalar is first
01266 converted to the array type.
01267 @param src1 first input array or a scalar.
01268 @param src2 second input array or a scalar.
01269 @param dst output array that has the same size and type as the input
01270 arrays.
01271 @param mask optional operation mask, 8-bit single channel array, that
01272 specifies elements of the output array to be changed.
01273 */
01274 CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2,
01275                               OutputArray dst, InputArray mask = noArray());
01276 
01277 /** @brief  Inverts every bit of an array.
01278 
01279 The function cv::bitwise_not calculates per-element bit-wise inversion of the input
01280 array:
01281 \f[\texttt{dst} (I) =  \neg \texttt{src} (I)\f]
01282 In case of a floating-point input array, its machine-specific bit
01283 representation (usually IEEE754-compliant) is used for the operation. In
01284 case of multi-channel arrays, each channel is processed independently.
01285 @param src input array.
01286 @param dst output array that has the same size and type as the input
01287 array.
01288 @param mask optional operation mask, 8-bit single channel array, that
01289 specifies elements of the output array to be changed.
01290 */
01291 CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst,
01292                               InputArray mask = noArray());
01293 
01294 /** @brief Calculates the per-element absolute difference between two arrays or between an array and a scalar.
01295 
01296 The function cv::absdiff calculates:
01297 *   Absolute difference between two arrays when they have the same
01298     size and type:
01299     \f[\texttt{dst}(I) =  \texttt{saturate} (| \texttt{src1}(I) -  \texttt{src2}(I)|)\f]
01300 *   Absolute difference between an array and a scalar when the second
01301     array is constructed from Scalar or has as many elements as the
01302     number of channels in `src1`:
01303     \f[\texttt{dst}(I) =  \texttt{saturate} (| \texttt{src1}(I) -  \texttt{src2} |)\f]
01304 *   Absolute difference between a scalar and an array when the first
01305     array is constructed from Scalar or has as many elements as the
01306     number of channels in `src2`:
01307     \f[\texttt{dst}(I) =  \texttt{saturate} (| \texttt{src1} -  \texttt{src2}(I) |)\f]
01308     where I is a multi-dimensional index of array elements. In case of
01309     multi-channel arrays, each channel is processed independently.
01310 @note Saturation is not applied when the arrays have the depth CV_32S.
01311 You may even get a negative value in the case of overflow.
01312 @param src1 first input array or a scalar.
01313 @param src2 second input array or a scalar.
01314 @param dst output array that has the same size and type as input arrays.
01315 @sa cv::abs(const Mat&)
01316 */
01317 CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst);
01318 
01319 /** @brief  Checks if array elements lie between the elements of two other arrays.
01320 
01321 The function checks the range as follows:
01322 -   For every element of a single-channel input array:
01323     \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0  \leq \texttt{src} (I)_0 \leq  \texttt{upperb} (I)_0\f]
01324 -   For two-channel arrays:
01325     \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]
01326 -   and so forth.
01327 
01328 That is, dst (I) is set to 255 (all 1 -bits) if src (I) is within the
01329 specified 1D, 2D, 3D, ... box and 0 otherwise.
01330 
01331 When the lower and/or upper boundary parameters are scalars, the indexes
01332 (I) at lowerb and upperb in the above formulas should be omitted.
01333 @param src first input array.
01334 @param lowerb inclusive lower boundary array or a scalar.
01335 @param upperb inclusive upper boundary array or a scalar.
01336 @param dst output array of the same size as src and CV_8U type.
01337 */
01338 CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb,
01339                           InputArray upperb, OutputArray dst);
01340 
01341 /** @brief Performs the per-element comparison of two arrays or an array and scalar value.
01342 
01343 The function compares:
01344 *   Elements of two arrays when src1 and src2 have the same size:
01345     \f[\texttt{dst} (I) =  \texttt{src1} (I)  \,\texttt{cmpop}\, \texttt{src2} (I)\f]
01346 *   Elements of src1 with a scalar src2 when src2 is constructed from
01347     Scalar or has a single element:
01348     \f[\texttt{dst} (I) =  \texttt{src1}(I) \,\texttt{cmpop}\,  \texttt{src2}\f]
01349 *   src1 with elements of src2 when src1 is constructed from Scalar or
01350     has a single element:
01351     \f[\texttt{dst} (I) =  \texttt{src1}  \,\texttt{cmpop}\, \texttt{src2} (I)\f]
01352 When the comparison result is true, the corresponding element of output
01353 array is set to 255. The comparison operations can be replaced with the
01354 equivalent matrix expressions:
01355 @code{.cpp}
01356     Mat dst1 = src1 >= src2;
01357     Mat dst2 = src1 < 8;
01358     ...
01359 @endcode
01360 @param src1 first input array or a scalar; when it is an array, it must have a single channel.
01361 @param src2 second input array or a scalar; when it is an array, it must have a single channel.
01362 @param dst output array of type ref CV_8U that has the same size and the same number of channels as
01363     the input arrays.
01364 @param cmpop a flag, that specifies correspondence between the arrays (cv::CmpTypes)
01365 @sa checkRange, min, max, threshold
01366 */
01367 CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop);
01368 
01369 /** @brief Calculates per-element minimum of two arrays or an array and a scalar.
01370 
01371 The function cv::min calculates the per-element minimum of two arrays:
01372 \f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f]
01373 or array and a scalar:
01374 \f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{value} )\f]
01375 @param src1 first input array.
01376 @param src2 second input array of the same size and type as src1.
01377 @param dst output array of the same size and type as src1.
01378 @sa max, compare, inRange, minMaxLoc
01379 */
01380 CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst);
01381 /** @overload
01382 needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
01383 */
01384 CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst);
01385 /** @overload
01386 needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
01387 */
01388 CV_EXPORTS void min(const UMat& src1, const UMat& src2, UMat& dst);
01389 
01390 /** @brief Calculates per-element maximum of two arrays or an array and a scalar.
01391 
01392 The function cv::max calculates the per-element maximum of two arrays:
01393 \f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f]
01394 or array and a scalar:
01395 \f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{value} )\f]
01396 @param src1 first input array.
01397 @param src2 second input array of the same size and type as src1 .
01398 @param dst output array of the same size and type as src1.
01399 @sa  min, compare, inRange, minMaxLoc, @ref MatrixExpressions
01400 */
01401 CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst);
01402 /** @overload
01403 needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
01404 */
01405 CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst);
01406 /** @overload
01407 needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
01408 */
01409 CV_EXPORTS void max(const UMat& src1, const UMat& src2, UMat& dst);
01410 
01411 /** @brief Calculates a square root of array elements.
01412 
01413 The function cv::sqrt calculates a square root of each input array element.
01414 In case of multi-channel arrays, each channel is processed
01415 independently. The accuracy is approximately the same as of the built-in
01416 std::sqrt .
01417 @param src input floating-point array.
01418 @param dst output array of the same size and type as src.
01419 */
01420 CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst);
01421 
01422 /** @brief Raises every array element to a power.
01423 
01424 The function cv::pow raises every element of the input array to power :
01425 \f[\texttt{dst} (I) =  \fork{\texttt{src}(I)^{power}}{if \(\texttt{power}\) is integer}{|\texttt{src}(I)|^{power}}{otherwise}\f]
01426 
01427 So, for a non-integer power exponent, the absolute values of input array
01428 elements are used. However, it is possible to get true values for
01429 negative values using some extra operations. In the example below,
01430 computing the 5th root of array src shows:
01431 @code{.cpp}
01432     Mat mask = src < 0;
01433     pow(src, 1./5, dst);
01434     subtract(Scalar::all(0), dst, dst, mask);
01435 @endcode
01436 For some values of power, such as integer values, 0.5 and -0.5,
01437 specialized faster algorithms are used.
01438 
01439 Special values (NaN, Inf) are not handled.
01440 @param src input array.
01441 @param power exponent of power.
01442 @param dst output array of the same size and type as src.
01443 @sa sqrt, exp, log, cartToPolar, polarToCart
01444 */
01445 CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst);
01446 
01447 /** @brief Calculates the exponent of every array element.
01448 
01449 The function cv::exp calculates the exponent of every element of the input
01450 array:
01451 \f[\texttt{dst} [I] = e^{ src(I) }\f]
01452 
01453 The maximum relative error is about 7e-6 for single-precision input and
01454 less than 1e-10 for double-precision input. Currently, the function
01455 converts denormalized values to zeros on output. Special values (NaN,
01456 Inf) are not handled.
01457 @param src input array.
01458 @param dst output array of the same size and type as src.
01459 @sa log , cartToPolar , polarToCart , phase , pow , sqrt , magnitude
01460 */
01461 CV_EXPORTS_W void exp(InputArray src, OutputArray dst);
01462 
01463 /** @brief Calculates the natural logarithm of every array element.
01464 
01465 The function cv::log calculates the natural logarithm of every element of the input array:
01466 \f[\texttt{dst} (I) =  \log (\texttt{src}(I)) \f]
01467 
01468 Output on zero, negative and special (NaN, Inf) values is undefined.
01469 
01470 @param src input array.
01471 @param dst output array of the same size and type as src .
01472 @sa exp, cartToPolar, polarToCart, phase, pow, sqrt, magnitude
01473 */
01474 CV_EXPORTS_W void log(InputArray src, OutputArray dst);
01475 
01476 /** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle.
01477 
01478 The function cv::polarToCart calculates the Cartesian coordinates of each 2D
01479 vector represented by the corresponding elements of magnitude and angle:
01480 \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]
01481 
01482 The relative accuracy of the estimated coordinates is about 1e-6.
01483 @param magnitude input floating-point array of magnitudes of 2D vectors;
01484 it can be an empty matrix (=Mat()), in this case, the function assumes
01485 that all the magnitudes are =1; if it is not empty, it must have the
01486 same size and type as angle.
01487 @param angle input floating-point array of angles of 2D vectors.
01488 @param x output array of x-coordinates of 2D vectors; it has the same
01489 size and type as angle.
01490 @param y output array of y-coordinates of 2D vectors; it has the same
01491 size and type as angle.
01492 @param angleInDegrees when true, the input angles are measured in
01493 degrees, otherwise, they are measured in radians.
01494 @sa cartToPolar, magnitude, phase, exp, log, pow, sqrt
01495 */
01496 CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle,
01497                               OutputArray x, OutputArray y, bool angleInDegrees = false);
01498 
01499 /** @brief Calculates the magnitude and angle of 2D vectors.
01500 
01501 The function cv::cartToPolar calculates either the magnitude, angle, or both
01502 for every 2D vector (x(I),y(I)):
01503 \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]
01504 
01505 The angles are calculated with accuracy about 0.3 degrees. For the point
01506 (0,0), the angle is set to 0.
01507 @param x array of x-coordinates; this must be a single-precision or
01508 double-precision floating-point array.
01509 @param y array of y-coordinates, that must have the same size and same type as x.
01510 @param magnitude output array of magnitudes of the same size and type as x.
01511 @param angle output array of angles that has the same size and type as
01512 x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees).
01513 @param angleInDegrees a flag, indicating whether the angles are measured
01514 in radians (which is by default), or in degrees.
01515 @sa Sobel, Scharr
01516 */
01517 CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y,
01518                               OutputArray magnitude, OutputArray angle,
01519                               bool angleInDegrees = false);
01520 
01521 /** @brief Calculates the rotation angle of 2D vectors.
01522 
01523 The function cv::phase calculates the rotation angle of each 2D vector that
01524 is formed from the corresponding elements of x and y :
01525 \f[\texttt{angle} (I) =  \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f]
01526 
01527 The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 ,
01528 the corresponding angle(I) is set to 0.
01529 @param x input floating-point array of x-coordinates of 2D vectors.
01530 @param y input array of y-coordinates of 2D vectors; it must have the
01531 same size and the same type as x.
01532 @param angle output array of vector angles; it has the same size and
01533 same type as x .
01534 @param angleInDegrees when true, the function calculates the angle in
01535 degrees, otherwise, they are measured in radians.
01536 */
01537 CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle,
01538                         bool angleInDegrees = false);
01539 
01540 /** @brief Calculates the magnitude of 2D vectors.
01541 
01542 The function cv::magnitude calculates the magnitude of 2D vectors formed
01543 from the corresponding elements of x and y arrays:
01544 \f[\texttt{dst} (I) =  \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}\f]
01545 @param x floating-point array of x-coordinates of the vectors.
01546 @param y floating-point array of y-coordinates of the vectors; it must
01547 have the same size as x.
01548 @param magnitude output array of the same size and type as x.
01549 @sa cartToPolar, polarToCart, phase, sqrt
01550 */
01551 CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude);
01552 
01553 /** @brief Checks every element of an input array for invalid values.
01554 
01555 The function cv::checkRange checks that every array element is neither NaN nor infinite. When minVal >
01556 -DBL_MAX and maxVal < DBL_MAX, the function also checks that each value is between minVal and
01557 maxVal. In case of multi-channel arrays, each channel is processed independently. If some values
01558 are out of range, position of the first outlier is stored in pos (when pos != NULL). Then, the
01559 function either returns false (when quiet=true) or throws an exception.
01560 @param a input array.
01561 @param quiet a flag, indicating whether the functions quietly return false when the array elements
01562 are out of range or they throw an exception.
01563 @param pos optional output parameter, when not NULL, must be a pointer to array of src.dims
01564 elements.
01565 @param minVal inclusive lower boundary of valid values range.
01566 @param maxVal exclusive upper boundary of valid values range.
01567 */
01568 CV_EXPORTS_W bool checkRange(InputArray a, bool quiet = true, CV_OUT Point* pos = 0,
01569                             double minVal = -DBL_MAX, double maxVal = DBL_MAX);
01570 
01571 /** @brief converts NaN's to the given number
01572 */
01573 CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0);
01574 
01575 /** @brief Performs generalized matrix multiplication.
01576 
01577 The function cv::gemm performs generalized matrix multiplication similar to the
01578 gemm functions in BLAS level 3. For example,
01579 `gemm(src1, src2, alpha, src3, beta, dst, GEMM_1_T + GEMM_3_T)`
01580 corresponds to
01581 \f[\texttt{dst} =  \texttt{alpha} \cdot \texttt{src1} ^T  \cdot \texttt{src2} +  \texttt{beta} \cdot \texttt{src3} ^T\f]
01582 
01583 In case of complex (two-channel) data, performed a complex matrix
01584 multiplication.
01585 
01586 The function can be replaced with a matrix expression. For example, the
01587 above call can be replaced with:
01588 @code{.cpp}
01589     dst = alpha*src1.t()*src2 + beta*src3.t();
01590 @endcode
01591 @param src1 first multiplied input matrix that could be real(CV_32FC1,
01592 CV_64FC1) or complex(CV_32FC2, CV_64FC2).
01593 @param src2 second multiplied input matrix of the same type as src1.
01594 @param alpha weight of the matrix product.
01595 @param src3 third optional delta matrix added to the matrix product; it
01596 should have the same type as src1 and src2.
01597 @param beta weight of src3.
01598 @param dst output matrix; it has the proper size and the same type as
01599 input matrices.
01600 @param flags operation flags (cv::GemmFlags)
01601 @sa mulTransposed , transform
01602 */
01603 CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha,
01604                        InputArray src3, double beta, OutputArray dst, int flags = 0);
01605 
01606 /** @brief Calculates the product of a matrix and its transposition.
01607 
01608 The function cv::mulTransposed calculates the product of src and its
01609 transposition:
01610 \f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} )^T ( \texttt{src} - \texttt{delta} )\f]
01611 if aTa=true , and
01612 \f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} ) ( \texttt{src} - \texttt{delta} )^T\f]
01613 otherwise. The function is used to calculate the covariance matrix. With
01614 zero delta, it can be used as a faster substitute for general matrix
01615 product A\*B when B=A'
01616 @param src input single-channel matrix. Note that unlike gemm, the
01617 function can multiply not only floating-point matrices.
01618 @param dst output square matrix.
01619 @param aTa Flag specifying the multiplication ordering. See the
01620 description below.
01621 @param delta Optional delta matrix subtracted from src before the
01622 multiplication. When the matrix is empty ( delta=noArray() ), it is
01623 assumed to be zero, that is, nothing is subtracted. If it has the same
01624 size as src , it is simply subtracted. Otherwise, it is "repeated" (see
01625 repeat ) to cover the full src and then subtracted. Type of the delta
01626 matrix, when it is not empty, must be the same as the type of created
01627 output matrix. See the dtype parameter description below.
01628 @param scale Optional scale factor for the matrix product.
01629 @param dtype Optional type of the output matrix. When it is negative,
01630 the output matrix will have the same type as src . Otherwise, it will be
01631 type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F .
01632 @sa calcCovarMatrix, gemm, repeat, reduce
01633 */
01634 CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa,
01635                                  InputArray delta = noArray(),
01636                                  double scale = 1, int dtype = -1 );
01637 
01638 /** @brief Transposes a matrix.
01639 
01640 The function cv::transpose transposes the matrix src :
01641 \f[\texttt{dst} (i,j) =  \texttt{src} (j,i)\f]
01642 @note No complex conjugation is done in case of a complex matrix. It it
01643 should be done separately if needed.
01644 @param src input array.
01645 @param dst output array of the same type as src.
01646 */
01647 CV_EXPORTS_W void transpose(InputArray src, OutputArray dst);
01648 
01649 /** @brief Performs the matrix transformation of every array element.
01650 
01651 The function cv::transform performs the matrix transformation of every
01652 element of the array src and stores the results in dst :
01653 \f[\texttt{dst} (I) =  \texttt{m} \cdot \texttt{src} (I)\f]
01654 (when m.cols=src.channels() ), or
01655 \f[\texttt{dst} (I) =  \texttt{m} \cdot [ \texttt{src} (I); 1]\f]
01656 (when m.cols=src.channels()+1 )
01657 
01658 Every element of the N -channel array src is interpreted as N -element
01659 vector that is transformed using the M x N or M x (N+1) matrix m to
01660 M-element vector - the corresponding element of the output array dst .
01661 
01662 The function may be used for geometrical transformation of
01663 N -dimensional points, arbitrary linear color space transformation (such
01664 as various kinds of RGB to YUV transforms), shuffling the image
01665 channels, and so forth.
01666 @param src input array that must have as many channels (1 to 4) as
01667 m.cols or m.cols-1.
01668 @param dst output array of the same size and depth as src; it has as
01669 many channels as m.rows.
01670 @param m transformation 2x2 or 2x3 floating-point matrix.
01671 @sa perspectiveTransform, getAffineTransform, estimateAffine2D, warpAffine, warpPerspective
01672 */
01673 CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m );
01674 
01675 /** @brief Performs the perspective matrix transformation of vectors.
01676 
01677 The function cv::perspectiveTransform transforms every element of src by
01678 treating it as a 2D or 3D vector, in the following way:
01679 \f[(x, y, z)  \rightarrow (x'/w, y'/w, z'/w)\f]
01680 where
01681 \f[(x', y', z', w') =  \texttt{mat} \cdot \begin{bmatrix} x & y & z & 1  \end{bmatrix}\f]
01682 and
01683 \f[w =  \fork{w'}{if \(w' \ne 0\)}{\infty}{otherwise}\f]
01684 
01685 Here a 3D vector transformation is shown. In case of a 2D vector
01686 transformation, the z component is omitted.
01687 
01688 @note The function transforms a sparse set of 2D or 3D vectors. If you
01689 want to transform an image using perspective transformation, use
01690 warpPerspective . If you have an inverse problem, that is, you want to
01691 compute the most probable perspective transformation out of several
01692 pairs of corresponding points, you can use getPerspectiveTransform or
01693 findHomography .
01694 @param src input two-channel or three-channel floating-point array; each
01695 element is a 2D/3D vector to be transformed.
01696 @param dst output array of the same size and type as src.
01697 @param m 3x3 or 4x4 floating-point transformation matrix.
01698 @sa  transform, warpPerspective, getPerspectiveTransform, findHomography
01699 */
01700 CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m );
01701 
01702 /** @brief Copies the lower or the upper half of a square matrix to another half.
01703 
01704 The function cv::completeSymm copies the lower half of a square matrix to
01705 its another half. The matrix diagonal remains unchanged:
01706 *   \f$\texttt{mtx}_{ij}=\texttt{mtx}_{ji}\f$ for \f$i > j\f$ if
01707     lowerToUpper=false
01708 *   \f$\texttt{mtx}_{ij}=\texttt{mtx}_{ji}\f$ for \f$i < j\f$ if
01709     lowerToUpper=true
01710 @param mtx input-output floating-point square matrix.
01711 @param lowerToUpper operation flag; if true, the lower half is copied to
01712 the upper half. Otherwise, the upper half is copied to the lower half.
01713 @sa flip, transpose
01714 */
01715 CV_EXPORTS_W void completeSymm(InputOutputArray mtx, bool lowerToUpper = false);
01716 
01717 /** @brief Initializes a scaled identity matrix.
01718 
01719 The function cv::setIdentity initializes a scaled identity matrix:
01720 \f[\texttt{mtx} (i,j)= \fork{\texttt{value}}{ if \(i=j\)}{0}{otherwise}\f]
01721 
01722 The function can also be emulated using the matrix initializers and the
01723 matrix expressions:
01724 @code
01725     Mat A = Mat::eye(4, 3, CV_32F)*5;
01726     // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]]
01727 @endcode
01728 @param mtx matrix to initialize (not necessarily square).
01729 @param s value to assign to diagonal elements.
01730 @sa Mat::zeros, Mat::ones, Mat::setTo, Mat::operator=
01731 */
01732 CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s = Scalar(1));
01733 
01734 /** @brief Returns the determinant of a square floating-point matrix.
01735 
01736 The function cv::determinant calculates and returns the determinant of the
01737 specified matrix. For small matrices ( mtx.cols=mtx.rows<=3 ), the
01738 direct method is used. For larger matrices, the function uses LU
01739 factorization with partial pivoting.
01740 
01741 For symmetric positively-determined matrices, it is also possible to use
01742 eigen decomposition to calculate the determinant.
01743 @param mtx input matrix that must have CV_32FC1 or CV_64FC1 type and
01744 square size.
01745 @sa trace, invert, solve, eigen, @ref MatrixExpressions
01746 */
01747 CV_EXPORTS_W double determinant(InputArray mtx);
01748 
01749 /** @brief Returns the trace of a matrix.
01750 
01751 The function cv::trace returns the sum of the diagonal elements of the
01752 matrix mtx .
01753 \f[\mathrm{tr} ( \texttt{mtx} ) =  \sum _i  \texttt{mtx} (i,i)\f]
01754 @param mtx input matrix.
01755 */
01756 CV_EXPORTS_W Scalar trace(InputArray mtx);
01757 
01758 /** @brief Finds the inverse or pseudo-inverse of a matrix.
01759 
01760 The function cv::invert inverts the matrix src and stores the result in dst
01761 . When the matrix src is singular or non-square, the function calculates
01762 the pseudo-inverse matrix (the dst matrix) so that norm(src\*dst - I) is
01763 minimal, where I is an identity matrix.
01764 
01765 In case of the DECOMP_LU method, the function returns non-zero value if
01766 the inverse has been successfully calculated and 0 if src is singular.
01767 
01768 In case of the DECOMP_SVD method, the function returns the inverse
01769 condition number of src (the ratio of the smallest singular value to the
01770 largest singular value) and 0 if src is singular. The SVD method
01771 calculates a pseudo-inverse matrix if src is singular.
01772 
01773 Similarly to DECOMP_LU, the method DECOMP_CHOLESKY works only with
01774 non-singular square matrices that should also be symmetrical and
01775 positively defined. In this case, the function stores the inverted
01776 matrix in dst and returns non-zero. Otherwise, it returns 0.
01777 
01778 @param src input floating-point M x N matrix.
01779 @param dst output matrix of N x M size and the same type as src.
01780 @param flags inversion method (cv::DecompTypes)
01781 @sa solve, SVD
01782 */
01783 CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags = DECOMP_LU);
01784 
01785 /** @brief Solves one or more linear systems or least-squares problems.
01786 
01787 The function cv::solve solves a linear system or least-squares problem (the
01788 latter is possible with SVD or QR methods, or by specifying the flag
01789 DECOMP_NORMAL ):
01790 \f[\texttt{dst} =  \arg \min _X \| \texttt{src1} \cdot \texttt{X} -  \texttt{src2} \|\f]
01791 
01792 If DECOMP_LU or DECOMP_CHOLESKY method is used, the function returns 1
01793 if src1 (or \f$\texttt{src1}^T\texttt{src1}\f$ ) is non-singular. Otherwise,
01794 it returns 0. In the latter case, dst is not valid. Other methods find a
01795 pseudo-solution in case of a singular left-hand side part.
01796 
01797 @note If you want to find a unity-norm solution of an under-defined
01798 singular system \f$\texttt{src1}\cdot\texttt{dst}=0\f$ , the function solve
01799 will not do the work. Use SVD::solveZ instead.
01800 
01801 @param src1 input matrix on the left-hand side of the system.
01802 @param src2 input matrix on the right-hand side of the system.
01803 @param dst output solution.
01804 @param flags solution (matrix inversion) method (cv::DecompTypes)
01805 @sa invert, SVD, eigen
01806 */
01807 CV_EXPORTS_W bool solve(InputArray src1, InputArray src2,
01808                         OutputArray dst, int flags = DECOMP_LU);
01809 
01810 /** @brief Sorts each row or each column of a matrix.
01811 
01812 The function cv::sort sorts each matrix row or each matrix column in
01813 ascending or descending order. So you should pass two operation flags to
01814 get desired behaviour. If you want to sort matrix rows or columns
01815 lexicographically, you can use STL std::sort generic function with the
01816 proper comparison predicate.
01817 
01818 @param src input single-channel array.
01819 @param dst output array of the same size and type as src.
01820 @param flags operation flags, a combination of cv::SortFlags
01821 @sa sortIdx, randShuffle
01822 */
01823 CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags);
01824 
01825 /** @brief Sorts each row or each column of a matrix.
01826 
01827 The function cv::sortIdx sorts each matrix row or each matrix column in the
01828 ascending or descending order. So you should pass two operation flags to
01829 get desired behaviour. Instead of reordering the elements themselves, it
01830 stores the indices of sorted elements in the output array. For example:
01831 @code
01832     Mat A = Mat::eye(3,3,CV_32F), B;
01833     sortIdx(A, B, SORT_EVERY_ROW + SORT_ASCENDING);
01834     // B will probably contain
01835     // (because of equal elements in A some permutations are possible):
01836     // [[1, 2, 0], [0, 2, 1], [0, 1, 2]]
01837 @endcode
01838 @param src input single-channel array.
01839 @param dst output integer array of the same size as src.
01840 @param flags operation flags that could be a combination of cv::SortFlags
01841 @sa sort, randShuffle
01842 */
01843 CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags);
01844 
01845 /** @brief Finds the real roots of a cubic equation.
01846 
01847 The function solveCubic finds the real roots of a cubic equation:
01848 -   if coeffs is a 4-element vector:
01849 \f[\texttt{coeffs} [0] x^3 +  \texttt{coeffs} [1] x^2 +  \texttt{coeffs} [2] x +  \texttt{coeffs} [3] = 0\f]
01850 -   if coeffs is a 3-element vector:
01851 \f[x^3 +  \texttt{coeffs} [0] x^2 +  \texttt{coeffs} [1] x +  \texttt{coeffs} [2] = 0\f]
01852 
01853 The roots are stored in the roots array.
01854 @param coeffs equation coefficients, an array of 3 or 4 elements.
01855 @param roots output array of real roots that has 1 or 3 elements.
01856 */
01857 CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots);
01858 
01859 /** @brief Finds the real or complex roots of a polynomial equation.
01860 
01861 The function cv::solvePoly finds real and complex roots of a polynomial equation:
01862 \f[\texttt{coeffs} [n] x^{n} +  \texttt{coeffs} [n-1] x^{n-1} + ... +  \texttt{coeffs} [1] x +  \texttt{coeffs} [0] = 0\f]
01863 @param coeffs array of polynomial coefficients.
01864 @param roots output (complex) array of roots.
01865 @param maxIters maximum number of iterations the algorithm does.
01866 */
01867 CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters = 300);
01868 
01869 /** @brief Calculates eigenvalues and eigenvectors of a symmetric matrix.
01870 
01871 The function cv::eigen calculates just eigenvalues, or eigenvalues and eigenvectors of the symmetric
01872 matrix src:
01873 @code
01874     src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t()
01875 @endcode
01876 @note in the new and the old interfaces different ordering of eigenvalues and eigenvectors
01877 parameters is used.
01878 @param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical
01879 (src ^T^ == src).
01880 @param eigenvalues output vector of eigenvalues of the same type as src; the eigenvalues are stored
01881 in the descending order.
01882 @param eigenvectors output matrix of eigenvectors; it has the same size and type as src; the
01883 eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding
01884 eigenvalues.
01885 @sa completeSymm , PCA
01886 */
01887 CV_EXPORTS_W bool eigen(InputArray src, OutputArray eigenvalues,
01888                         OutputArray eigenvectors = noArray());
01889 
01890 /** @brief Calculates the covariance matrix of a set of vectors.
01891 
01892 The function cv::calcCovarMatrix calculates the covariance matrix and, optionally, the mean vector of
01893 the set of input vectors.
01894 @param samples samples stored as separate matrices
01895 @param nsamples number of samples
01896 @param covar output covariance matrix of the type ctype and square size.
01897 @param mean input or output (depending on the flags) array as the average value of the input vectors.
01898 @param flags operation flags as a combination of cv::CovarFlags
01899 @param ctype type of the matrixl; it equals 'CV_64F' by default.
01900 @sa PCA, mulTransposed, Mahalanobis
01901 @todo InputArrayOfArrays
01902 */
01903 CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean,
01904                                  int flags, int ctype = CV_64F);
01905 
01906 /** @overload
01907 @note use cv::COVAR_ROWS or cv::COVAR_COLS flag
01908 @param samples samples stored as rows/columns of a single matrix.
01909 @param covar output covariance matrix of the type ctype and square size.
01910 @param mean input or output (depending on the flags) array as the average value of the input vectors.
01911 @param flags operation flags as a combination of cv::CovarFlags
01912 @param ctype type of the matrixl; it equals 'CV_64F' by default.
01913 */
01914 CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar,
01915                                    InputOutputArray mean, int flags, int ctype = CV_64F);
01916 
01917 /** wrap PCA::operator() */
01918 CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean,
01919                              OutputArray eigenvectors, int maxComponents = 0);
01920 
01921 /** wrap PCA::operator() */
01922 CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean,
01923                              OutputArray eigenvectors, double retainedVariance);
01924 
01925 /** wrap PCA::project */
01926 CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean,
01927                              InputArray eigenvectors, OutputArray result);
01928 
01929 /** wrap PCA::backProject */
01930 CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean,
01931                                  InputArray eigenvectors, OutputArray result);
01932 
01933 /** wrap SVD::compute */
01934 CV_EXPORTS_W void SVDecomp( InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags = 0 );
01935 
01936 /** wrap SVD::backSubst */
01937 CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt,
01938                                InputArray rhs, OutputArray dst );
01939 
01940 /** @brief Calculates the Mahalanobis distance between two vectors.
01941 
01942 The function cv::Mahalanobis calculates and returns the weighted distance between two vectors:
01943 \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]
01944 The covariance matrix may be calculated using the cv::calcCovarMatrix function and then inverted using
01945 the invert function (preferably using the cv::DECOMP_SVD method, as the most accurate).
01946 @param v1 first 1D input vector.
01947 @param v2 second 1D input vector.
01948 @param icovar inverse covariance matrix.
01949 */
01950 CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar);
01951 
01952 /** @brief Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array.
01953 
01954 The function cv::dft performs one of the following:
01955 -   Forward the Fourier transform of a 1D vector of N elements:
01956     \f[Y = F^{(N)}  \cdot X,\f]
01957     where \f$F^{(N)}_{jk}=\exp(-2\pi i j k/N)\f$ and \f$i=\sqrt{-1}\f$
01958 -   Inverse the Fourier transform of a 1D vector of N elements:
01959     \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]
01960     where \f$F^*=\left(\textrm{Re}(F^{(N)})-\textrm{Im}(F^{(N)})\right)^T\f$
01961 -   Forward the 2D Fourier transform of a M x N matrix:
01962     \f[Y = F^{(M)}  \cdot X  \cdot F^{(N)}\f]
01963 -   Inverse the 2D Fourier transform of a M x N matrix:
01964     \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]
01965 
01966 In case of real (single-channel) data, the output spectrum of the forward Fourier transform or input
01967 spectrum of the inverse Fourier transform can be represented in a packed format called *CCS*
01968 (complex-conjugate-symmetrical). It was borrowed from IPL (Intel\* Image Processing Library). Here
01969 is how 2D *CCS* spectrum looks:
01970 \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]
01971 
01972 In case of 1D transform of a real vector, the output looks like the first row of the matrix above.
01973 
01974 So, the function chooses an operation mode depending on the flags and size of the input array:
01975 -   If DFT_ROWS is set or the input array has a single row or single column, the function
01976     performs a 1D forward or inverse transform of each row of a matrix when DFT_ROWS is set.
01977     Otherwise, it performs a 2D transform.
01978 -   If the input array is real and DFT_INVERSE is not set, the function performs a forward 1D or
01979     2D transform:
01980     -   When DFT_COMPLEX_OUTPUT is set, the output is a complex matrix of the same size as
01981         input.
01982     -   When DFT_COMPLEX_OUTPUT is not set, the output is a real matrix of the same size as
01983         input. In case of 2D transform, it uses the packed format as shown above. In case of a
01984         single 1D transform, it looks like the first row of the matrix above. In case of
01985         multiple 1D transforms (when using the DFT_ROWS flag), each row of the output matrix
01986         looks like the first row of the matrix above.
01987 -   If the input array is complex and either DFT_INVERSE or DFT_REAL_OUTPUT are not set, the
01988     output is a complex array of the same size as input. The function performs a forward or
01989     inverse 1D or 2D transform of the whole input array or each row of the input array
01990     independently, depending on the flags DFT_INVERSE and DFT_ROWS.
01991 -   When DFT_INVERSE is set and the input array is real, or it is complex but DFT_REAL_OUTPUT
01992     is set, the output is a real array of the same size as input. The function performs a 1D or 2D
01993     inverse transformation of the whole input array or each individual row, depending on the flags
01994     DFT_INVERSE and DFT_ROWS.
01995 
01996 If DFT_SCALE is set, the scaling is done after the transformation.
01997 
01998 Unlike dct , the function supports arrays of arbitrary size. But only those arrays are processed
01999 efficiently, whose sizes can be factorized in a product of small prime numbers (2, 3, and 5 in the
02000 current implementation). Such an efficient DFT size can be calculated using the getOptimalDFTSize
02001 method.
02002 
02003 The sample below illustrates how to calculate a DFT-based convolution of two 2D real arrays:
02004 @code
02005     void convolveDFT(InputArray A, InputArray B, OutputArray C)
02006     {
02007         // reallocate the output array if needed
02008         C.create(abs(A.rows - B.rows)+1, abs(A.cols - B.cols)+1, A.type());
02009         Size dftSize;
02010         // calculate the size of DFT transform
02011         dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1);
02012         dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1);
02013 
02014         // allocate temporary buffers and initialize them with 0's
02015         Mat tempA(dftSize, A.type(), Scalar::all(0));
02016         Mat tempB(dftSize, B.type(), Scalar::all(0));
02017 
02018         // copy A and B to the top-left corners of tempA and tempB, respectively
02019         Mat roiA(tempA, Rect(0,0,A.cols,A.rows));
02020         A.copyTo(roiA);
02021         Mat roiB(tempB, Rect(0,0,B.cols,B.rows));
02022         B.copyTo(roiB);
02023 
02024         // now transform the padded A & B in-place;
02025         // use "nonzeroRows" hint for faster processing
02026         dft(tempA, tempA, 0, A.rows);
02027         dft(tempB, tempB, 0, B.rows);
02028 
02029         // multiply the spectrums;
02030         // the function handles packed spectrum representations well
02031         mulSpectrums(tempA, tempB, tempA);
02032 
02033         // transform the product back from the frequency domain.
02034         // Even though all the result rows will be non-zero,
02035         // you need only the first C.rows of them, and thus you
02036         // pass nonzeroRows == C.rows
02037         dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows);
02038 
02039         // now copy the result back to C.
02040         tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C);
02041 
02042         // all the temporary buffers will be deallocated automatically
02043     }
02044 @endcode
02045 To optimize this sample, consider the following approaches:
02046 -   Since nonzeroRows != 0 is passed to the forward transform calls and since A and B are copied to
02047     the top-left corners of tempA and tempB, respectively, it is not necessary to clear the whole
02048     tempA and tempB. It is only necessary to clear the tempA.cols - A.cols ( tempB.cols - B.cols)
02049     rightmost columns of the matrices.
02050 -   This DFT-based convolution does not have to be applied to the whole big arrays, especially if B
02051     is significantly smaller than A or vice versa. Instead, you can calculate convolution by parts.
02052     To do this, you need to split the output array C into multiple tiles. For each tile, estimate
02053     which parts of A and B are required to calculate convolution in this tile. If the tiles in C are
02054     too small, the speed will decrease a lot because of repeated work. In the ultimate case, when
02055     each tile in C is a single pixel, the algorithm becomes equivalent to the naive convolution
02056     algorithm. If the tiles are too big, the temporary arrays tempA and tempB become too big and
02057     there is also a slowdown because of bad cache locality. So, there is an optimal tile size
02058     somewhere in the middle.
02059 -   If different tiles in C can be calculated in parallel and, thus, the convolution is done by
02060     parts, the loop can be threaded.
02061 
02062 All of the above improvements have been implemented in matchTemplate and filter2D . Therefore, by
02063 using them, you can get the performance even better than with the above theoretically optimal
02064 implementation. Though, those two functions actually calculate cross-correlation, not convolution,
02065 so you need to "flip" the second convolution operand B vertically and horizontally using flip .
02066 @note
02067 -   An example using the discrete fourier transform can be found at
02068     opencv_source_code/samples/cpp/dft.cpp
02069 -   (Python) An example using the dft functionality to perform Wiener deconvolution can be found
02070     at opencv_source/samples/python/deconvolution.py
02071 -   (Python) An example rearranging the quadrants of a Fourier image can be found at
02072     opencv_source/samples/python/dft.py
02073 @param src input array that could be real or complex.
02074 @param dst output array whose size and type depends on the flags .
02075 @param flags transformation flags, representing a combination of the cv::DftFlags
02076 @param nonzeroRows when the parameter is not zero, the function assumes that only the first
02077 nonzeroRows rows of the input array (DFT_INVERSE is not set) or only the first nonzeroRows of the
02078 output array (DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the
02079 rows more efficiently and save some time; this technique is very useful for calculating array
02080 cross-correlation or convolution using DFT.
02081 @sa dct , getOptimalDFTSize , mulSpectrums, filter2D , matchTemplate , flip , cartToPolar ,
02082 magnitude , phase
02083 */
02084 CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0);
02085 
02086 /** @brief Calculates the inverse Discrete Fourier Transform of a 1D or 2D array.
02087 
02088 idft(src, dst, flags) is equivalent to dft(src, dst, flags | DFT_INVERSE) .
02089 @note None of dft and idft scales the result by default. So, you should pass DFT_SCALE to one of
02090 dft or idft explicitly to make these transforms mutually inverse.
02091 @sa dft, dct, idct, mulSpectrums, getOptimalDFTSize
02092 @param src input floating-point real or complex array.
02093 @param dst output array whose size and type depend on the flags.
02094 @param flags operation flags (see dft and cv::DftFlags).
02095 @param nonzeroRows number of dst rows to process; the rest of the rows have undefined content (see
02096 the convolution sample in dft description.
02097 */
02098 CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0);
02099 
02100 /** @brief Performs a forward or inverse discrete Cosine transform of 1D or 2D array.
02101 
02102 The function cv::dct performs a forward or inverse discrete Cosine transform (DCT) of a 1D or 2D
02103 floating-point array:
02104 -   Forward Cosine transform of a 1D vector of N elements:
02105     \f[Y = C^{(N)}  \cdot X\f]
02106     where
02107     \f[C^{(N)}_{jk}= \sqrt{\alpha_j/N} \cos \left ( \frac{\pi(2k+1)j}{2N} \right )\f]
02108     and
02109     \f$\alpha_0=1\f$, \f$\alpha_j=2\f$ for *j > 0*.
02110 -   Inverse Cosine transform of a 1D vector of N elements:
02111     \f[X =  \left (C^{(N)} \right )^{-1}  \cdot Y =  \left (C^{(N)} \right )^T  \cdot Y\f]
02112     (since \f$C^{(N)}\f$ is an orthogonal matrix, \f$C^{(N)} \cdot \left(C^{(N)}\right)^T = I\f$ )
02113 -   Forward 2D Cosine transform of M x N matrix:
02114     \f[Y = C^{(N)}  \cdot X  \cdot \left (C^{(N)} \right )^T\f]
02115 -   Inverse 2D Cosine transform of M x N matrix:
02116     \f[X =  \left (C^{(N)} \right )^T  \cdot X  \cdot C^{(N)}\f]
02117 
02118 The function chooses the mode of operation by looking at the flags and size of the input array:
02119 -   If (flags & DCT_INVERSE) == 0 , the function does a forward 1D or 2D transform. Otherwise, it
02120     is an inverse 1D or 2D transform.
02121 -   If (flags & DCT_ROWS) != 0 , the function performs a 1D transform of each row.
02122 -   If the array is a single column or a single row, the function performs a 1D transform.
02123 -   If none of the above is true, the function performs a 2D transform.
02124 
02125 @note Currently dct supports even-size arrays (2, 4, 6 ...). For data analysis and approximation, you
02126 can pad the array when necessary.
02127 Also, the function performance depends very much, and not monotonically, on the array size (see
02128 getOptimalDFTSize ). In the current implementation DCT of a vector of size N is calculated via DFT
02129 of a vector of size N/2 . Thus, the optimal DCT size N1 >= N can be calculated as:
02130 @code
02131     size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); }
02132     N1 = getOptimalDCTSize(N);
02133 @endcode
02134 @param src input floating-point array.
02135 @param dst output array of the same size and type as src .
02136 @param flags transformation flags as a combination of cv::DftFlags (DCT_*)
02137 @sa dft , getOptimalDFTSize , idct
02138 */
02139 CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags = 0);
02140 
02141 /** @brief Calculates the inverse Discrete Cosine Transform of a 1D or 2D array.
02142 
02143 idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE).
02144 @param src input floating-point single-channel array.
02145 @param dst output array of the same size and type as src.
02146 @param flags operation flags.
02147 @sa  dct, dft, idft, getOptimalDFTSize
02148 */
02149 CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags = 0);
02150 
02151 /** @brief Performs the per-element multiplication of two Fourier spectrums.
02152 
02153 The function cv::mulSpectrums performs the per-element multiplication of the two CCS-packed or complex
02154 matrices that are results of a real or complex Fourier transform.
02155 
02156 The function, together with dft and idft , may be used to calculate convolution (pass conjB=false )
02157 or correlation (pass conjB=true ) of two arrays rapidly. When the arrays are complex, they are
02158 simply multiplied (per element) with an optional conjugation of the second-array elements. When the
02159 arrays are real, they are assumed to be CCS-packed (see dft for details).
02160 @param a first input array.
02161 @param b second input array of the same size and type as src1 .
02162 @param c output array of the same size and type as src1 .
02163 @param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that
02164 each 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.
02165 @param conjB optional flag that conjugates the second input array before the multiplication (true)
02166 or not (false).
02167 */
02168 CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c,
02169                                int flags, bool conjB = false);
02170 
02171 /** @brief Returns the optimal DFT size for a given vector size.
02172 
02173 DFT performance is not a monotonic function of a vector size. Therefore, when you calculate
02174 convolution of two arrays or perform the spectral analysis of an array, it usually makes sense to
02175 pad the input data with zeros to get a bit larger array that can be transformed much faster than the
02176 original one. Arrays whose size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process.
02177 Though, the arrays whose size is a product of 2's, 3's, and 5's (for example, 300 = 5\*5\*3\*2\*2)
02178 are also processed quite efficiently.
02179 
02180 The function cv::getOptimalDFTSize returns the minimum number N that is greater than or equal to vecsize
02181 so that the DFT of a vector of size N can be processed efficiently. In the current implementation N
02182 = 2 ^p^ \* 3 ^q^ \* 5 ^r^ for some integer p, q, r.
02183 
02184 The function returns a negative number if vecsize is too large (very close to INT_MAX ).
02185 
02186 While the function cannot be used directly to estimate the optimal vector size for DCT transform
02187 (since the current DCT implementation supports only even-size vectors), it can be easily processed
02188 as getOptimalDFTSize((vecsize+1)/2)\*2.
02189 @param vecsize vector size.
02190 @sa dft , dct , idft , idct , mulSpectrums
02191 */
02192 CV_EXPORTS_W int getOptimalDFTSize(int vecsize);
02193 
02194 /** @brief Returns the default random number generator.
02195 
02196 The function cv::theRNG returns the default random number generator. For each thread, there is a
02197 separate random number generator, so you can use the function safely in multi-thread environments.
02198 If you just need to get a single random number using this generator or initialize an array, you can
02199 use randu or randn instead. But if you are going to generate many random numbers inside a loop, it
02200 is much faster to use this function to retrieve the generator and then use RNG::operator _Tp() .
02201 @sa RNG, randu, randn
02202 */
02203 CV_EXPORTS RNG& theRNG();
02204 
02205 /** @brief Sets state of default random number generator.
02206 
02207 The function cv::setRNGSeed sets state of default random number generator to custom value.
02208 @param seed new state for default random number generator
02209 @sa RNG, randu, randn
02210 */
02211 CV_EXPORTS_W void setRNGSeed(int seed);
02212 
02213 /** @brief Generates a single uniformly-distributed random number or an array of random numbers.
02214 
02215 Non-template variant of the function fills the matrix dst with uniformly-distributed
02216 random numbers from the specified range:
02217 \f[\texttt{low} _c  \leq \texttt{dst} (I)_c <  \texttt{high} _c\f]
02218 @param dst output array of random numbers; the array must be pre-allocated.
02219 @param low inclusive lower boundary of the generated random numbers.
02220 @param high exclusive upper boundary of the generated random numbers.
02221 @sa RNG, randn, theRNG
02222 */
02223 CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high);
02224 
02225 /** @brief Fills the array with normally distributed random numbers.
02226 
02227 The function cv::randn fills the matrix dst with normally distributed random numbers with the specified
02228 mean vector and the standard deviation matrix. The generated random numbers are clipped to fit the
02229 value range of the output array data type.
02230 @param dst output array of random numbers; the array must be pre-allocated and have 1 to 4 channels.
02231 @param mean mean value (expectation) of the generated random numbers.
02232 @param stddev standard deviation of the generated random numbers; it can be either a vector (in
02233 which case a diagonal standard deviation matrix is assumed) or a square matrix.
02234 @sa RNG, randu
02235 */
02236 CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev);
02237 
02238 /** @brief Shuffles the array elements randomly.
02239 
02240 The function cv::randShuffle shuffles the specified 1D array by randomly choosing pairs of elements and
02241 swapping them. The number of such swap operations will be dst.rows\*dst.cols\*iterFactor .
02242 @param dst input/output numerical 1D array.
02243 @param iterFactor scale factor that determines the number of random swap operations (see the details
02244 below).
02245 @param rng optional random number generator used for shuffling; if it is zero, theRNG () is used
02246 instead.
02247 @sa RNG, sort
02248 */
02249 CV_EXPORTS_W void randShuffle(InputOutputArray dst, double iterFactor = 1., RNG* rng = 0);
02250 
02251 /** @brief Principal Component Analysis
02252 
02253 The class is used to calculate a special basis for a set of vectors. The
02254 basis will consist of eigenvectors of the covariance matrix calculated
02255 from the input set of vectors. The class %PCA can also transform
02256 vectors to/from the new coordinate space defined by the basis. Usually,
02257 in this new coordinate system, each vector from the original set (and
02258 any linear combination of such vectors) can be quite accurately
02259 approximated by taking its first few components, corresponding to the
02260 eigenvectors of the largest eigenvalues of the covariance matrix.
02261 Geometrically it means that you calculate a projection of the vector to
02262 a subspace formed by a few eigenvectors corresponding to the dominant
02263 eigenvalues of the covariance matrix. And usually such a projection is
02264 very close to the original vector. So, you can represent the original
02265 vector from a high-dimensional space with a much shorter vector
02266 consisting of the projected vector's coordinates in the subspace. Such a
02267 transformation is also known as Karhunen-Loeve Transform, or KLT.
02268 See http://en.wikipedia.org/wiki/Principal_component_analysis
02269 
02270 The sample below is the function that takes two matrices. The first
02271 function stores a set of vectors (a row per vector) that is used to
02272 calculate PCA. The second function stores another "test" set of vectors
02273 (a row per vector). First, these vectors are compressed with PCA, then
02274 reconstructed back, and then the reconstruction error norm is computed
02275 and printed for each vector. :
02276 
02277 @code{.cpp}
02278 using namespace cv;
02279 
02280 PCA compressPCA(const Mat& pcaset, int maxComponents,
02281                 const Mat& testset, Mat& compressed)
02282 {
02283     PCA pca(pcaset, // pass the data
02284             Mat(), // we do not have a pre-computed mean vector,
02285                    // so let the PCA engine to compute it
02286             PCA::DATA_AS_ROW, // indicate that the vectors
02287                                 // are stored as matrix rows
02288                                 // (use PCA::DATA_AS_COL if the vectors are
02289                                 // the matrix columns)
02290             maxComponents // specify, how many principal components to retain
02291             );
02292     // if there is no test data, just return the computed basis, ready-to-use
02293     if( !testset.data )
02294         return pca;
02295     CV_Assert( testset.cols == pcaset.cols );
02296 
02297     compressed.create(testset.rows, maxComponents, testset.type());
02298 
02299     Mat reconstructed;
02300     for( int i = 0; i < testset.rows; i++ )
02301     {
02302         Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed;
02303         // compress the vector, the result will be stored
02304         // in the i-th row of the output matrix
02305         pca.project(vec, coeffs);
02306         // and then reconstruct it
02307         pca.backProject(coeffs, reconstructed);
02308         // and measure the error
02309         printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2));
02310     }
02311     return pca;
02312 }
02313 @endcode
02314 @sa calcCovarMatrix, mulTransposed, SVD, dft, dct
02315 */
02316 class CV_EXPORTS PCA
02317 {
02318 public:
02319     enum Flags  { DATA_AS_ROW = 0, //!< indicates that the input samples are stored as matrix rows
02320                  DATA_AS_COL = 1, //!< indicates that the input samples are stored as matrix columns
02321                  USE_AVG     = 2  //!
02322                };
02323 
02324     /** @brief default constructor
02325 
02326     The default constructor initializes an empty %PCA structure. The other
02327     constructors initialize the structure and call PCA::operator()().
02328     */
02329     PCA();
02330 
02331     /** @overload
02332     @param data input samples stored as matrix rows or matrix columns.
02333     @param mean optional mean value; if the matrix is empty (@c noArray()),
02334     the mean is computed from the data.
02335     @param flags operation flags; currently the parameter is only used to
02336     specify the data layout (PCA::Flags)
02337     @param maxComponents maximum number of components that %PCA should
02338     retain; by default, all the components are retained.
02339     */
02340     PCA(InputArray data, InputArray mean, int flags, int maxComponents = 0);
02341 
02342     /** @overload
02343     @param data input samples stored as matrix rows or matrix columns.
02344     @param mean optional mean value; if the matrix is empty (noArray()),
02345     the mean is computed from the data.
02346     @param flags operation flags; currently the parameter is only used to
02347     specify the data layout (PCA::Flags)
02348     @param retainedVariance Percentage of variance that PCA should retain.
02349     Using this parameter will let the PCA decided how many components to
02350     retain but it will always keep at least 2.
02351     */
02352     PCA(InputArray data, InputArray mean, int flags, double retainedVariance);
02353 
02354     /** @brief performs %PCA
02355 
02356     The operator performs %PCA of the supplied dataset. It is safe to reuse
02357     the same PCA structure for multiple datasets. That is, if the structure
02358     has been previously used with another dataset, the existing internal
02359     data is reclaimed and the new @ref eigenvalues, @ref eigenvectors and @ref
02360     mean are allocated and computed.
02361 
02362     The computed @ref eigenvalues are sorted from the largest to the smallest and
02363     the corresponding @ref eigenvectors are stored as eigenvectors rows.
02364 
02365     @param data input samples stored as the matrix rows or as the matrix
02366     columns.
02367     @param mean optional mean value; if the matrix is empty (noArray()),
02368     the mean is computed from the data.
02369     @param flags operation flags; currently the parameter is only used to
02370     specify the data layout. (Flags)
02371     @param maxComponents maximum number of components that PCA should
02372     retain; by default, all the components are retained.
02373     */
02374     PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents = 0);
02375 
02376     /** @overload
02377     @param data input samples stored as the matrix rows or as the matrix
02378     columns.
02379     @param mean optional mean value; if the matrix is empty (noArray()),
02380     the mean is computed from the data.
02381     @param flags operation flags; currently the parameter is only used to
02382     specify the data layout. (PCA::Flags)
02383     @param retainedVariance Percentage of variance that %PCA should retain.
02384     Using this parameter will let the %PCA decided how many components to
02385     retain but it will always keep at least 2.
02386      */
02387     PCA& operator()(InputArray data, InputArray mean, int flags, double retainedVariance);
02388 
02389     /** @brief Projects vector(s) to the principal component subspace.
02390 
02391     The methods project one or more vectors to the principal component
02392     subspace, where each vector projection is represented by coefficients in
02393     the principal component basis. The first form of the method returns the
02394     matrix that the second form writes to the result. So the first form can
02395     be used as a part of expression while the second form can be more
02396     efficient in a processing loop.
02397     @param vec input vector(s); must have the same dimensionality and the
02398     same layout as the input data used at %PCA phase, that is, if
02399     DATA_AS_ROW are specified, then `vec.cols==data.cols`
02400     (vector dimensionality) and `vec.rows` is the number of vectors to
02401     project, and the same is true for the PCA::DATA_AS_COL case.
02402     */
02403     Mat project(InputArray vec) const;
02404 
02405     /** @overload
02406     @param vec input vector(s); must have the same dimensionality and the
02407     same layout as the input data used at PCA phase, that is, if
02408     DATA_AS_ROW are specified, then `vec.cols==data.cols`
02409     (vector dimensionality) and `vec.rows` is the number of vectors to
02410     project, and the same is true for the PCA::DATA_AS_COL case.
02411     @param result output vectors; in case of PCA::DATA_AS_COL, the
02412     output matrix has as many columns as the number of input vectors, this
02413     means that `result.cols==vec.cols` and the number of rows match the
02414     number of principal components (for example, `maxComponents` parameter
02415     passed to the constructor).
02416      */
02417     void project(InputArray vec, OutputArray result) const;
02418 
02419     /** @brief Reconstructs vectors from their PC projections.
02420 
02421     The methods are inverse operations to PCA::project. They take PC
02422     coordinates of projected vectors and reconstruct the original vectors.
02423     Unless all the principal components have been retained, the
02424     reconstructed vectors are different from the originals. But typically,
02425     the difference is small if the number of components is large enough (but
02426     still much smaller than the original vector dimensionality). As a
02427     result, PCA is used.
02428     @param vec coordinates of the vectors in the principal component
02429     subspace, the layout and size are the same as of PCA::project output
02430     vectors.
02431      */
02432     Mat backProject(InputArray vec) const;
02433 
02434     /** @overload
02435     @param vec coordinates of the vectors in the principal component
02436     subspace, the layout and size are the same as of PCA::project output
02437     vectors.
02438     @param result reconstructed vectors; the layout and size are the same as
02439     of PCA::project input vectors.
02440      */
02441     void backProject(InputArray vec, OutputArray result) const;
02442 
02443     /** @brief write PCA objects
02444 
02445     Writes @ref eigenvalues @ref eigenvectors and @ref mean to specified FileStorage
02446      */
02447     void write(FileStorage& fs) const;
02448 
02449     /** @brief load PCA objects
02450 
02451     Loads @ref eigenvalues @ref eigenvectors and @ref mean from specified FileNode
02452      */
02453     void read(const FileNode& fn);
02454 
02455     Mat eigenvectors; //!< eigenvectors of the covariation matrix
02456     Mat eigenvalues; //!< eigenvalues of the covariation matrix
02457     Mat mean; //!< mean value subtracted before the projection and added after the back projection
02458 };
02459 
02460 /** @example pca.cpp
02461   An example using %PCA for dimensionality reduction while maintaining an amount of variance
02462  */
02463 
02464 /**
02465    @brief Linear Discriminant Analysis
02466    @todo document this class
02467  */
02468 class CV_EXPORTS LDA
02469 {
02470 public:
02471     /** @brief constructor
02472     Initializes a LDA with num_components (default 0).
02473     */
02474     explicit LDA(int num_components = 0);
02475 
02476     /** Initializes and performs a Discriminant Analysis with Fisher's
02477      Optimization Criterion on given data in src and corresponding labels
02478      in labels. If 0 (or less) number of components are given, they are
02479      automatically determined for given data in computation.
02480     */
02481     LDA(InputArrayOfArrays src, InputArray labels, int num_components = 0);
02482 
02483     /** Serializes this object to a given filename.
02484       */
02485     void save(const String& filename) const;
02486 
02487     /** Deserializes this object from a given filename.
02488       */
02489     void load(const String& filename);
02490 
02491     /** Serializes this object to a given cv::FileStorage.
02492       */
02493     void save(FileStorage& fs) const;
02494 
02495     /** Deserializes this object from a given cv::FileStorage.
02496       */
02497     void load(const FileStorage& node);
02498 
02499     /** destructor
02500       */
02501     ~LDA();
02502 
02503     /** Compute the discriminants for data in src (row aligned) and labels.
02504       */
02505     void compute(InputArrayOfArrays src, InputArray labels);
02506 
02507     /** Projects samples into the LDA subspace.
02508         src may be one or more row aligned samples.
02509       */
02510     Mat project(InputArray src);
02511 
02512     /** Reconstructs projections from the LDA subspace.
02513         src may be one or more row aligned projections.
02514       */
02515     Mat reconstruct(InputArray src);
02516 
02517     /** Returns the eigenvectors of this LDA.
02518       */
02519     Mat eigenvectors() const { return _eigenvectors; }
02520 
02521     /** Returns the eigenvalues of this LDA.
02522       */
02523     Mat eigenvalues() const { return _eigenvalues; }
02524 
02525     static Mat subspaceProject(InputArray W, InputArray mean, InputArray src);
02526     static Mat subspaceReconstruct(InputArray W, InputArray mean, InputArray src);
02527 
02528 protected:
02529     bool _dataAsRow; // unused, but needed for 3.0 ABI compatibility.
02530     int _num_components;
02531     Mat _eigenvectors;
02532     Mat _eigenvalues;
02533     void lda(InputArrayOfArrays src, InputArray labels);
02534 };
02535 
02536 /** @brief Singular Value Decomposition
02537 
02538 Class for computing Singular Value Decomposition of a floating-point
02539 matrix. The Singular Value Decomposition is used to solve least-square
02540 problems, under-determined linear systems, invert matrices, compute
02541 condition numbers, and so on.
02542 
02543 If you want to compute a condition number of a matrix or an absolute value of
02544 its determinant, you do not need `u` and `vt`. You can pass
02545 flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that full-size u
02546 and vt must be computed, which is not necessary most of the time.
02547 
02548 @sa invert, solve, eigen, determinant
02549 */
02550 class CV_EXPORTS SVD
02551 {
02552 public:
02553     enum Flags  {
02554         /** allow the algorithm to modify the decomposed matrix; it can save space and speed up
02555             processing. currently ignored. */
02556         MODIFY_A = 1,
02557         /** indicates that only a vector of singular values `w` is to be processed, while u and vt
02558             will be set to empty matrices */
02559         NO_UV    = 2,
02560         /** when the matrix is not square, by default the algorithm produces u and vt matrices of
02561             sufficiently large size for the further A reconstruction; if, however, FULL_UV flag is
02562             specified, u and vt will be full-size square orthogonal matrices.*/
02563         FULL_UV  = 4
02564     };
02565 
02566     /** @brief the default constructor
02567 
02568     initializes an empty SVD structure
02569       */
02570     SVD();
02571 
02572     /** @overload
02573     initializes an empty SVD structure and then calls SVD::operator()
02574     @param src decomposed matrix.
02575     @param flags operation flags (SVD::Flags)
02576       */
02577     SVD( InputArray src, int flags = 0 );
02578 
02579     /** @brief the operator that performs SVD. The previously allocated u, w and vt are released.
02580 
02581     The operator performs the singular value decomposition of the supplied
02582     matrix. The u,`vt` , and the vector of singular values w are stored in
02583     the structure. The same SVD structure can be reused many times with
02584     different matrices. Each time, if needed, the previous u,`vt` , and w
02585     are reclaimed and the new matrices are created, which is all handled by
02586     Mat::create.
02587     @param src decomposed matrix.
02588     @param flags operation flags (SVD::Flags)
02589       */
02590     SVD& operator ()( InputArray src, int flags = 0 );
02591 
02592     /** @brief decomposes matrix and stores the results to user-provided matrices
02593 
02594     The methods/functions perform SVD of matrix. Unlike SVD::SVD constructor
02595     and SVD::operator(), they store the results to the user-provided
02596     matrices:
02597 
02598     @code{.cpp}
02599     Mat A, w, u, vt;
02600     SVD::compute(A, w, u, vt);
02601     @endcode
02602 
02603     @param src decomposed matrix
02604     @param w calculated singular values
02605     @param u calculated left singular vectors
02606     @param vt transposed matrix of right singular values
02607     @param flags operation flags - see SVD::SVD.
02608       */
02609     static void compute( InputArray src, OutputArray w,
02610                          OutputArray u, OutputArray vt, int flags = 0 );
02611 
02612     /** @overload
02613     computes singular values of a matrix
02614     @param src decomposed matrix
02615     @param w calculated singular values
02616     @param flags operation flags - see SVD::Flags.
02617       */
02618     static void compute( InputArray src, OutputArray w, int flags = 0 );
02619 
02620     /** @brief performs back substitution
02621       */
02622     static void backSubst( InputArray w, InputArray u,
02623                            InputArray vt, InputArray rhs,
02624                            OutputArray dst );
02625 
02626     /** @brief solves an under-determined singular linear system
02627 
02628     The method finds a unit-length solution x of a singular linear system
02629     A\*x = 0. Depending on the rank of A, there can be no solutions, a
02630     single solution or an infinite number of solutions. In general, the
02631     algorithm solves the following problem:
02632     \f[dst =  \arg \min _{x:  \| x \| =1}  \| src  \cdot x  \|\f]
02633     @param src left-hand-side matrix.
02634     @param dst found solution.
02635       */
02636     static void solveZ( InputArray src, OutputArray dst );
02637 
02638     /** @brief performs a singular value back substitution.
02639 
02640     The method calculates a back substitution for the specified right-hand
02641     side:
02642 
02643     \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]
02644 
02645     Using this technique you can either get a very accurate solution of the
02646     convenient linear system, or the best (in the least-squares terms)
02647     pseudo-solution of an overdetermined linear system.
02648 
02649     @param rhs right-hand side of a linear system (u\*w\*v')\*dst = rhs to
02650     be solved, where A has been previously decomposed.
02651 
02652     @param dst found solution of the system.
02653 
02654     @note Explicit SVD with the further back substitution only makes sense
02655     if you need to solve many linear systems with the same left-hand side
02656     (for example, src ). If all you need is to solve a single system
02657     (possibly with multiple rhs immediately available), simply call solve
02658     add pass DECOMP_SVD there. It does absolutely the same thing.
02659       */
02660     void backSubst( InputArray rhs, OutputArray dst ) const;
02661 
02662     /** @todo document */
02663     template<typename _Tp, int m, int n, int nm> static
02664     void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt );
02665 
02666     /** @todo document */
02667     template<typename _Tp, int m, int n, int nm> static
02668     void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w );
02669 
02670     /** @todo document */
02671     template<typename _Tp, int m, int n, int nm, int nb> static
02672     void backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst );
02673 
02674     Mat u, w, vt;
02675 };
02676 
02677 /** @brief Random Number Generator
02678 
02679 Random number generator. It encapsulates the state (currently, a 64-bit
02680 integer) and has methods to return scalar random values and to fill
02681 arrays with random values. Currently it supports uniform and Gaussian
02682 (normal) distributions. The generator uses Multiply-With-Carry
02683 algorithm, introduced by G. Marsaglia (
02684 <http://en.wikipedia.org/wiki/Multiply-with-carry> ).
02685 Gaussian-distribution random numbers are generated using the Ziggurat
02686 algorithm ( <http://en.wikipedia.org/wiki/Ziggurat_algorithm> ),
02687 introduced by G. Marsaglia and W. W. Tsang.
02688 */
02689 class CV_EXPORTS RNG
02690 {
02691 public:
02692     enum { UNIFORM = 0,
02693            NORMAL  = 1
02694          };
02695 
02696     /** @brief constructor
02697 
02698     These are the RNG constructors. The first form sets the state to some
02699     pre-defined value, equal to 2\*\*32-1 in the current implementation. The
02700     second form sets the state to the specified value. If you passed state=0
02701     , the constructor uses the above default value instead to avoid the
02702     singular random number sequence, consisting of all zeros.
02703     */
02704     RNG();
02705     /** @overload
02706     @param state 64-bit value used to initialize the RNG.
02707     */
02708     RNG(uint64 state);
02709     /**The method updates the state using the MWC algorithm and returns the
02710     next 32-bit random number.*/
02711     unsigned next();
02712 
02713     /**Each of the methods updates the state using the MWC algorithm and
02714     returns the next random number of the specified type. In case of integer
02715     types, the returned number is from the available value range for the
02716     specified type. In case of floating-point types, the returned value is
02717     from [0,1) range.
02718     */
02719     operator uchar();
02720     /** @overload */
02721     operator schar();
02722     /** @overload */
02723     operator ushort();
02724     /** @overload */
02725     operator short();
02726     /** @overload */
02727     operator unsigned();
02728     /** @overload */
02729     operator int();
02730     /** @overload */
02731     operator float();
02732     /** @overload */
02733     operator double();
02734 
02735     /** @brief returns a random integer sampled uniformly from [0, N).
02736 
02737     The methods transform the state using the MWC algorithm and return the
02738     next random number. The first form is equivalent to RNG::next . The
02739     second form returns the random number modulo N , which means that the
02740     result is in the range [0, N) .
02741     */
02742     unsigned operator ()();
02743     /** @overload
02744     @param N upper non-inclusive boundary of the returned random number.
02745     */
02746     unsigned operator ()(unsigned N);
02747 
02748     /** @brief returns uniformly distributed integer random number from [a,b) range
02749 
02750     The methods transform the state using the MWC algorithm and return the
02751     next uniformly-distributed random number of the specified type, deduced
02752     from the input parameter type, from the range [a, b) . There is a nuance
02753     illustrated by the following sample:
02754 
02755     @code{.cpp}
02756     RNG rng;
02757 
02758     // always produces 0
02759     double a = rng.uniform(0, 1);
02760 
02761     // produces double from [0, 1)
02762     double a1 = rng.uniform((double)0, (double)1);
02763 
02764     // produces float from [0, 1)
02765     double b = rng.uniform(0.f, 1.f);
02766 
02767     // produces double from [0, 1)
02768     double c = rng.uniform(0., 1.);
02769 
02770     // may cause compiler error because of ambiguity:
02771     //  RNG::uniform(0, (int)0.999999)? or RNG::uniform((double)0, 0.99999)?
02772     double d = rng.uniform(0, 0.999999);
02773     @endcode
02774 
02775     The compiler does not take into account the type of the variable to
02776     which you assign the result of RNG::uniform . The only thing that
02777     matters to the compiler is the type of a and b parameters. So, if you
02778     want a floating-point random number, but the range boundaries are
02779     integer numbers, either put dots in the end, if they are constants, or
02780     use explicit type cast operators, as in the a1 initialization above.
02781     @param a lower inclusive boundary of the returned random numbers.
02782     @param b upper non-inclusive boundary of the returned random numbers.
02783       */
02784     int uniform(int a, int b);
02785     /** @overload */
02786     float uniform(float a, float b);
02787     /** @overload */
02788     double uniform(double a, double b);
02789 
02790     /** @brief Fills arrays with random numbers.
02791 
02792     @param mat 2D or N-dimensional matrix; currently matrices with more than
02793     4 channels are not supported by the methods, use Mat::reshape as a
02794     possible workaround.
02795     @param distType distribution type, RNG::UNIFORM or RNG::NORMAL.
02796     @param a first distribution parameter; in case of the uniform
02797     distribution, this is an inclusive lower boundary, in case of the normal
02798     distribution, this is a mean value.
02799     @param b second distribution parameter; in case of the uniform
02800     distribution, this is a non-inclusive upper boundary, in case of the
02801     normal distribution, this is a standard deviation (diagonal of the
02802     standard deviation matrix or the full standard deviation matrix).
02803     @param saturateRange pre-saturation flag; for uniform distribution only;
02804     if true, the method will first convert a and b to the acceptable value
02805     range (according to the mat datatype) and then will generate uniformly
02806     distributed random numbers within the range [saturate(a), saturate(b)),
02807     if saturateRange=false, the method will generate uniformly distributed
02808     random numbers in the original range [a, b) and then will saturate them,
02809     it means, for example, that
02810     <tt>theRNG().fill(mat_8u, RNG::UNIFORM, -DBL_MAX, DBL_MAX)</tt> will likely
02811     produce array mostly filled with 0's and 255's, since the range (0, 255)
02812     is significantly smaller than [-DBL_MAX, DBL_MAX).
02813 
02814     Each of the methods fills the matrix with the random values from the
02815     specified distribution. As the new numbers are generated, the RNG state
02816     is updated accordingly. In case of multiple-channel images, every
02817     channel is filled independently, which means that RNG cannot generate
02818     samples from the multi-dimensional Gaussian distribution with
02819     non-diagonal covariance matrix directly. To do that, the method
02820     generates samples from multi-dimensional standard Gaussian distribution
02821     with zero mean and identity covariation matrix, and then transforms them
02822     using transform to get samples from the specified Gaussian distribution.
02823     */
02824     void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange = false );
02825 
02826     /** @brief Returns the next random number sampled from the Gaussian distribution
02827     @param sigma standard deviation of the distribution.
02828 
02829     The method transforms the state using the MWC algorithm and returns the
02830     next random number from the Gaussian distribution N(0,sigma) . That is,
02831     the mean value of the returned random numbers is zero and the standard
02832     deviation is the specified sigma .
02833     */
02834     double gaussian(double sigma);
02835 
02836     uint64 state;
02837 };
02838 
02839 /** @brief Mersenne Twister random number generator
02840 
02841 Inspired by http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c
02842 @todo document
02843  */
02844 class CV_EXPORTS RNG_MT19937
02845 {
02846 public:
02847     RNG_MT19937();
02848     RNG_MT19937(unsigned s);
02849     void seed(unsigned s);
02850 
02851     unsigned next();
02852 
02853     operator int();
02854     operator unsigned();
02855     operator float();
02856     operator double();
02857 
02858     unsigned operator ()(unsigned N);
02859     unsigned operator ()();
02860 
02861     /** @brief returns uniformly distributed integer random number from [a,b) range
02862 
02863 */
02864     int uniform(int a, int b);
02865     /** @brief returns uniformly distributed floating-point random number from [a,b) range
02866 
02867 */
02868     float uniform(float a, float b);
02869     /** @brief returns uniformly distributed double-precision floating-point random number from [a,b) range
02870 
02871 */
02872     double uniform(double a, double b);
02873 
02874 private:
02875     enum PeriodParameters {N = 624, M = 397};
02876     unsigned state[N];
02877     int mti;
02878 };
02879 
02880 //! @} core_array
02881 
02882 //! @addtogroup core_cluster
02883 //!  @{
02884 
02885 /** @example kmeans.cpp
02886   An example on K-means clustering
02887 */
02888 
02889 /** @brief Finds centers of clusters and groups input samples around the clusters.
02890 
02891 The function kmeans implements a k-means algorithm that finds the centers of cluster_count clusters
02892 and groups the input samples around the clusters. As an output, \f$\texttt{labels}_i\f$ contains a
02893 0-based cluster index for the sample stored in the \f$i^{th}\f$ row of the samples matrix.
02894 
02895 @note
02896 -   (Python) An example on K-means clustering can be found at
02897     opencv_source_code/samples/python/kmeans.py
02898 @param data Data for clustering. An array of N-Dimensional points with float coordinates is needed.
02899 Examples of this array can be:
02900 -   Mat points(count, 2, CV_32F);
02901 -   Mat points(count, 1, CV_32FC2);
02902 -   Mat points(1, count, CV_32FC2);
02903 -   std::vector<cv::Point2f> points(sampleCount);
02904 @param K Number of clusters to split the set by.
02905 @param bestLabels Input/output integer array that stores the cluster indices for every sample.
02906 @param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or
02907 the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster
02908 centers moves by less than criteria.epsilon on some iteration, the algorithm stops.
02909 @param attempts Flag to specify the number of times the algorithm is executed using different
02910 initial labellings. The algorithm returns the labels that yield the best compactness (see the last
02911 function parameter).
02912 @param flags Flag that can take values of cv::KmeansFlags
02913 @param centers Output matrix of the cluster centers, one row per each cluster center.
02914 @return The function returns the compactness measure that is computed as
02915 \f[\sum _i  \| \texttt{samples} _i -  \texttt{centers} _{ \texttt{labels} _i} \| ^2\f]
02916 after every attempt. The best (minimum) value is chosen and the corresponding labels and the
02917 compactness value are returned by the function. Basically, you can use only the core of the
02918 function, set the number of attempts to 1, initialize labels each time using a custom algorithm,
02919 pass them with the ( flags = KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best
02920 (most-compact) clustering.
02921 */
02922 CV_EXPORTS_W double kmeans( InputArray data, int K, InputOutputArray bestLabels,
02923                             TermCriteria criteria, int attempts,
02924                             int flags, OutputArray centers = noArray() );
02925 
02926 //! @} core_cluster
02927 
02928 //! @addtogroup core_basic
02929 //! @{
02930 
02931 /////////////////////////////// Formatted output of cv::Mat ///////////////////////////
02932 
02933 /** @todo document */
02934 class CV_EXPORTS Formatted 
02935 {
02936 public:
02937     virtual const char* next() = 0;
02938     virtual void reset() = 0;
02939     virtual ~Formatted ();
02940 };
02941 
02942 /** @todo document */
02943 class CV_EXPORTS Formatter 
02944 {
02945 public:
02946     enum { FMT_DEFAULT = 0,
02947            FMT_MATLAB  = 1,
02948            FMT_CSV     = 2,
02949            FMT_PYTHON  = 3,
02950            FMT_NUMPY   = 4,
02951            FMT_C       = 5
02952          };
02953 
02954     virtual ~Formatter ();
02955 
02956     virtual Ptr<Formatted> format(const Mat& mtx) const = 0;
02957 
02958     virtual void set32fPrecision(int p = 8) = 0;
02959     virtual void set64fPrecision(int p = 16) = 0;
02960     virtual void setMultiline(bool ml = true) = 0;
02961 
02962     static Ptr<Formatter> get(int fmt = FMT_DEFAULT);
02963 
02964 };
02965 
02966 static inline
02967 String& operator << (String& out, Ptr<Formatted> fmtd)
02968 {
02969     fmtd->reset();
02970     for(const char* str = fmtd->next(); str; str = fmtd->next())
02971         out += cv::String(str);
02972     return out;
02973 }
02974 
02975 static inline
02976 String& operator << (String& out, const Mat& mtx)
02977 {
02978     return out << Formatter::get()->format(mtx);
02979 }
02980 
02981 //////////////////////////////////////// Algorithm ////////////////////////////////////
02982 
02983 class CV_EXPORTS Algorithm;
02984 
02985 template<typename _Tp> struct ParamType {};
02986 
02987 
02988 /** @brief This is a base class for all more or less complex algorithms in OpenCV
02989 
02990 especially for classes of algorithms, for which there can be multiple implementations. The examples
02991 are stereo correspondence (for which there are algorithms like block matching, semi-global block
02992 matching, graph-cut etc.), background subtraction (which can be done using mixture-of-gaussians
02993 models, codebook-based algorithm etc.), optical flow (block matching, Lucas-Kanade, Horn-Schunck
02994 etc.).
02995 
02996 Here is example of SIFT use in your application via Algorithm interface:
02997 @code
02998     #include "opencv2/opencv.hpp"
02999     #include "opencv2/xfeatures2d.hpp"
03000     using namespace cv::xfeatures2d;
03001 
03002     Ptr<Feature2D> sift = SIFT::create();
03003     FileStorage fs("sift_params.xml", FileStorage::READ);
03004     if( fs.isOpened() ) // if we have file with parameters, read them
03005     {
03006         sift->read(fs["sift_params"]);
03007         fs.release();
03008     }
03009     else // else modify the parameters and store them; user can later edit the file to use different parameters
03010     {
03011         sift->setContrastThreshold(0.01f); // lower the contrast threshold, compared to the default value
03012         {
03013             WriteStructContext ws(fs, "sift_params", CV_NODE_MAP);
03014             sift->write(fs);
03015         }
03016     }
03017     Mat image = imread("myimage.png", 0), descriptors;
03018     vector<KeyPoint> keypoints;
03019     sift->detectAndCompute(image, noArray(), keypoints, descriptors);
03020 @endcode
03021  */
03022 class CV_EXPORTS_W Algorithm
03023 {
03024 public:
03025     Algorithm();
03026     virtual ~Algorithm();
03027 
03028     /** @brief Clears the algorithm state
03029     */
03030     CV_WRAP virtual void clear() {}
03031 
03032     /** @brief Stores algorithm parameters in a file storage
03033     */
03034     virtual void write(FileStorage& fs) const { (void)fs; }
03035 
03036     /** @brief Reads algorithm parameters from a file storage
03037     */
03038     virtual void read(const FileNode& fn) { (void)fn; }
03039 
03040     /** @brief Returns true if the Algorithm is empty (e.g. in the very beginning or after unsuccessful read
03041      */
03042     virtual bool empty() const { return false; }
03043 
03044     /** @brief Reads algorithm from the file node
03045 
03046      This is static template method of Algorithm. It's usage is following (in the case of SVM):
03047      @code
03048      cv::FileStorage fsRead("example.xml", FileStorage::READ);
03049      Ptr<SVM> svm = Algorithm::read<SVM>(fsRead.root());
03050      @endcode
03051      In order to make this method work, the derived class must overwrite Algorithm::read(const
03052      FileNode& fn) and also have static create() method without parameters
03053      (or with all the optional parameters)
03054      */
03055     template<typename _Tp> static Ptr<_Tp> read(const FileNode& fn)
03056     {
03057         Ptr<_Tp> obj = _Tp::create();
03058         obj->read(fn);
03059         return !obj->empty() ? obj : Ptr<_Tp>();
03060     }
03061 
03062     /** @brief Loads algorithm from the file
03063 
03064      @param filename Name of the file to read.
03065      @param objname The optional name of the node to read (if empty, the first top-level node will be used)
03066 
03067      This is static template method of Algorithm. It's usage is following (in the case of SVM):
03068      @code
03069      Ptr<SVM> svm = Algorithm::load<SVM>("my_svm_model.xml");
03070      @endcode
03071      In order to make this method work, the derived class must overwrite Algorithm::read(const
03072      FileNode& fn).
03073      */
03074     template<typename _Tp> static Ptr<_Tp> load(const String& filename, const String& objname=String())
03075     {
03076         FileStorage fs(filename, FileStorage::READ);
03077         FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname];
03078         if (fn.empty()) return Ptr<_Tp>();
03079         Ptr<_Tp> obj = _Tp::create();
03080         obj->read(fn);
03081         return !obj->empty() ? obj : Ptr<_Tp>();
03082     }
03083 
03084     /** @brief Loads algorithm from a String
03085 
03086      @param strModel The string variable containing the model you want to load.
03087      @param objname The optional name of the node to read (if empty, the first top-level node will be used)
03088 
03089      This is static template method of Algorithm. It's usage is following (in the case of SVM):
03090      @code
03091      Ptr<SVM> svm = Algorithm::loadFromString<SVM>(myStringModel);
03092      @endcode
03093      */
03094     template<typename _Tp> static Ptr<_Tp> loadFromString(const String& strModel, const String& objname=String())
03095     {
03096         FileStorage fs(strModel, FileStorage::READ + FileStorage::MEMORY);
03097         FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname];
03098         Ptr<_Tp> obj = _Tp::create();
03099         obj->read(fn);
03100         return !obj->empty() ? obj : Ptr<_Tp>();
03101     }
03102 
03103     /** Saves the algorithm to a file.
03104      In order to make this method work, the derived class must implement Algorithm::write(FileStorage& fs). */
03105     CV_WRAP virtual void save(const String& filename) const;
03106 
03107     /** Returns the algorithm string identifier.
03108      This string is used as top level xml/yml node tag when the object is saved to a file or string. */
03109     CV_WRAP virtual String getDefaultName() const;
03110 
03111 protected:
03112     void writeFormat(FileStorage& fs) const;
03113 };
03114 
03115 struct Param {
03116     enum { INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7,
03117            UNSIGNED_INT=8, UINT64=9, UCHAR=11 };
03118 };
03119 
03120 
03121 
03122 template<> struct ParamType<bool>
03123 {
03124     typedef bool const_param_type;
03125     typedef bool member_type;
03126 
03127     enum { type = Param::BOOLEAN };
03128 };
03129 
03130 template<> struct ParamType<int>
03131 {
03132     typedef int const_param_type;
03133     typedef int member_type;
03134 
03135     enum { type = Param::INT };
03136 };
03137 
03138 template<> struct ParamType<double>
03139 {
03140     typedef double const_param_type;
03141     typedef double member_type;
03142 
03143     enum { type = Param::REAL };
03144 };
03145 
03146 template<> struct ParamType<String>
03147 {
03148     typedef const String& const_param_type;
03149     typedef String member_type;
03150 
03151     enum { type = Param::STRING };
03152 };
03153 
03154 template<> struct ParamType<Mat>
03155 {
03156     typedef const Mat& const_param_type;
03157     typedef Mat member_type;
03158 
03159     enum { type = Param::MAT };
03160 };
03161 
03162 template<> struct ParamType<std::vector<Mat> >
03163 {
03164     typedef const std::vector<Mat>& const_param_type;
03165     typedef std::vector<Mat> member_type;
03166 
03167     enum { type = Param::MAT_VECTOR };
03168 };
03169 
03170 template<> struct ParamType<Algorithm>
03171 {
03172     typedef const Ptr<Algorithm>& const_param_type;
03173     typedef Ptr<Algorithm> member_type;
03174 
03175     enum { type = Param::ALGORITHM };
03176 };
03177 
03178 template<> struct ParamType<float>
03179 {
03180     typedef float const_param_type;
03181     typedef float member_type;
03182 
03183     enum { type = Param::FLOAT };
03184 };
03185 
03186 template<> struct ParamType<unsigned>
03187 {
03188     typedef unsigned const_param_type;
03189     typedef unsigned member_type;
03190 
03191     enum { type = Param::UNSIGNED_INT };
03192 };
03193 
03194 template<> struct ParamType<uint64>
03195 {
03196     typedef uint64 const_param_type;
03197     typedef uint64 member_type;
03198 
03199     enum { type = Param::UINT64 };
03200 };
03201 
03202 template<> struct ParamType<uchar>
03203 {
03204     typedef uchar const_param_type;
03205     typedef uchar member_type;
03206 
03207     enum { type = Param::UCHAR };
03208 };
03209 
03210 //! @} core_basic
03211 
03212 } //namespace cv
03213 
03214 #include "opencv2/core/operations.hpp"
03215 #include "opencv2/core/cvstd.inl.hpp"
03216 #include "opencv2/core/utility.hpp"
03217 #include "opencv2/core/optim.hpp"
03218 #include "opencv2/core/ovx.hpp"
03219 
03220 #endif /*OPENCV_CORE_HPP*/