1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
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.
11 // For Open Source Computer Vision Library
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.
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
20 // * Redistribution's of source code must retain the above copyright notice,
21 // this list of conditions and the following disclaimer.
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.
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.
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.
43 #ifndef __OPENCV_CORE_HPP__
44 #define __OPENCV_CORE_HPP__
47 # error core.hpp header must be compiled as C++
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"
61 Namespace where all the C++ OpenCV functionality resides
66 The standard OpenCV exception class.
67 Instances of the class are thrown by various functions and methods in the case of critical errors.
69 class CV_EXPORTS Exception : public std::exception
77 Full constructor. Normally the constuctor is not called explicitly.
78 Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used.
80 Exception(int _code, const String& _err, const String& _func, const String& _file, int _line);
81 virtual ~Exception() throw();
84 \return the error description and the context as a text string.
86 virtual const char *what() const throw();
89 String msg; ///< the formatted error message
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
99 //! Signals an error and raises the exception.
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().
106 \param exc the exception raisen.
108 //TODO: drop this version
109 CV_EXPORTS void error( const Exception& exc );
112 enum { SORT_EVERY_ROW = 0,
113 SORT_EVERY_COLUMN = 1,
118 enum { COVAR_SCRAMBLED = 0,
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
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,
151 enum { REDUCE_SUM = 0,
158 //! swaps two matrices
159 CV_EXPORTS void swap(Mat& a, Mat& b);
161 //! swaps two umatrices
162 CV_EXPORTS void swap( UMat& a, UMat& b );
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);
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() );
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);
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);
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);
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);
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);
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);
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);
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);
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);
206 //! computes sum of array elements
207 CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src);
209 //! computes the number of nonzero array elements
210 CV_EXPORTS_W int countNonZero( InputArray src );
212 //! returns the list of locations of non-zero pixels
213 CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx );
215 //! computes mean value of selected array elements
216 CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask = noArray());
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());
222 //! computes norm of the selected array part
223 CV_EXPORTS_W double norm(InputArray src1, int normType = NORM_L2, InputArray mask = noArray());
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());
229 //! computes PSNR image/video quality metric
230 CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2);
232 //! computes norm of a sparse matrix
233 CV_EXPORTS double norm( const SparseMat& src, int normType );
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);
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());
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 );
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());
254 CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal = 0,
255 int* minIdx = 0, int* maxIdx = 0, InputArray mask = noArray());
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);
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);
264 //! makes multi-channel array out of several single-channel arrays
265 CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst);
267 //! makes multi-channel array out of several single-channel arrays
268 CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst);
270 //! copies each plane of a multi-channel array to a dedicated array
271 CV_EXPORTS void split(const Mat& src, Mat* mvbegin);
273 //! copies each plane of a multi-channel array to a dedicated array
274 CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv);
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);
280 CV_EXPORTS void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst,
281 const int* fromTo, size_t npairs);
283 CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst,
284 const std::vector<int>& fromTo);
286 //! extracts a single channel from src (coi is 0-based index)
287 CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi);
289 //! inserts a single channel to dst (coi is 0-based index)
290 CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi);
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);
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);
298 CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx);
300 CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, OutputArray dst);
302 CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst);
304 CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst);
306 CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst);
308 CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst);
310 CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst);
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());
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());
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());
324 //! inverts each bit of array (dst = ~src)
325 CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst,
326 InputArray mask = noArray());
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);
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);
335 //! compares elements of two arrays (dst = src1 <cmpop> src2)
336 CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop);
338 //! computes per-element minimum of two arrays (dst = min(src1, src2))
339 CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst);
341 //! computes per-element maximum of two arrays (dst = max(src1, src2))
342 CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst);
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);
355 //! computes square root of each matrix element (dst = src**0.5)
356 CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst);
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);
361 //! computes exponent of each matrix element (dst = e**src)
362 CV_EXPORTS_W void exp(InputArray src, OutputArray dst);
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);
367 //! converts polar coordinates to Cartesian
368 CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle,
369 OutputArray x, OutputArray y, bool angleInDegrees = false);
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);
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);
380 //! computes magnitude (magnitude(i)) of each (x(i), y(i)) vector
381 CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude);
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);
387 //! converts NaN's to the given number
388 CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0);
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);
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 );
399 //! transposes the matrix
400 CV_EXPORTS_W void transpose(InputArray src, OutputArray dst);
402 //! performs affine transformation of each element of multi-channel input matrix
403 CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m );
405 //! performs perspective transformation of each element of multi-channel input matrix
406 CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m );
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);
411 //! initializes scaled identity matrix
412 CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s = Scalar(1));
414 //! computes determinant of a square matrix
415 CV_EXPORTS_W double determinant(InputArray mtx);
417 //! computes trace of a matrix
418 CV_EXPORTS_W Scalar trace(InputArray mtx);
420 //! computes inverse or pseudo-inverse matrix
421 CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags = DECOMP_LU);
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);
427 //! sorts independently each matrix row or each matrix column
428 CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags);
430 //! sorts independently each matrix row or each matrix column
431 CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags);
433 //! finds real roots of a cubic polynomial
434 CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots);
436 //! finds real and complex roots of a polynomial
437 CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters = 300);
439 //! finds eigenvalues and eigenvectors of a symmetric matrix
440 CV_EXPORTS_W bool eigen(InputArray src, OutputArray eigenvalues,
441 OutputArray eigenvectors = noArray());
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
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);
451 CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean,
452 OutputArray eigenvectors, int maxComponents = 0);
454 CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean,
455 OutputArray eigenvectors, double retainedVariance);
457 CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean,
458 InputArray eigenvectors, OutputArray result);
460 CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean,
461 InputArray eigenvectors, OutputArray result);
463 //! computes SVD of src
464 CV_EXPORTS_W void SVDecomp( InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags = 0 );
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 );
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);
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);
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);
479 //! performs forward or inverse 1D or 2D Discrete Cosine Transformation
480 CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags = 0);
482 //! performs inverse 1D or 2D Discrete Cosine Transformation
483 CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags = 0);
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);
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);
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() );
497 //! returns the thread-local Random number generator
498 CV_EXPORTS RNG& theRNG();
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);
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);
506 //! shuffles the input array elements
507 CV_EXPORTS_W void randShuffle(InputOutputArray dst, double iterFactor = 1., RNG* rng = 0);
510 Principal Component Analysis
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.
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.
528 PCA compressPCA(const Mat& pcaset, int maxComponents,
529 const Mat& testset, Mat& compressed)
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
540 // if there is no test data, just return the computed basis, ready-to-use
543 CV_Assert( testset.cols == pcaset.cols );
545 compressed.create(testset.rows, maxComponents, testset.type());
548 for( int i = 0; i < testset.rows; i++ )
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));
566 enum { DATA_AS_ROW = 0,
571 //! default constructor
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);
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);
582 //! projects vector from the original space to the principal components subspace
583 Mat project(InputArray vec) const;
585 //! projects vector from the original space to the principal components subspace
586 void project(InputArray vec, OutputArray result) const;
588 //! reconstructs the original vector from the projection
589 Mat backProject(InputArray vec) const;
591 //! reconstructs the original vector from the projection
592 void backProject(InputArray vec, OutputArray result) const;
594 //! write and load PCA matrix
595 void write(FileStorage& fs ) const;
596 void read(const FileNode& fs);
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
603 // Linear Discriminant Analysis
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);
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);
617 // Serializes this object to a given filename.
618 void save(const String& filename) const;
620 // Deserializes this object from a given filename.
621 void load(const String& filename);
623 // Serializes this object to a given cv::FileStorage.
624 void save(FileStorage& fs) const;
626 // Deserializes this object from a given cv::FileStorage.
627 void load(const FileStorage& node);
632 //! Compute the discriminants for data in src and labels.
633 void compute(InputArrayOfArrays src, InputArray labels);
635 // Projects samples into the LDA subspace.
636 Mat project(InputArray src);
638 // Reconstructs projections from the LDA subspace.
639 Mat reconstruct(InputArray src);
641 // Returns the eigenvectors of this LDA.
642 Mat eigenvectors() const { return _eigenvectors; }
644 // Returns the eigenvalues of this LDA.
645 Mat eigenvalues() const { return _eigenvalues; }
647 static Mat subspaceProject(InputArray W, InputArray mean, InputArray src);
648 static Mat subspaceReconstruct(InputArray W, InputArray mean, InputArray src);
656 void lda(InputArrayOfArrays src, InputArray labels);
660 Singular Value Decomposition class
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.
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.
680 //! the default constructor
683 //! the constructor that performs SVD
684 SVD( InputArray src, int flags = 0 );
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 );
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 );
693 //! computes singular values of a matrix
694 static void compute( InputArray src, OutputArray w, int flags = 0 );
696 //! performs back substitution
697 static void backSubst( InputArray w, InputArray u,
698 InputArray vt, InputArray rhs,
701 //! finds dst = arg min_{|dst|=1} |m*dst|
702 static void solveZ( InputArray src, OutputArray dst );
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;
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 );
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 );
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 );
724 The class is used to iterate over all the pixels on the raster line
725 segment connecting two specified points.
727 class CV_EXPORTS LineIterator
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
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
746 int minusDelta, plusDelta;
747 int minusStep, plusStep;
753 Fast Nearest Neighbor Search Class.
755 The class implements D. Lowe BBF (Best-Bin-First) algorithm for the last
756 approximate (or accurate) nearest neighbor search in multi-dimensional spaces.
758 First, a set of vectors is passed to KDTree::KDTree() constructor
759 or KDTree::build() method, where it is reordered.
761 Then arbitrary vectors can be passed to KDTree::findNearest() methods, which
762 find the K nearest neighbors among the vectors from the initial set.
763 The user can balance between the speed and accuracy of the search by varying Emax
764 parameter, which is the number of leaves that the algorithm checks.
765 The larger parameter values yield more accurate results at the expense of lower processing speed.
768 KDTree T(points, false);
769 const int K = 3, Emax = INT_MAX;
772 T.findNearest(query_vec, K, Emax, idx, 0, dist);
773 CV_Assert(dist[0] <= dist[1] && dist[1] <= dist[2]);
776 class CV_EXPORTS_W KDTree
780 The node of the search tree.
784 Node() : idx(-1), left(-1), right(-1), boundary(0.f) {}
785 Node(int _idx, int _left, int _right, float _boundary)
786 : idx(_idx), left(_left), right(_right), boundary(_boundary) {}
788 //! split dimension; >=0 for nodes (dim), < 0 for leaves (index of the point)
790 //! node indices of the left and the right branches
792 //! go to the left if query_vec[node.idx]<=node.boundary, otherwise go to the right
796 //! the default constructor
798 //! the full constructor that builds the search tree
799 CV_WRAP KDTree(InputArray points, bool copyAndReorderPoints = false);
800 //! the full constructor that builds the search tree
801 CV_WRAP KDTree(InputArray points, InputArray _labels,
802 bool copyAndReorderPoints = false);
803 //! builds the search tree
804 CV_WRAP void build(InputArray points, bool copyAndReorderPoints = false);
805 //! builds the search tree
806 CV_WRAP void build(InputArray points, InputArray labels,
807 bool copyAndReorderPoints = false);
808 //! finds the K nearest neighbors of "vec" while looking at Emax (at most) leaves
809 CV_WRAP int findNearest(InputArray vec, int K, int Emax,
810 OutputArray neighborsIdx,
811 OutputArray neighbors = noArray(),
812 OutputArray dist = noArray(),
813 OutputArray labels = noArray()) const;
814 //! finds all the points from the initial set that belong to the specified box
815 CV_WRAP void findOrthoRange(InputArray minBounds,
816 InputArray maxBounds,
817 OutputArray neighborsIdx,
818 OutputArray neighbors = noArray(),
819 OutputArray labels = noArray()) const;
820 //! returns vectors with the specified indices
821 CV_WRAP void getPoints(InputArray idx, OutputArray pts,
822 OutputArray labels = noArray()) const;
823 //! return a vector with the specified index
824 const float* getPoint(int ptidx, int* label = 0) const;
825 //! returns the search space dimensionality
826 CV_WRAP int dims() const;
828 std::vector<Node> nodes; //!< all the tree nodes
829 CV_PROP Mat points; //!< all the points. It can be a reordered copy of the input vector set or the original vector set.
830 CV_PROP std::vector<int> labels; //!< the parallel array of labels.
831 CV_PROP int maxDepth; //!< maximum depth of the search tree. Do not modify it
832 CV_PROP_RW int normType; //!< type of the distance (cv::NORM_L1 or cv::NORM_L2) used for search. Initially set to cv::NORM_L2, but you can modify it
838 Random Number Generator
840 The class implements RNG using Multiply-with-Carry algorithm
851 //! updates the state and returns the next 32-bit unsigned integer random number
859 //! returns a random integer sampled uniformly from [0, N).
860 unsigned operator ()(unsigned N);
861 unsigned operator ()();
865 //! returns uniformly distributed integer random number from [a,b) range
866 int uniform(int a, int b);
867 //! returns uniformly distributed floating-point random number from [a,b) range
868 float uniform(float a, float b);
869 //! returns uniformly distributed double-precision floating-point random number from [a,b) range
870 double uniform(double a, double b);
871 void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange = false );
872 //! returns Gaussian random variate with mean zero.
873 double gaussian(double sigma);
878 class CV_EXPORTS RNG_MT19937
882 RNG_MT19937(unsigned s);
883 void seed(unsigned s);
892 unsigned operator ()(unsigned N);
893 unsigned operator ()();
895 // returns uniformly distributed integer random number from [a,b) range
896 int uniform(int a, int b);
897 // returns uniformly distributed floating-point random number from [a,b) range
898 float uniform(float a, float b);
899 // returns uniformly distributed double-precision floating-point random number from [a,b) range
900 double uniform(double a, double b);
903 enum PeriodParameters {N = 624, M = 397};
910 /////////////////////////////// Formatted output of cv::Mat ///////////////////////////
912 class CV_EXPORTS Formatted
915 virtual const char* next() = 0;
916 virtual void reset() = 0;
917 virtual ~Formatted();
921 class CV_EXPORTS Formatter
924 enum { FMT_DEFAULT = 0,
932 virtual ~Formatter();
934 virtual Ptr<Formatted> format(const Mat& mtx) const = 0;
936 virtual void set32fPrecision(int p = 8) = 0;
937 virtual void set64fPrecision(int p = 16) = 0;
938 virtual void setMultiline(bool ml = true) = 0;
940 static Ptr<Formatter> get(int fmt = FMT_DEFAULT);
946 //////////////////////////////////////// Algorithm ////////////////////////////////////
948 class CV_EXPORTS Algorithm;
949 class CV_EXPORTS AlgorithmInfo;
950 struct CV_EXPORTS AlgorithmInfoData;
952 template<typename _Tp> struct ParamType {};
955 Base class for high-level OpenCV algorithms
957 class CV_EXPORTS_W Algorithm
961 virtual ~Algorithm();
964 template<typename _Tp> typename ParamType<_Tp>::member_type get(const String& name) const;
965 template<typename _Tp> typename ParamType<_Tp>::member_type get(const char* name) const;
967 CV_WRAP int getInt(const String& name) const;
968 CV_WRAP double getDouble(const String& name) const;
969 CV_WRAP bool getBool(const String& name) const;
970 CV_WRAP String getString(const String& name) const;
971 CV_WRAP Mat getMat(const String& name) const;
972 CV_WRAP std::vector<Mat> getMatVector(const String& name) const;
973 CV_WRAP Ptr<Algorithm> getAlgorithm(const String& name) const;
975 void set(const String& name, int value);
976 void set(const String& name, double value);
977 void set(const String& name, bool value);
978 void set(const String& name, const String& value);
979 void set(const String& name, const Mat& value);
980 void set(const String& name, const std::vector<Mat>& value);
981 void set(const String& name, const Ptr<Algorithm>& value);
982 template<typename _Tp> void set(const String& name, const Ptr<_Tp>& value);
984 CV_WRAP void setInt(const String& name, int value);
985 CV_WRAP void setDouble(const String& name, double value);
986 CV_WRAP void setBool(const String& name, bool value);
987 CV_WRAP void setString(const String& name, const String& value);
988 CV_WRAP void setMat(const String& name, const Mat& value);
989 CV_WRAP void setMatVector(const String& name, const std::vector<Mat>& value);
990 CV_WRAP void setAlgorithm(const String& name, const Ptr<Algorithm>& value);
991 template<typename _Tp> void setAlgorithm(const String& name, const Ptr<_Tp>& value);
993 void set(const char* name, int value);
994 void set(const char* name, double value);
995 void set(const char* name, bool value);
996 void set(const char* name, const String& value);
997 void set(const char* name, const Mat& value);
998 void set(const char* name, const std::vector<Mat>& value);
999 void set(const char* name, const Ptr<Algorithm>& value);
1000 template<typename _Tp> void set(const char* name, const Ptr<_Tp>& value);
1002 void setInt(const char* name, int value);
1003 void setDouble(const char* name, double value);
1004 void setBool(const char* name, bool value);
1005 void setString(const char* name, const String& value);
1006 void setMat(const char* name, const Mat& value);
1007 void setMatVector(const char* name, const std::vector<Mat>& value);
1008 void setAlgorithm(const char* name, const Ptr<Algorithm>& value);
1009 template<typename _Tp> void setAlgorithm(const char* name, const Ptr<_Tp>& value);
1011 CV_WRAP String paramHelp(const String& name) const;
1012 int paramType(const char* name) const;
1013 CV_WRAP int paramType(const String& name) const;
1014 CV_WRAP void getParams(CV_OUT std::vector<String>& names) const;
1017 virtual void write(FileStorage& fs) const;
1018 virtual void read(const FileNode& fn);
1020 typedef Algorithm* (*Constructor)(void);
1021 typedef int (Algorithm::*Getter)() const;
1022 typedef void (Algorithm::*Setter)(int);
1024 CV_WRAP static void getList(CV_OUT std::vector<String>& algorithms);
1025 CV_WRAP static Ptr<Algorithm> _create(const String& name);
1026 template<typename _Tp> static Ptr<_Tp> create(const String& name);
1028 virtual AlgorithmInfo* info() const /* TODO: make it = 0;*/ { return 0; }
1032 class CV_EXPORTS AlgorithmInfo
1035 friend class Algorithm;
1036 AlgorithmInfo(const String& name, Algorithm::Constructor create);
1038 void get(const Algorithm* algo, const char* name, int argType, void* value) const;
1039 void addParam_(Algorithm& algo, const char* name, int argType,
1040 void* value, bool readOnly,
1041 Algorithm::Getter getter, Algorithm::Setter setter,
1042 const String& help=String());
1043 String paramHelp(const char* name) const;
1044 int paramType(const char* name) const;
1045 void getParams(std::vector<String>& names) const;
1047 void write(const Algorithm* algo, FileStorage& fs) const;
1048 void read(Algorithm* algo, const FileNode& fn) const;
1049 String name() const;
1051 void addParam(Algorithm& algo, const char* name,
1052 int& value, bool readOnly=false,
1053 int (Algorithm::*getter)()=0,
1054 void (Algorithm::*setter)(int)=0,
1055 const String& help=String());
1056 void addParam(Algorithm& algo, const char* name,
1057 bool& value, bool readOnly=false,
1058 int (Algorithm::*getter)()=0,
1059 void (Algorithm::*setter)(int)=0,
1060 const String& help=String());
1061 void addParam(Algorithm& algo, const char* name,
1062 double& value, bool readOnly=false,
1063 double (Algorithm::*getter)()=0,
1064 void (Algorithm::*setter)(double)=0,
1065 const String& help=String());
1066 void addParam(Algorithm& algo, const char* name,
1067 String& value, bool readOnly=false,
1068 String (Algorithm::*getter)()=0,
1069 void (Algorithm::*setter)(const String&)=0,
1070 const String& help=String());
1071 void addParam(Algorithm& algo, const char* name,
1072 Mat& value, bool readOnly=false,
1073 Mat (Algorithm::*getter)()=0,
1074 void (Algorithm::*setter)(const Mat&)=0,
1075 const String& help=String());
1076 void addParam(Algorithm& algo, const char* name,
1077 std::vector<Mat>& value, bool readOnly=false,
1078 std::vector<Mat> (Algorithm::*getter)()=0,
1079 void (Algorithm::*setter)(const std::vector<Mat>&)=0,
1080 const String& help=String());
1081 void addParam(Algorithm& algo, const char* name,
1082 Ptr<Algorithm>& value, bool readOnly=false,
1083 Ptr<Algorithm> (Algorithm::*getter)()=0,
1084 void (Algorithm::*setter)(const Ptr<Algorithm>&)=0,
1085 const String& help=String());
1086 void addParam(Algorithm& algo, const char* name,
1087 float& value, bool readOnly=false,
1088 float (Algorithm::*getter)()=0,
1089 void (Algorithm::*setter)(float)=0,
1090 const String& help=String());
1091 void addParam(Algorithm& algo, const char* name,
1092 unsigned int& value, bool readOnly=false,
1093 unsigned int (Algorithm::*getter)()=0,
1094 void (Algorithm::*setter)(unsigned int)=0,
1095 const String& help=String());
1096 void addParam(Algorithm& algo, const char* name,
1097 uint64& value, bool readOnly=false,
1098 uint64 (Algorithm::*getter)()=0,
1099 void (Algorithm::*setter)(uint64)=0,
1100 const String& help=String());
1101 void addParam(Algorithm& algo, const char* name,
1102 uchar& value, bool readOnly=false,
1103 uchar (Algorithm::*getter)()=0,
1104 void (Algorithm::*setter)(uchar)=0,
1105 const String& help=String());
1106 template<typename _Tp, typename _Base> void addParam(Algorithm& algo, const char* name,
1107 Ptr<_Tp>& value, bool readOnly=false,
1108 Ptr<_Tp> (Algorithm::*getter)()=0,
1109 void (Algorithm::*setter)(const Ptr<_Tp>&)=0,
1110 const String& help=String());
1111 template<typename _Tp> void addParam(Algorithm& algo, const char* name,
1112 Ptr<_Tp>& value, bool readOnly=false,
1113 Ptr<_Tp> (Algorithm::*getter)()=0,
1114 void (Algorithm::*setter)(const Ptr<_Tp>&)=0,
1115 const String& help=String());
1117 AlgorithmInfoData* data;
1118 void set(Algorithm* algo, const char* name, int argType,
1119 const void* value, bool force=false) const;
1123 struct CV_EXPORTS Param
1125 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 };
1128 Param(int _type, bool _readonly, int _offset,
1129 Algorithm::Getter _getter=0,
1130 Algorithm::Setter _setter=0,
1131 const String& _help=String());
1135 Algorithm::Getter getter;
1136 Algorithm::Setter setter;
1140 template<> struct ParamType<bool>
1142 typedef bool const_param_type;
1143 typedef bool member_type;
1145 enum { type = Param::BOOLEAN };
1148 template<> struct ParamType<int>
1150 typedef int const_param_type;
1151 typedef int member_type;
1153 enum { type = Param::INT };
1156 template<> struct ParamType<double>
1158 typedef double const_param_type;
1159 typedef double member_type;
1161 enum { type = Param::REAL };
1164 template<> struct ParamType<String>
1166 typedef const String& const_param_type;
1167 typedef String member_type;
1169 enum { type = Param::STRING };
1172 template<> struct ParamType<Mat>
1174 typedef const Mat& const_param_type;
1175 typedef Mat member_type;
1177 enum { type = Param::MAT };
1180 template<> struct ParamType<std::vector<Mat> >
1182 typedef const std::vector<Mat>& const_param_type;
1183 typedef std::vector<Mat> member_type;
1185 enum { type = Param::MAT_VECTOR };
1188 template<> struct ParamType<Algorithm>
1190 typedef const Ptr<Algorithm>& const_param_type;
1191 typedef Ptr<Algorithm> member_type;
1193 enum { type = Param::ALGORITHM };
1196 template<> struct ParamType<float>
1198 typedef float const_param_type;
1199 typedef float member_type;
1201 enum { type = Param::FLOAT };
1204 template<> struct ParamType<unsigned>
1206 typedef unsigned const_param_type;
1207 typedef unsigned member_type;
1209 enum { type = Param::UNSIGNED_INT };
1212 template<> struct ParamType<uint64>
1214 typedef uint64 const_param_type;
1215 typedef uint64 member_type;
1217 enum { type = Param::UINT64 };
1220 template<> struct ParamType<uchar>
1222 typedef uchar const_param_type;
1223 typedef uchar member_type;
1225 enum { type = Param::UCHAR };
1230 #include "opencv2/core/operations.hpp"
1231 #include "opencv2/core/cvstd.inl.hpp"
1232 #include "opencv2/core/utility.hpp"
1233 #include "opencv2/core/optim.hpp"
1235 #endif /*__OPENCV_CORE_HPP__*/