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().
105 \param exc the exception raisen.
106 \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;
751 Random Number Generator
753 The class implements RNG using Multiply-with-Carry algorithm
764 //! updates the state and returns the next 32-bit unsigned integer random number
772 //! returns a random integer sampled uniformly from [0, N).
773 unsigned operator ()(unsigned N);
774 unsigned operator ()();
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);
791 class CV_EXPORTS RNG_MT19937
795 RNG_MT19937(unsigned s);
796 void seed(unsigned s);
805 unsigned operator ()(unsigned N);
806 unsigned operator ()();
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);
816 enum PeriodParameters {N = 624, M = 397};
823 /////////////////////////////// Formatted output of cv::Mat ///////////////////////////
825 class CV_EXPORTS Formatted
828 virtual const char* next() = 0;
829 virtual void reset() = 0;
830 virtual ~Formatted();
834 class CV_EXPORTS Formatter
837 enum { FMT_DEFAULT = 0,
845 virtual ~Formatter();
847 virtual Ptr<Formatted> format(const Mat& mtx) const = 0;
849 virtual void set32fPrecision(int p = 8) = 0;
850 virtual void set64fPrecision(int p = 16) = 0;
851 virtual void setMultiline(bool ml = true) = 0;
853 static Ptr<Formatter> get(int fmt = FMT_DEFAULT);
859 //////////////////////////////////////// Algorithm ////////////////////////////////////
861 class CV_EXPORTS Algorithm;
862 class CV_EXPORTS AlgorithmInfo;
863 struct CV_EXPORTS AlgorithmInfoData;
865 template<typename _Tp> struct ParamType {};
868 Base class for high-level OpenCV algorithms
870 class CV_EXPORTS_W Algorithm
874 virtual ~Algorithm();
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;
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;
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);
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);
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);
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);
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;
930 virtual void write(FileStorage& fs) const;
931 virtual void read(const FileNode& fn);
933 typedef Algorithm* (*Constructor)(void);
934 typedef int (Algorithm::*Getter)() const;
935 typedef void (Algorithm::*Setter)(int);
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);
941 virtual AlgorithmInfo* info() const /* TODO: make it = 0;*/ { return 0; }
945 class CV_EXPORTS AlgorithmInfo
948 friend class Algorithm;
949 AlgorithmInfo(const String& name, Algorithm::Constructor create);
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;
960 void write(const Algorithm* algo, FileStorage& fs) const;
961 void read(Algorithm* algo, const FileNode& fn) const;
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());
1030 AlgorithmInfoData* data;
1031 void set(Algorithm* algo, const char* name, int argType,
1032 const void* value, bool force=false) const;
1036 struct CV_EXPORTS Param
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 };
1041 Param(int _type, bool _readonly, int _offset,
1042 Algorithm::Getter _getter=0,
1043 Algorithm::Setter _setter=0,
1044 const String& _help=String());
1048 Algorithm::Getter getter;
1049 Algorithm::Setter setter;
1053 template<> struct ParamType<bool>
1055 typedef bool const_param_type;
1056 typedef bool member_type;
1058 enum { type = Param::BOOLEAN };
1061 template<> struct ParamType<int>
1063 typedef int const_param_type;
1064 typedef int member_type;
1066 enum { type = Param::INT };
1069 template<> struct ParamType<double>
1071 typedef double const_param_type;
1072 typedef double member_type;
1074 enum { type = Param::REAL };
1077 template<> struct ParamType<String>
1079 typedef const String& const_param_type;
1080 typedef String member_type;
1082 enum { type = Param::STRING };
1085 template<> struct ParamType<Mat>
1087 typedef const Mat& const_param_type;
1088 typedef Mat member_type;
1090 enum { type = Param::MAT };
1093 template<> struct ParamType<std::vector<Mat> >
1095 typedef const std::vector<Mat>& const_param_type;
1096 typedef std::vector<Mat> member_type;
1098 enum { type = Param::MAT_VECTOR };
1101 template<> struct ParamType<Algorithm>
1103 typedef const Ptr<Algorithm>& const_param_type;
1104 typedef Ptr<Algorithm> member_type;
1106 enum { type = Param::ALGORITHM };
1109 template<> struct ParamType<float>
1111 typedef float const_param_type;
1112 typedef float member_type;
1114 enum { type = Param::FLOAT };
1117 template<> struct ParamType<unsigned>
1119 typedef unsigned const_param_type;
1120 typedef unsigned member_type;
1122 enum { type = Param::UNSIGNED_INT };
1125 template<> struct ParamType<uint64>
1127 typedef uint64 const_param_type;
1128 typedef uint64 member_type;
1130 enum { type = Param::UINT64 };
1133 template<> struct ParamType<uchar>
1135 typedef uchar const_param_type;
1136 typedef uchar member_type;
1138 enum { type = Param::UCHAR };
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"
1148 #endif /*__OPENCV_CORE_HPP__*/