first version of moving KDTree from core to ml
[profile/ivi/opencv.git] / modules / core / include / opencv2 / core.hpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                           License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14 // Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
15 // Third party copyrights are property of their respective owners.
16 //
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
19 //
20 //   * Redistribution's of source code must retain the above copyright notice,
21 //     this list of conditions and the following disclaimer.
22 //
23 //   * Redistribution's in binary form must reproduce the above copyright notice,
24 //     this list of conditions and the following disclaimer in the documentation
25 //     and/or other materials provided with the distribution.
26 //
27 //   * The name of the copyright holders may not be used to endorse or promote products
28 //     derived from this software without specific prior written permission.
29 //
30 // This software is provided by the copyright holders and contributors "as is" and
31 // any express or implied warranties, including, but not limited to, the implied
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.
33 // In no event shall the Intel Corporation or contributors be liable for any direct,
34 // indirect, incidental, special, exemplary, or consequential damages
35 // (including, but not limited to, procurement of substitute goods or services;
36 // loss of use, data, or profits; or business interruption) however caused
37 // and on any theory of liability, whether in contract, strict liability,
38 // or tort (including negligence or otherwise) arising in any way out of
39 // the use of this software, even if advised of the possibility of such damage.
40 //
41 //M*/
42
43 #ifndef __OPENCV_CORE_HPP__
44 #define __OPENCV_CORE_HPP__
45
46 #ifndef __cplusplus
47 #  error core.hpp header must be compiled as C++
48 #endif
49
50 #include "opencv2/core/cvdef.h"
51 #include "opencv2/core/version.hpp"
52 #include "opencv2/core/base.hpp"
53 #include "opencv2/core/cvstd.hpp"
54 #include "opencv2/core/traits.hpp"
55 #include "opencv2/core/matx.hpp"
56 #include "opencv2/core/types.hpp"
57 #include "opencv2/core/mat.hpp"
58 #include "opencv2/core/persistence.hpp"
59
60 /*! \namespace cv
61     Namespace where all the C++ OpenCV functionality resides
62 */
63 namespace cv {
64
65 /*!
66  The standard OpenCV exception class.
67  Instances of the class are thrown by various functions and methods in the case of critical errors.
68  */
69 class CV_EXPORTS Exception : public std::exception
70 {
71 public:
72     /*!
73      Default constructor
74      */
75     Exception();
76     /*!
77      Full constructor. Normally the constuctor is not called explicitly.
78      Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used.
79     */
80     Exception(int _code, const String& _err, const String& _func, const String& _file, int _line);
81     virtual ~Exception() throw();
82
83     /*!
84      \return the error description and the context as a text string.
85     */
86     virtual const char *what() const throw();
87     void formatMessage();
88
89     String msg; ///< the formatted error message
90
91     int code; ///< error code @see CVStatus
92     String err; ///< error description
93     String func; ///< function name. Available only when the compiler supports getting it
94     String file; ///< source file name where the error has occured
95     int line; ///< line number in the source file where the error has occured
96 };
97
98
99 //! Signals an error and raises the exception.
100
101 /*!
102   By default the function prints information about the error to stderr,
103   then it either stops if setBreakOnError() had been called before or raises the exception.
104   It is possible to alternate error processing by using redirectError().
105
106   \param exc the exception raisen.
107  */
108 //TODO: drop this version
109 CV_EXPORTS void error( const Exception& exc );
110
111
112 enum { SORT_EVERY_ROW    = 0,
113        SORT_EVERY_COLUMN = 1,
114        SORT_ASCENDING    = 0,
115        SORT_DESCENDING   = 16
116      };
117
118 enum { COVAR_SCRAMBLED = 0,
119        COVAR_NORMAL    = 1,
120        COVAR_USE_AVG   = 2,
121        COVAR_SCALE     = 4,
122        COVAR_ROWS      = 8,
123        COVAR_COLS      = 16
124      };
125
126 /*!
127  k-Means flags
128 */
129 enum { KMEANS_RANDOM_CENTERS     = 0, // Chooses random centers for k-Means initialization
130        KMEANS_PP_CENTERS         = 2, // Uses k-Means++ algorithm for initialization
131        KMEANS_USE_INITIAL_LABELS = 1  // Uses the user-provided labels for K-Means initialization
132      };
133
134 enum { FILLED  = -1,
135        LINE_4  = 4,
136        LINE_8  = 8,
137        LINE_AA = 16
138      };
139
140 enum { FONT_HERSHEY_SIMPLEX        = 0,
141        FONT_HERSHEY_PLAIN          = 1,
142        FONT_HERSHEY_DUPLEX         = 2,
143        FONT_HERSHEY_COMPLEX        = 3,
144        FONT_HERSHEY_TRIPLEX        = 4,
145        FONT_HERSHEY_COMPLEX_SMALL  = 5,
146        FONT_HERSHEY_SCRIPT_SIMPLEX = 6,
147        FONT_HERSHEY_SCRIPT_COMPLEX = 7,
148        FONT_ITALIC                 = 16
149      };
150
151 enum { REDUCE_SUM = 0,
152        REDUCE_AVG = 1,
153        REDUCE_MAX = 2,
154        REDUCE_MIN = 3
155      };
156
157
158 //! swaps two matrices
159 CV_EXPORTS void swap(Mat& a, Mat& b);
160
161 //! swaps two umatrices
162 CV_EXPORTS void swap( UMat& a, UMat& b );
163
164 //! 1D interpolation function: returns coordinate of the "donor" pixel for the specified location p.
165 CV_EXPORTS_W int borderInterpolate(int p, int len, int borderType);
166
167 //! copies 2D array to a larger destination array with extrapolation of the outer part of src using the specified border mode
168 CV_EXPORTS_W void copyMakeBorder(InputArray src, OutputArray dst,
169                                  int top, int bottom, int left, int right,
170                                  int borderType, const Scalar& value = Scalar() );
171
172 //! adds one matrix to another (dst = src1 + src2)
173 CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst,
174                       InputArray mask = noArray(), int dtype = -1);
175
176 //! subtracts one matrix from another (dst = src1 - src2)
177 CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst,
178                            InputArray mask = noArray(), int dtype = -1);
179
180 //! computes element-wise weighted product of the two arrays (dst = scale*src1*src2)
181 CV_EXPORTS_W void multiply(InputArray src1, InputArray src2,
182                            OutputArray dst, double scale = 1, int dtype = -1);
183
184 //! computes element-wise weighted quotient of the two arrays (dst = scale * src1 / src2)
185 CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst,
186                          double scale = 1, int dtype = -1);
187
188 //! computes element-wise weighted reciprocal of an array (dst = scale/src2)
189 CV_EXPORTS_W void divide(double scale, InputArray src2,
190                          OutputArray dst, int dtype = -1);
191
192 //! adds scaled array to another one (dst = alpha*src1 + src2)
193 CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst);
194
195 //! computes weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma)
196 CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2,
197                               double beta, double gamma, OutputArray dst, int dtype = -1);
198
199 //! scales array elements, computes absolute values and converts the results to 8-bit unsigned integers: dst(i)=saturate_cast<uchar>abs(src(i)*alpha+beta)
200 CV_EXPORTS_W void convertScaleAbs(InputArray src, OutputArray dst,
201                                   double alpha = 1, double beta = 0);
202
203 //! transforms array of numbers using a lookup table: dst(i)=lut(src(i))
204 CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst);
205
206 //! computes sum of array elements
207 CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src);
208
209 //! computes the number of nonzero array elements
210 CV_EXPORTS_W int countNonZero( InputArray src );
211
212 //! returns the list of locations of non-zero pixels
213 CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx );
214
215 //! computes mean value of selected array elements
216 CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask = noArray());
217
218 //! computes mean value and standard deviation of all or selected array elements
219 CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev,
220                              InputArray mask=noArray());
221
222 //! computes norm of the selected array part
223 CV_EXPORTS_W double norm(InputArray src1, int normType = NORM_L2, InputArray mask = noArray());
224
225 //! computes norm of selected part of the difference between two arrays
226 CV_EXPORTS_W double norm(InputArray src1, InputArray src2,
227                          int normType = NORM_L2, InputArray mask = noArray());
228
229 //! computes PSNR image/video quality metric
230 CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2);
231
232 //! computes norm of a sparse matrix
233 CV_EXPORTS double norm( const SparseMat& src, int normType );
234
235 //! naive nearest neighbor finder
236 CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2,
237                                 OutputArray dist, int dtype, OutputArray nidx,
238                                 int normType = NORM_L2, int K = 0,
239                                 InputArray mask = noArray(), int update = 0,
240                                 bool crosscheck = false);
241
242 //! scales and shifts array elements so that either the specified norm (alpha) or the minimum (alpha) and maximum (beta) array values get the specified values
243 CV_EXPORTS_W void normalize( InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0,
244                              int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray());
245
246 //! scales and shifts array elements so that either the specified norm (alpha) or the minimum (alpha) and maximum (beta) array values get the specified values
247 CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType );
248
249 //! finds global minimum and maximum array elements and returns their values and their locations
250 CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal,
251                             CV_OUT double* maxVal = 0, CV_OUT Point* minLoc = 0,
252                             CV_OUT Point* maxLoc = 0, InputArray mask = noArray());
253
254 CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal = 0,
255                           int* minIdx = 0, int* maxIdx = 0, InputArray mask = noArray());
256
257 //! finds global minimum and maximum sparse array elements and returns their values and their locations
258 CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal,
259                           double* maxVal, int* minIdx = 0, int* maxIdx = 0);
260
261 //! transforms 2D matrix to 1D row or column vector by taking sum, minimum, maximum or mean value over all the rows
262 CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype = -1);
263
264 //! makes multi-channel array out of several single-channel arrays
265 CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst);
266
267 //! makes multi-channel array out of several single-channel arrays
268 CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst);
269
270 //! copies each plane of a multi-channel array to a dedicated array
271 CV_EXPORTS void split(const Mat& src, Mat* mvbegin);
272
273 //! copies each plane of a multi-channel array to a dedicated array
274 CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv);
275
276 //! copies selected channels from the input arrays to the selected channels of the output arrays
277 CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts,
278                             const int* fromTo, size_t npairs);
279
280 CV_EXPORTS void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst,
281                             const int* fromTo, size_t npairs);
282
283 CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst,
284                               const std::vector<int>& fromTo);
285
286 //! extracts a single channel from src (coi is 0-based index)
287 CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi);
288
289 //! inserts a single channel to dst (coi is 0-based index)
290 CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi);
291
292 //! reverses the order of the rows, columns or both in a matrix
293 CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode);
294
295 //! replicates the input matrix the specified number of times in the horizontal and/or vertical direction
296 CV_EXPORTS_W void repeat(InputArray src, int ny, int nx, OutputArray dst);
297
298 CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx);
299
300 CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, OutputArray dst);
301
302 CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst);
303
304 CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst);
305
306 CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst);
307
308 CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst);
309
310 CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst);
311
312 //! computes bitwise conjunction of the two arrays (dst = src1 & src2)
313 CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2,
314                               OutputArray dst, InputArray mask = noArray());
315
316 //! computes bitwise disjunction of the two arrays (dst = src1 | src2)
317 CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2,
318                              OutputArray dst, InputArray mask = noArray());
319
320 //! computes bitwise exclusive-or of the two arrays (dst = src1 ^ src2)
321 CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2,
322                               OutputArray dst, InputArray mask = noArray());
323
324 //! inverts each bit of array (dst = ~src)
325 CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst,
326                               InputArray mask = noArray());
327
328 //! computes element-wise absolute difference of two arrays (dst = abs(src1 - src2))
329 CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst);
330
331 //! set mask elements for those array elements which are within the element-specific bounding box (dst = lowerb <= src && src < upperb)
332 CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb,
333                           InputArray upperb, OutputArray dst);
334
335 //! compares elements of two arrays (dst = src1 <cmpop> src2)
336 CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop);
337
338 //! computes per-element minimum of two arrays (dst = min(src1, src2))
339 CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst);
340
341 //! computes per-element maximum of two arrays (dst = max(src1, src2))
342 CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst);
343
344 // the following overloads are needed to avoid conflicts with
345 //     const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
346 //! computes per-element minimum of two arrays (dst = min(src1, src2))
347 CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst);
348 //! computes per-element maximum of two arrays (dst = max(src1, src2))
349 CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst);
350 //! computes per-element minimum of two arrays (dst = min(src1, src2))
351 CV_EXPORTS void min(const UMat& src1, const UMat& src2, UMat& dst);
352 //! computes per-element maximum of two arrays (dst = max(src1, src2))
353 CV_EXPORTS void max(const UMat& src1, const UMat& src2, UMat& dst);
354
355 //! computes square root of each matrix element (dst = src**0.5)
356 CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst);
357
358 //! raises the input matrix elements to the specified power (b = a**power)
359 CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst);
360
361 //! computes exponent of each matrix element (dst = e**src)
362 CV_EXPORTS_W void exp(InputArray src, OutputArray dst);
363
364 //! computes natural logarithm of absolute value of each matrix element: dst = log(abs(src))
365 CV_EXPORTS_W void log(InputArray src, OutputArray dst);
366
367 //! converts polar coordinates to Cartesian
368 CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle,
369                               OutputArray x, OutputArray y, bool angleInDegrees = false);
370
371 //! converts Cartesian coordinates to polar
372 CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y,
373                               OutputArray magnitude, OutputArray angle,
374                               bool angleInDegrees = false);
375
376 //! computes angle (angle(i)) of each (x(i), y(i)) vector
377 CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle,
378                         bool angleInDegrees = false);
379
380 //! computes magnitude (magnitude(i)) of each (x(i), y(i)) vector
381 CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude);
382
383 //! checks that each matrix element is within the specified range.
384 CV_EXPORTS_W bool checkRange(InputArray a, bool quiet = true, CV_OUT Point* pos = 0,
385                             double minVal = -DBL_MAX, double maxVal = DBL_MAX);
386
387 //! converts NaN's to the given number
388 CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0);
389
390 //! implements generalized matrix product algorithm GEMM from BLAS
391 CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha,
392                        InputArray src3, double beta, OutputArray dst, int flags = 0);
393
394 //! multiplies matrix by its transposition from the left or from the right
395 CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa,
396                                  InputArray delta = noArray(),
397                                  double scale = 1, int dtype = -1 );
398
399 //! transposes the matrix
400 CV_EXPORTS_W void transpose(InputArray src, OutputArray dst);
401
402 //! performs affine transformation of each element of multi-channel input matrix
403 CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m );
404
405 //! performs perspective transformation of each element of multi-channel input matrix
406 CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m );
407
408 //! extends the symmetrical matrix from the lower half or from the upper half
409 CV_EXPORTS_W void completeSymm(InputOutputArray mtx, bool lowerToUpper = false);
410
411 //! initializes scaled identity matrix
412 CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s = Scalar(1));
413
414 //! computes determinant of a square matrix
415 CV_EXPORTS_W double determinant(InputArray mtx);
416
417 //! computes trace of a matrix
418 CV_EXPORTS_W Scalar trace(InputArray mtx);
419
420 //! computes inverse or pseudo-inverse matrix
421 CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags = DECOMP_LU);
422
423 //! solves linear system or a least-square problem
424 CV_EXPORTS_W bool solve(InputArray src1, InputArray src2,
425                         OutputArray dst, int flags = DECOMP_LU);
426
427 //! sorts independently each matrix row or each matrix column
428 CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags);
429
430 //! sorts independently each matrix row or each matrix column
431 CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags);
432
433 //! finds real roots of a cubic polynomial
434 CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots);
435
436 //! finds real and complex roots of a polynomial
437 CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters = 300);
438
439 //! finds eigenvalues and eigenvectors of a symmetric matrix
440 CV_EXPORTS_W bool eigen(InputArray src, OutputArray eigenvalues,
441                         OutputArray eigenvectors = noArray());
442
443 //! computes covariation matrix of a set of samples
444 CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean,
445                                  int flags, int ctype = CV_64F); //TODO: InputArrayOfArrays
446
447 //! computes covariation matrix of a set of samples
448 CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar,
449                                    InputOutputArray mean, int flags, int ctype = CV_64F);
450
451 CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean,
452                              OutputArray eigenvectors, int maxComponents = 0);
453
454 CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean,
455                              OutputArray eigenvectors, double retainedVariance);
456
457 CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean,
458                              InputArray eigenvectors, OutputArray result);
459
460 CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean,
461                                  InputArray eigenvectors, OutputArray result);
462
463 //! computes SVD of src
464 CV_EXPORTS_W void SVDecomp( InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags = 0 );
465
466 //! performs back substitution for the previously computed SVD
467 CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt,
468                                InputArray rhs, OutputArray dst );
469
470 //! computes Mahalanobis distance between two vectors: sqrt((v1-v2)'*icovar*(v1-v2)), where icovar is the inverse covariation matrix
471 CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar);
472
473 //! performs forward or inverse 1D or 2D Discrete Fourier Transformation
474 CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0);
475
476 //! performs inverse 1D or 2D Discrete Fourier Transformation
477 CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0);
478
479 //! performs forward or inverse 1D or 2D Discrete Cosine Transformation
480 CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags = 0);
481
482 //! performs inverse 1D or 2D Discrete Cosine Transformation
483 CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags = 0);
484
485 //! computes element-wise product of the two Fourier spectrums. The second spectrum can optionally be conjugated before the multiplication
486 CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c,
487                                int flags, bool conjB = false);
488
489 //! computes the minimal vector size vecsize1 >= vecsize so that the dft() of the vector of length vecsize1 can be computed efficiently
490 CV_EXPORTS_W int getOptimalDFTSize(int vecsize);
491
492 //! clusters the input data using k-Means algorithm
493 CV_EXPORTS_W double kmeans( InputArray data, int K, InputOutputArray bestLabels,
494                             TermCriteria criteria, int attempts,
495                             int flags, OutputArray centers = noArray() );
496
497 //! returns the thread-local Random number generator
498 CV_EXPORTS RNG& theRNG();
499
500 //! fills array with uniformly-distributed random numbers from the range [low, high)
501 CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high);
502
503 //! fills array with normally-distributed random numbers with the specified mean and the standard deviation
504 CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev);
505
506 //! shuffles the input array elements
507 CV_EXPORTS_W void randShuffle(InputOutputArray dst, double iterFactor = 1., RNG* rng = 0);
508
509 /*!
510     Principal Component Analysis
511
512     The class PCA is used to compute the special basis for a set of vectors.
513     The basis will consist of eigenvectors of the covariance matrix computed
514     from the input set of vectors. After PCA is performed, vectors can be transformed from
515     the original high-dimensional space to the subspace formed by a few most
516     prominent eigenvectors (called the principal components),
517     corresponding to the largest eigenvalues of the covariation matrix.
518     Thus the dimensionality of the vector and the correlation between the coordinates is reduced.
519
520     The following sample is the function that takes two matrices. The first one stores the set
521     of vectors (a row per vector) that is used to compute PCA, the second one stores another
522     "test" set of vectors (a row per vector) that are first compressed with PCA,
523     then reconstructed back and then the reconstruction error norm is computed and printed for each vector.
524
525     \code
526     using namespace cv;
527
528     PCA compressPCA(const Mat& pcaset, int maxComponents,
529                     const Mat& testset, Mat& compressed)
530     {
531         PCA pca(pcaset, // pass the data
532                 Mat(), // we do not have a pre-computed mean vector,
533                        // so let the PCA engine to compute it
534                 PCA::DATA_AS_ROW, // indicate that the vectors
535                                     // are stored as matrix rows
536                                     // (use PCA::DATA_AS_COL if the vectors are
537                                     // the matrix columns)
538                 maxComponents // specify, how many principal components to retain
539                 );
540         // if there is no test data, just return the computed basis, ready-to-use
541         if( !testset.data )
542             return pca;
543         CV_Assert( testset.cols == pcaset.cols );
544
545         compressed.create(testset.rows, maxComponents, testset.type());
546
547         Mat reconstructed;
548         for( int i = 0; i < testset.rows; i++ )
549         {
550             Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed;
551             // compress the vector, the result will be stored
552             // in the i-th row of the output matrix
553             pca.project(vec, coeffs);
554             // and then reconstruct it
555             pca.backProject(coeffs, reconstructed);
556             // and measure the error
557             printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2));
558         }
559         return pca;
560     }
561     \endcode
562 */
563 class CV_EXPORTS PCA
564 {
565 public:
566     enum { DATA_AS_ROW = 0,
567            DATA_AS_COL = 1,
568            USE_AVG     = 2
569          };
570
571     //! default constructor
572     PCA();
573
574     //! the constructor that performs PCA
575     PCA(InputArray data, InputArray mean, int flags, int maxComponents = 0);
576     PCA(InputArray data, InputArray mean, int flags, double retainedVariance);
577
578     //! operator that performs PCA. The previously stored data, if any, is released
579     PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents = 0);
580     PCA& operator()(InputArray data, InputArray mean, int flags, double retainedVariance);
581
582     //! projects vector from the original space to the principal components subspace
583     Mat project(InputArray vec) const;
584
585     //! projects vector from the original space to the principal components subspace
586     void project(InputArray vec, OutputArray result) const;
587
588     //! reconstructs the original vector from the projection
589     Mat backProject(InputArray vec) const;
590
591     //! reconstructs the original vector from the projection
592     void backProject(InputArray vec, OutputArray result) const;
593
594     //! write and load PCA matrix
595     void write(FileStorage& fs ) const;
596     void read(const FileNode& fs);
597
598     Mat eigenvectors; //!< eigenvectors of the covariation matrix
599     Mat eigenvalues; //!< eigenvalues of the covariation matrix
600     Mat mean; //!< mean value subtracted before the projection and added after the back projection
601 };
602
603 // Linear Discriminant Analysis
604 class CV_EXPORTS LDA
605 {
606 public:
607     // Initializes a LDA with num_components (default 0) and specifies how
608     // samples are aligned (default dataAsRow=true).
609     explicit LDA(int num_components = 0);
610
611     // Initializes and performs a Discriminant Analysis with Fisher's
612     // Optimization Criterion on given data in src and corresponding labels
613     // in labels. If 0 (or less) number of components are given, they are
614     // automatically determined for given data in computation.
615     LDA(InputArrayOfArrays src, InputArray labels, int num_components = 0);
616
617     // Serializes this object to a given filename.
618     void save(const String& filename) const;
619
620     // Deserializes this object from a given filename.
621     void load(const String& filename);
622
623     // Serializes this object to a given cv::FileStorage.
624     void save(FileStorage& fs) const;
625
626         // Deserializes this object from a given cv::FileStorage.
627     void load(const FileStorage& node);
628
629     // Destructor.
630     ~LDA();
631
632     //! Compute the discriminants for data in src and labels.
633     void compute(InputArrayOfArrays src, InputArray labels);
634
635     // Projects samples into the LDA subspace.
636     Mat project(InputArray src);
637
638     // Reconstructs projections from the LDA subspace.
639     Mat reconstruct(InputArray src);
640
641     // Returns the eigenvectors of this LDA.
642     Mat eigenvectors() const { return _eigenvectors; }
643
644     // Returns the eigenvalues of this LDA.
645     Mat eigenvalues() const { return _eigenvalues; }
646
647     static Mat subspaceProject(InputArray W, InputArray mean, InputArray src);
648     static Mat subspaceReconstruct(InputArray W, InputArray mean, InputArray src);
649
650 protected:
651     bool _dataAsRow;
652     int _num_components;
653     Mat _eigenvectors;
654     Mat _eigenvalues;
655
656     void lda(InputArrayOfArrays src, InputArray labels);
657 };
658
659 /*!
660     Singular Value Decomposition class
661
662     The class is used to compute Singular Value Decomposition of a floating-point matrix and then
663     use it to solve least-square problems, under-determined linear systems, invert matrices,
664     compute condition numbers etc.
665
666     For a bit faster operation you can pass flags=SVD::MODIFY_A|... to modify the decomposed matrix
667     when it is not necessarily to preserve it. If you want to compute condition number of a matrix
668     or absolute value of its determinant - you do not need SVD::u or SVD::vt,
669     so you can pass flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that the full-size SVD::u and SVD::vt
670     must be computed, which is not necessary most of the time.
671 */
672 class CV_EXPORTS SVD
673 {
674 public:
675     enum { MODIFY_A = 1,
676            NO_UV    = 2,
677            FULL_UV  = 4
678          };
679
680     //! the default constructor
681     SVD();
682
683     //! the constructor that performs SVD
684     SVD( InputArray src, int flags = 0 );
685
686     //! the operator that performs SVD. The previously allocated SVD::u, SVD::w are SVD::vt are released.
687     SVD& operator ()( InputArray src, int flags = 0 );
688
689     //! decomposes matrix and stores the results to user-provided matrices
690     static void compute( InputArray src, OutputArray w,
691                          OutputArray u, OutputArray vt, int flags = 0 );
692
693     //! computes singular values of a matrix
694     static void compute( InputArray src, OutputArray w, int flags = 0 );
695
696     //! performs back substitution
697     static void backSubst( InputArray w, InputArray u,
698                            InputArray vt, InputArray rhs,
699                            OutputArray dst );
700
701     //! finds dst = arg min_{|dst|=1} |m*dst|
702     static void solveZ( InputArray src, OutputArray dst );
703
704     //! performs back substitution, so that dst is the solution or pseudo-solution of m*dst = rhs, where m is the decomposed matrix
705     void backSubst( InputArray rhs, OutputArray dst ) const;
706
707     template<typename _Tp, int m, int n, int nm> static
708     void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt );
709
710     template<typename _Tp, int m, int n, int nm> static
711     void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w );
712
713     template<typename _Tp, int m, int n, int nm, int nb> static
714     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 );
715
716     Mat u, w, vt;
717 };
718
719
720
721 /*!
722    Line iterator class
723
724    The class is used to iterate over all the pixels on the raster line
725    segment connecting two specified points.
726 */
727 class CV_EXPORTS LineIterator
728 {
729 public:
730     //! intializes the iterator
731     LineIterator( const Mat& img, Point pt1, Point pt2,
732                   int connectivity = 8, bool leftToRight = false );
733     //! returns pointer to the current pixel
734     uchar* operator *();
735     //! prefix increment operator (++it). shifts iterator to the next pixel
736     LineIterator& operator ++();
737     //! postfix increment operator (it++). shifts iterator to the next pixel
738     LineIterator operator ++(int);
739     //! returns coordinates of the current pixel
740     Point pos() const;
741
742     uchar* ptr;
743     const uchar* ptr0;
744     int step, elemSize;
745     int err, count;
746     int minusDelta, plusDelta;
747     int minusStep, plusStep;
748 };
749
750 /*!
751    Random Number Generator
752
753    The class implements RNG using Multiply-with-Carry algorithm
754 */
755 class CV_EXPORTS RNG
756 {
757 public:
758     enum { UNIFORM = 0,
759            NORMAL  = 1
760          };
761
762     RNG();
763     RNG(uint64 state);
764     //! updates the state and returns the next 32-bit unsigned integer random number
765     unsigned next();
766
767     operator uchar();
768     operator schar();
769     operator ushort();
770     operator short();
771     operator unsigned();
772     //! returns a random integer sampled uniformly from [0, N).
773     unsigned operator ()(unsigned N);
774     unsigned operator ()();
775     operator int();
776     operator float();
777     operator double();
778     //! returns uniformly distributed integer random number from [a,b) range
779     int uniform(int a, int b);
780     //! returns uniformly distributed floating-point random number from [a,b) range
781     float uniform(float a, float b);
782     //! returns uniformly distributed double-precision floating-point random number from [a,b) range
783     double uniform(double a, double b);
784     void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange = false );
785     //! returns Gaussian random variate with mean zero.
786     double gaussian(double sigma);
787
788     uint64 state;
789 };
790
791 class CV_EXPORTS RNG_MT19937
792 {
793 public:
794     RNG_MT19937();
795     RNG_MT19937(unsigned s);
796     void seed(unsigned s);
797
798     unsigned next();
799
800     operator int();
801     operator unsigned();
802     operator float();
803     operator double();
804
805     unsigned operator ()(unsigned N);
806     unsigned operator ()();
807
808     // returns uniformly distributed integer random number from [a,b) range
809     int uniform(int a, int b);
810     // returns uniformly distributed floating-point random number from [a,b) range
811     float uniform(float a, float b);
812     // returns uniformly distributed double-precision floating-point random number from [a,b) range
813     double uniform(double a, double b);
814
815 private:
816     enum PeriodParameters {N = 624, M = 397};
817     unsigned state[N];
818     int mti;
819 };
820
821
822
823 /////////////////////////////// Formatted output of cv::Mat ///////////////////////////
824
825 class CV_EXPORTS Formatted
826 {
827 public:
828     virtual const char* next() = 0;
829     virtual void reset() = 0;
830     virtual ~Formatted();
831 };
832
833
834 class CV_EXPORTS Formatter
835 {
836 public:
837     enum { FMT_DEFAULT = 0,
838            FMT_MATLAB  = 1,
839            FMT_CSV     = 2,
840            FMT_PYTHON  = 3,
841            FMT_NUMPY   = 4,
842            FMT_C       = 5
843          };
844
845     virtual ~Formatter();
846
847     virtual Ptr<Formatted> format(const Mat& mtx) const = 0;
848
849     virtual void set32fPrecision(int p = 8) = 0;
850     virtual void set64fPrecision(int p = 16) = 0;
851     virtual void setMultiline(bool ml = true) = 0;
852
853     static Ptr<Formatter> get(int fmt = FMT_DEFAULT);
854
855 };
856
857
858
859 //////////////////////////////////////// Algorithm ////////////////////////////////////
860
861 class CV_EXPORTS Algorithm;
862 class CV_EXPORTS AlgorithmInfo;
863 struct CV_EXPORTS AlgorithmInfoData;
864
865 template<typename _Tp> struct ParamType {};
866
867 /*!
868   Base class for high-level OpenCV algorithms
869 */
870 class CV_EXPORTS_W Algorithm
871 {
872 public:
873     Algorithm();
874     virtual ~Algorithm();
875     String name() const;
876
877     template<typename _Tp> typename ParamType<_Tp>::member_type get(const String& name) const;
878     template<typename _Tp> typename ParamType<_Tp>::member_type get(const char* name) const;
879
880     CV_WRAP int getInt(const String& name) const;
881     CV_WRAP double getDouble(const String& name) const;
882     CV_WRAP bool getBool(const String& name) const;
883     CV_WRAP String getString(const String& name) const;
884     CV_WRAP Mat getMat(const String& name) const;
885     CV_WRAP std::vector<Mat> getMatVector(const String& name) const;
886     CV_WRAP Ptr<Algorithm> getAlgorithm(const String& name) const;
887
888     void set(const String& name, int value);
889     void set(const String& name, double value);
890     void set(const String& name, bool value);
891     void set(const String& name, const String& value);
892     void set(const String& name, const Mat& value);
893     void set(const String& name, const std::vector<Mat>& value);
894     void set(const String& name, const Ptr<Algorithm>& value);
895     template<typename _Tp> void set(const String& name, const Ptr<_Tp>& value);
896
897     CV_WRAP void setInt(const String& name, int value);
898     CV_WRAP void setDouble(const String& name, double value);
899     CV_WRAP void setBool(const String& name, bool value);
900     CV_WRAP void setString(const String& name, const String& value);
901     CV_WRAP void setMat(const String& name, const Mat& value);
902     CV_WRAP void setMatVector(const String& name, const std::vector<Mat>& value);
903     CV_WRAP void setAlgorithm(const String& name, const Ptr<Algorithm>& value);
904     template<typename _Tp> void setAlgorithm(const String& name, const Ptr<_Tp>& value);
905
906     void set(const char* name, int value);
907     void set(const char* name, double value);
908     void set(const char* name, bool value);
909     void set(const char* name, const String& value);
910     void set(const char* name, const Mat& value);
911     void set(const char* name, const std::vector<Mat>& value);
912     void set(const char* name, const Ptr<Algorithm>& value);
913     template<typename _Tp> void set(const char* name, const Ptr<_Tp>& value);
914
915     void setInt(const char* name, int value);
916     void setDouble(const char* name, double value);
917     void setBool(const char* name, bool value);
918     void setString(const char* name, const String& value);
919     void setMat(const char* name, const Mat& value);
920     void setMatVector(const char* name, const std::vector<Mat>& value);
921     void setAlgorithm(const char* name, const Ptr<Algorithm>& value);
922     template<typename _Tp> void setAlgorithm(const char* name, const Ptr<_Tp>& value);
923
924     CV_WRAP String paramHelp(const String& name) const;
925     int paramType(const char* name) const;
926     CV_WRAP int paramType(const String& name) const;
927     CV_WRAP void getParams(CV_OUT std::vector<String>& names) const;
928
929
930     virtual void write(FileStorage& fs) const;
931     virtual void read(const FileNode& fn);
932
933     typedef Algorithm* (*Constructor)(void);
934     typedef int (Algorithm::*Getter)() const;
935     typedef void (Algorithm::*Setter)(int);
936
937     CV_WRAP static void getList(CV_OUT std::vector<String>& algorithms);
938     CV_WRAP static Ptr<Algorithm> _create(const String& name);
939     template<typename _Tp> static Ptr<_Tp> create(const String& name);
940
941     virtual AlgorithmInfo* info() const /* TODO: make it = 0;*/ { return 0; }
942 };
943
944
945 class CV_EXPORTS AlgorithmInfo
946 {
947 public:
948     friend class Algorithm;
949     AlgorithmInfo(const String& name, Algorithm::Constructor create);
950     ~AlgorithmInfo();
951     void get(const Algorithm* algo, const char* name, int argType, void* value) const;
952     void addParam_(Algorithm& algo, const char* name, int argType,
953                    void* value, bool readOnly,
954                    Algorithm::Getter getter, Algorithm::Setter setter,
955                    const String& help=String());
956     String paramHelp(const char* name) const;
957     int paramType(const char* name) const;
958     void getParams(std::vector<String>& names) const;
959
960     void write(const Algorithm* algo, FileStorage& fs) const;
961     void read(Algorithm* algo, const FileNode& fn) const;
962     String name() const;
963
964     void addParam(Algorithm& algo, const char* name,
965                   int& value, bool readOnly=false,
966                   int (Algorithm::*getter)()=0,
967                   void (Algorithm::*setter)(int)=0,
968                   const String& help=String());
969     void addParam(Algorithm& algo, const char* name,
970                   bool& value, bool readOnly=false,
971                   int (Algorithm::*getter)()=0,
972                   void (Algorithm::*setter)(int)=0,
973                   const String& help=String());
974     void addParam(Algorithm& algo, const char* name,
975                   double& value, bool readOnly=false,
976                   double (Algorithm::*getter)()=0,
977                   void (Algorithm::*setter)(double)=0,
978                   const String& help=String());
979     void addParam(Algorithm& algo, const char* name,
980                   String& value, bool readOnly=false,
981                   String (Algorithm::*getter)()=0,
982                   void (Algorithm::*setter)(const String&)=0,
983                   const String& help=String());
984     void addParam(Algorithm& algo, const char* name,
985                   Mat& value, bool readOnly=false,
986                   Mat (Algorithm::*getter)()=0,
987                   void (Algorithm::*setter)(const Mat&)=0,
988                   const String& help=String());
989     void addParam(Algorithm& algo, const char* name,
990                   std::vector<Mat>& value, bool readOnly=false,
991                   std::vector<Mat> (Algorithm::*getter)()=0,
992                   void (Algorithm::*setter)(const std::vector<Mat>&)=0,
993                   const String& help=String());
994     void addParam(Algorithm& algo, const char* name,
995                   Ptr<Algorithm>& value, bool readOnly=false,
996                   Ptr<Algorithm> (Algorithm::*getter)()=0,
997                   void (Algorithm::*setter)(const Ptr<Algorithm>&)=0,
998                   const String& help=String());
999     void addParam(Algorithm& algo, const char* name,
1000                   float& value, bool readOnly=false,
1001                   float (Algorithm::*getter)()=0,
1002                   void (Algorithm::*setter)(float)=0,
1003                   const String& help=String());
1004     void addParam(Algorithm& algo, const char* name,
1005                   unsigned int& value, bool readOnly=false,
1006                   unsigned int (Algorithm::*getter)()=0,
1007                   void (Algorithm::*setter)(unsigned int)=0,
1008                   const String& help=String());
1009     void addParam(Algorithm& algo, const char* name,
1010                   uint64& value, bool readOnly=false,
1011                   uint64 (Algorithm::*getter)()=0,
1012                   void (Algorithm::*setter)(uint64)=0,
1013                   const String& help=String());
1014     void addParam(Algorithm& algo, const char* name,
1015                   uchar& value, bool readOnly=false,
1016                   uchar (Algorithm::*getter)()=0,
1017                   void (Algorithm::*setter)(uchar)=0,
1018                   const String& help=String());
1019     template<typename _Tp, typename _Base> void addParam(Algorithm& algo, const char* name,
1020                   Ptr<_Tp>& value, bool readOnly=false,
1021                   Ptr<_Tp> (Algorithm::*getter)()=0,
1022                   void (Algorithm::*setter)(const Ptr<_Tp>&)=0,
1023                   const String& help=String());
1024     template<typename _Tp> void addParam(Algorithm& algo, const char* name,
1025                   Ptr<_Tp>& value, bool readOnly=false,
1026                   Ptr<_Tp> (Algorithm::*getter)()=0,
1027                   void (Algorithm::*setter)(const Ptr<_Tp>&)=0,
1028                   const String& help=String());
1029 protected:
1030     AlgorithmInfoData* data;
1031     void set(Algorithm* algo, const char* name, int argType,
1032               const void* value, bool force=false) const;
1033 };
1034
1035
1036 struct CV_EXPORTS Param
1037 {
1038     enum { INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7, UNSIGNED_INT=8, UINT64=9, UCHAR=11 };
1039
1040     Param();
1041     Param(int _type, bool _readonly, int _offset,
1042           Algorithm::Getter _getter=0,
1043           Algorithm::Setter _setter=0,
1044           const String& _help=String());
1045     int type;
1046     int offset;
1047     bool readonly;
1048     Algorithm::Getter getter;
1049     Algorithm::Setter setter;
1050     String help;
1051 };
1052
1053 template<> struct ParamType<bool>
1054 {
1055     typedef bool const_param_type;
1056     typedef bool member_type;
1057
1058     enum { type = Param::BOOLEAN };
1059 };
1060
1061 template<> struct ParamType<int>
1062 {
1063     typedef int const_param_type;
1064     typedef int member_type;
1065
1066     enum { type = Param::INT };
1067 };
1068
1069 template<> struct ParamType<double>
1070 {
1071     typedef double const_param_type;
1072     typedef double member_type;
1073
1074     enum { type = Param::REAL };
1075 };
1076
1077 template<> struct ParamType<String>
1078 {
1079     typedef const String& const_param_type;
1080     typedef String member_type;
1081
1082     enum { type = Param::STRING };
1083 };
1084
1085 template<> struct ParamType<Mat>
1086 {
1087     typedef const Mat& const_param_type;
1088     typedef Mat member_type;
1089
1090     enum { type = Param::MAT };
1091 };
1092
1093 template<> struct ParamType<std::vector<Mat> >
1094 {
1095     typedef const std::vector<Mat>& const_param_type;
1096     typedef std::vector<Mat> member_type;
1097
1098     enum { type = Param::MAT_VECTOR };
1099 };
1100
1101 template<> struct ParamType<Algorithm>
1102 {
1103     typedef const Ptr<Algorithm>& const_param_type;
1104     typedef Ptr<Algorithm> member_type;
1105
1106     enum { type = Param::ALGORITHM };
1107 };
1108
1109 template<> struct ParamType<float>
1110 {
1111     typedef float const_param_type;
1112     typedef float member_type;
1113
1114     enum { type = Param::FLOAT };
1115 };
1116
1117 template<> struct ParamType<unsigned>
1118 {
1119     typedef unsigned const_param_type;
1120     typedef unsigned member_type;
1121
1122     enum { type = Param::UNSIGNED_INT };
1123 };
1124
1125 template<> struct ParamType<uint64>
1126 {
1127     typedef uint64 const_param_type;
1128     typedef uint64 member_type;
1129
1130     enum { type = Param::UINT64 };
1131 };
1132
1133 template<> struct ParamType<uchar>
1134 {
1135     typedef uchar const_param_type;
1136     typedef uchar member_type;
1137
1138     enum { type = Param::UCHAR };
1139 };
1140
1141 } //namespace cv
1142
1143 #include "opencv2/core/operations.hpp"
1144 #include "opencv2/core/cvstd.inl.hpp"
1145 #include "opencv2/core/utility.hpp"
1146 #include "opencv2/core/optim.hpp"
1147
1148 #endif /*__OPENCV_CORE_HPP__*/