2 \brief The Core Functionality
4 /*M///////////////////////////////////////////////////////////////////////////////////////
6 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
8 // By downloading, copying, installing or using the software you agree to this license.
9 // If you do not agree to this license, do not download, install,
10 // copy or use the software.
14 // For Open Source Computer Vision Library
16 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
17 // Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
18 // Third party copyrights are property of their respective owners.
20 // Redistribution and use in source and binary forms, with or without modification,
21 // are permitted provided that the following conditions are met:
23 // * Redistribution's of source code must retain the above copyright notice,
24 // this list of conditions and the following disclaimer.
26 // * Redistribution's in binary form must reproduce the above copyright notice,
27 // this list of conditions and the following disclaimer in the documentation
28 // and/or other materials provided with the distribution.
30 // * The name of the copyright holders may not be used to endorse or promote products
31 // derived from this software without specific prior written permission.
33 // This software is provided by the copyright holders and contributors "as is" and
34 // any express or implied warranties, including, but not limited to, the implied
35 // warranties of merchantability and fitness for a particular purpose are disclaimed.
36 // In no event shall the Intel Corporation or contributors be liable for any direct,
37 // indirect, incidental, special, exemplary, or consequential damages
38 // (including, but not limited to, procurement of substitute goods or services;
39 // loss of use, data, or profits; or business interruption) however caused
40 // and on any theory of liability, whether in contract, strict liability,
41 // or tort (including negligence or otherwise) arising in any way out of
42 // the use of this software, even if advised of the possibility of such damage.
46 #ifndef __OPENCV_CORE_HPP__
47 #define __OPENCV_CORE_HPP__
49 #include "opencv2/core/types_c.h"
50 #include "opencv2/core/version.hpp"
65 #endif // SKIP_INCLUDES
68 Namespace where all the C++ OpenCV functionality resides
81 template<typename _Tp> class CV_EXPORTS Size_;
82 template<typename _Tp> class CV_EXPORTS Point_;
83 template<typename _Tp> class CV_EXPORTS Rect_;
84 template<typename _Tp, int cn> class CV_EXPORTS Vec;
85 template<typename _Tp, int m, int n> class CV_EXPORTS Matx;
87 typedef std::string String;
110 class CV_EXPORTS MatExpr;
111 class CV_EXPORTS MatOp_Base;
112 class CV_EXPORTS MatArg;
113 class CV_EXPORTS MatConstIterator;
115 template<typename _Tp> class CV_EXPORTS Mat_;
116 template<typename _Tp> class CV_EXPORTS MatIterator_;
117 template<typename _Tp> class CV_EXPORTS MatConstIterator_;
118 template<typename _Tp> class CV_EXPORTS MatCommaInitializer_;
120 #if !defined(ANDROID) || (defined(_GLIBCXX_USE_WCHAR_T) && _GLIBCXX_USE_WCHAR_T)
121 typedef std::basic_string<wchar_t> WString;
123 CV_EXPORTS string fromUtf16(const WString& str);
124 CV_EXPORTS WString toUtf16(const string& str);
127 CV_EXPORTS string format( const char* fmt, ... );
128 CV_EXPORTS string tempfile( const char* suffix CV_DEFAULT(0));
130 // matrix decomposition types
131 enum { DECOMP_LU=0, DECOMP_SVD=1, DECOMP_EIG=2, DECOMP_CHOLESKY=3, DECOMP_QR=4, DECOMP_NORMAL=16 };
132 enum { NORM_INF=1, NORM_L1=2, NORM_L2=4, NORM_L2SQR=5, NORM_HAMMING=6, NORM_HAMMING2=7, NORM_TYPE_MASK=7, NORM_RELATIVE=8, NORM_MINMAX=32 };
133 enum { CMP_EQ=0, CMP_GT=1, CMP_GE=2, CMP_LT=3, CMP_LE=4, CMP_NE=5 };
134 enum { GEMM_1_T=1, GEMM_2_T=2, GEMM_3_T=4 };
135 enum { DFT_INVERSE=1, DFT_SCALE=2, DFT_ROWS=4, DFT_COMPLEX_OUTPUT=16, DFT_REAL_OUTPUT=32,
136 DCT_INVERSE = DFT_INVERSE, DCT_ROWS=DFT_ROWS };
140 The standard OpenCV exception class.
141 Instances of the class are thrown by various functions and methods in the case of critical errors.
143 class CV_EXPORTS Exception : public std::exception
151 Full constructor. Normally the constuctor is not called explicitly.
152 Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used.
154 Exception(int _code, const string& _err, const string& _func, const string& _file, int _line);
155 virtual ~Exception() throw();
158 \return the error description and the context as a text string.
160 virtual const char *what() const throw();
161 void formatMessage();
163 string msg; ///< the formatted error message
165 int code; ///< error code @see CVStatus
166 string err; ///< error description
167 string func; ///< function name. Available only when the compiler supports __func__ macro
168 string file; ///< source file name where the error has occured
169 int line; ///< line number in the source file where the error has occured
173 //! Signals an error and raises the exception.
176 By default the function prints information about the error to stderr,
177 then it either stops if setBreakOnError() had been called before or raises the exception.
178 It is possible to alternate error processing by using redirectError().
180 \param exc the exception raisen.
182 CV_EXPORTS void error( const Exception& exc );
184 //! Sets/resets the break-on-error mode.
187 When the break-on-error mode is set, the default error handler
188 issues a hardware exception, which can make debugging more convenient.
190 \return the previous state
192 CV_EXPORTS bool setBreakOnError(bool flag);
194 typedef int (CV_CDECL *ErrorCallback)( int status, const char* func_name,
195 const char* err_msg, const char* file_name,
196 int line, void* userdata );
198 //! Sets the new error handler and the optional user data.
201 The function sets the new error handler, called from cv::error().
203 \param errCallback the new error handler. If NULL, the default error handler is used.
204 \param userdata the optional user data pointer, passed to the callback.
205 \param prevUserdata the optional output parameter where the previous user data pointer is stored
207 \return the previous error handler
209 CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback,
210 void* userdata=0, void** prevUserdata=0);
213 #define CV_Error( code, msg ) cv::error( cv::Exception(code, msg, __func__, __FILE__, __LINE__) )
214 #define CV_Error_( code, args ) cv::error( cv::Exception(code, cv::format args, __func__, __FILE__, __LINE__) )
215 #define CV_Assert( expr ) if(!!(expr)) ; else cv::error( cv::Exception(CV_StsAssert, #expr, __func__, __FILE__, __LINE__) )
217 #define CV_Error( code, msg ) cv::error( cv::Exception(code, msg, "", __FILE__, __LINE__) )
218 #define CV_Error_( code, args ) cv::error( cv::Exception(code, cv::format args, "", __FILE__, __LINE__) )
219 #define CV_Assert( expr ) if(!!(expr)) ; else cv::error( cv::Exception(CV_StsAssert, #expr, "", __FILE__, __LINE__) )
223 #define CV_DbgAssert(expr) CV_Assert(expr)
225 #define CV_DbgAssert(expr)
228 CV_EXPORTS void glob(String pattern, std::vector<String>& result, bool recursive = false);
230 CV_EXPORTS void setNumThreads(int nthreads);
231 CV_EXPORTS int getNumThreads();
232 CV_EXPORTS int getThreadNum();
234 CV_EXPORTS_W const string& getBuildInformation();
236 //! Returns the number of ticks.
239 The function returns the number of ticks since the certain event (e.g. when the machine was turned on).
240 It can be used to initialize cv::RNG or to measure a function execution time by reading the tick count
241 before and after the function call. The granularity of ticks depends on the hardware and OS used. Use
242 cv::getTickFrequency() to convert ticks to seconds.
244 CV_EXPORTS_W int64 getTickCount();
247 Returns the number of ticks per seconds.
249 The function returns the number of ticks (as returned by cv::getTickCount()) per second.
250 The following code computes the execution time in milliseconds:
253 double exec_time = (double)getTickCount();
255 exec_time = ((double)getTickCount() - exec_time)*1000./getTickFrequency();
258 CV_EXPORTS_W double getTickFrequency();
261 Returns the number of CPU ticks.
263 On platforms where the feature is available, the function returns the number of CPU ticks
264 since the certain event (normally, the system power-on moment). Using this function
265 one can accurately measure the execution time of very small code fragments,
266 for which cv::getTickCount() granularity is not enough.
268 CV_EXPORTS_W int64 getCPUTickCount();
271 Returns SSE etc. support status
273 The function returns true if certain hardware features are available.
274 Currently, the following features are recognized:
277 - CV_CPU_SSE2 - SSE 2
278 - CV_CPU_SSE3 - SSE 3
279 - CV_CPU_SSSE3 - SSSE 3
280 - CV_CPU_SSE4_1 - SSE 4.1
281 - CV_CPU_SSE4_2 - SSE 4.2
282 - CV_CPU_POPCNT - POPCOUNT
285 \note {Note that the function output is not static. Once you called cv::useOptimized(false),
286 most of the hardware acceleration is disabled and thus the function will returns false,
287 until you call cv::useOptimized(true)}
289 CV_EXPORTS_W bool checkHardwareSupport(int feature);
291 //! returns the number of CPUs (including hyper-threading)
292 CV_EXPORTS_W int getNumberOfCPUs();
295 Allocates memory buffer
297 This is specialized OpenCV memory allocation function that returns properly aligned memory buffers.
298 The usage is identical to malloc(). The allocated buffers must be freed with cv::fastFree().
299 If there is not enough memory, the function calls cv::error(), which raises an exception.
301 \param bufSize buffer size in bytes
302 \return the allocated memory buffer.
304 CV_EXPORTS void* fastMalloc(size_t bufSize);
307 Frees the memory allocated with cv::fastMalloc
309 This is the corresponding deallocation function for cv::fastMalloc().
310 When ptr==NULL, the function has no effect.
312 CV_EXPORTS void fastFree(void* ptr);
314 template<typename _Tp> static inline _Tp* allocate(size_t n)
319 template<typename _Tp> static inline void deallocate(_Tp* ptr, size_t)
325 Aligns pointer by the certain number of bytes
327 This small inline function aligns the pointer by the certian number of bytes by shifting
328 it forward by 0 or a positive offset.
330 template<typename _Tp> static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp))
332 return (_Tp*)(((size_t)ptr + n-1) & -n);
336 Aligns buffer size by the certain number of bytes
338 This small inline function aligns a buffer size by the certian number of bytes by enlarging it.
340 static inline size_t alignSize(size_t sz, int n)
342 return (sz + n-1) & -n;
346 Turns on/off available optimization
348 The function turns on or off the optimized code in OpenCV. Some optimization can not be enabled
349 or disabled, but, for example, most of SSE code in OpenCV can be temporarily turned on or off this way.
351 \note{Since optimization may imply using special data structures, it may be unsafe
352 to call this function anywhere in the code. Instead, call it somewhere at the top level.}
354 CV_EXPORTS_W void setUseOptimized(bool onoff);
357 Returns the current optimization status
359 The function returns the current optimization status, which is controlled by cv::setUseOptimized().
361 CV_EXPORTS_W bool useOptimized();
364 The STL-compilant memory Allocator based on cv::fastMalloc() and cv::fastFree()
366 template<typename _Tp> class CV_EXPORTS Allocator
369 typedef _Tp value_type;
370 typedef value_type* pointer;
371 typedef const value_type* const_pointer;
372 typedef value_type& reference;
373 typedef const value_type& const_reference;
374 typedef size_t size_type;
375 typedef ptrdiff_t difference_type;
376 template<typename U> class rebind { typedef Allocator<U> other; };
378 explicit Allocator() {}
380 explicit Allocator(Allocator const&) {}
382 explicit Allocator(Allocator<U> const&) {}
385 pointer address(reference r) { return &r; }
386 const_pointer address(const_reference r) { return &r; }
388 pointer allocate(size_type count, const void* =0)
389 { return reinterpret_cast<pointer>(fastMalloc(count * sizeof (_Tp))); }
391 void deallocate(pointer p, size_type) {fastFree(p); }
393 size_type max_size() const
394 { return max(static_cast<_Tp>(-1)/sizeof(_Tp), 1); }
396 void construct(pointer p, const _Tp& v) { new(static_cast<void*>(p)) _Tp(v); }
397 void destroy(pointer p) { p->~_Tp(); }
400 /////////////////////// Vec (used as element of multi-channel images /////////////////////
403 A helper class for cv::DataType
405 The class is specialized for each fundamental numerical data type supported by OpenCV.
406 It provides DataDepth<T>::value constant.
408 template<typename _Tp> class CV_EXPORTS DataDepth {};
410 template<> class DataDepth<bool> { public: enum { value = CV_8U, fmt=(int)'u' }; };
411 template<> class DataDepth<uchar> { public: enum { value = CV_8U, fmt=(int)'u' }; };
412 template<> class DataDepth<schar> { public: enum { value = CV_8S, fmt=(int)'c' }; };
413 template<> class DataDepth<char> { public: enum { value = CV_8S, fmt=(int)'c' }; };
414 template<> class DataDepth<ushort> { public: enum { value = CV_16U, fmt=(int)'w' }; };
415 template<> class DataDepth<short> { public: enum { value = CV_16S, fmt=(int)'s' }; };
416 template<> class DataDepth<int> { public: enum { value = CV_32S, fmt=(int)'i' }; };
417 // this is temporary solution to support 32-bit unsigned integers
418 template<> class DataDepth<unsigned> { public: enum { value = CV_32S, fmt=(int)'i' }; };
419 template<> class DataDepth<float> { public: enum { value = CV_32F, fmt=(int)'f' }; };
420 template<> class DataDepth<double> { public: enum { value = CV_64F, fmt=(int)'d' }; };
421 template<typename _Tp> class DataDepth<_Tp*> { public: enum { value = CV_USRTYPE1, fmt=(int)'r' }; };
424 ////////////////////////////// Small Matrix ///////////////////////////
427 A short numerical vector.
429 This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements)
430 on which you can perform basic arithmetical operations, access individual elements using [] operator etc.
431 The vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc.,
432 which elements are dynamically allocated in the heap.
434 The template takes 2 parameters:
436 -# cn the number of elements
438 In addition to the universal notation like Vec<float, 3>, you can use shorter aliases
439 for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec<float, 3>.
442 struct CV_EXPORTS Matx_AddOp {};
443 struct CV_EXPORTS Matx_SubOp {};
444 struct CV_EXPORTS Matx_ScaleOp {};
445 struct CV_EXPORTS Matx_MulOp {};
446 struct CV_EXPORTS Matx_MatMulOp {};
447 struct CV_EXPORTS Matx_TOp {};
449 template<typename _Tp, int m, int n> class CV_EXPORTS Matx
452 typedef _Tp value_type;
453 typedef Matx<_Tp, (m < n ? m : n), 1> diag_type;
454 typedef Matx<_Tp, m, n> mat_type;
455 enum { depth = DataDepth<_Tp>::value, rows = m, cols = n, channels = rows*cols,
456 type = CV_MAKETYPE(depth, channels) };
458 //! default constructor
461 Matx(_Tp v0); //!< 1x1 matrix
462 Matx(_Tp v0, _Tp v1); //!< 1x2 or 2x1 matrix
463 Matx(_Tp v0, _Tp v1, _Tp v2); //!< 1x3 or 3x1 matrix
464 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 1x4, 2x2 or 4x1 matrix
465 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 1x5 or 5x1 matrix
466 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 1x6, 2x3, 3x2 or 6x1 matrix
467 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 1x7 or 7x1 matrix
468 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 1x8, 2x4, 4x2 or 8x1 matrix
469 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 1x9, 3x3 or 9x1 matrix
470 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 1x10, 2x5 or 5x2 or 10x1 matrix
471 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3,
472 _Tp v4, _Tp v5, _Tp v6, _Tp v7,
473 _Tp v8, _Tp v9, _Tp v10, _Tp v11); //!< 1x12, 2x6, 3x4, 4x3, 6x2 or 12x1 matrix
474 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3,
475 _Tp v4, _Tp v5, _Tp v6, _Tp v7,
476 _Tp v8, _Tp v9, _Tp v10, _Tp v11,
477 _Tp v12, _Tp v13, _Tp v14, _Tp v15); //!< 1x16, 4x4 or 16x1 matrix
478 explicit Matx(const _Tp* vals); //!< initialize from a plain array
480 static Matx all(_Tp alpha);
484 static Matx diag(const diag_type& d);
485 static Matx randu(_Tp a, _Tp b);
486 static Matx randn(_Tp a, _Tp b);
488 //! dot product computed with the default precision
489 _Tp dot(const Matx<_Tp, m, n>& v) const;
491 //! dot product computed in double-precision arithmetics
492 double ddot(const Matx<_Tp, m, n>& v) const;
494 //! convertion to another data type
495 template<typename T2> operator Matx<T2, m, n>() const;
497 //! change the matrix shape
498 template<int m1, int n1> Matx<_Tp, m1, n1> reshape() const;
500 //! extract part of the matrix
501 template<int m1, int n1> Matx<_Tp, m1, n1> get_minor(int i, int j) const;
503 //! extract the matrix row
504 Matx<_Tp, 1, n> row(int i) const;
506 //! extract the matrix column
507 Matx<_Tp, m, 1> col(int i) const;
509 //! extract the matrix diagonal
510 diag_type diag() const;
512 //! transpose the matrix
513 Matx<_Tp, n, m> t() const;
515 //! invert matrix the matrix
516 Matx<_Tp, n, m> inv(int method=DECOMP_LU) const;
518 //! solve linear system
519 template<int l> Matx<_Tp, n, l> solve(const Matx<_Tp, m, l>& rhs, int flags=DECOMP_LU) const;
520 Vec<_Tp, n> solve(const Vec<_Tp, m>& rhs, int method) const;
522 //! multiply two matrices element-wise
523 Matx<_Tp, m, n> mul(const Matx<_Tp, m, n>& a) const;
526 const _Tp& operator ()(int i, int j) const;
527 _Tp& operator ()(int i, int j);
529 //! 1D element access
530 const _Tp& operator ()(int i) const;
531 _Tp& operator ()(int i);
533 Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp);
534 Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp);
535 template<typename _T2> Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp);
536 Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp);
537 template<int l> Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp);
538 Matx(const Matx<_Tp, n, m>& a, Matx_TOp);
540 _Tp val[m*n]; //< matrix elements
544 typedef Matx<float, 1, 2> Matx12f;
545 typedef Matx<double, 1, 2> Matx12d;
546 typedef Matx<float, 1, 3> Matx13f;
547 typedef Matx<double, 1, 3> Matx13d;
548 typedef Matx<float, 1, 4> Matx14f;
549 typedef Matx<double, 1, 4> Matx14d;
550 typedef Matx<float, 1, 6> Matx16f;
551 typedef Matx<double, 1, 6> Matx16d;
553 typedef Matx<float, 2, 1> Matx21f;
554 typedef Matx<double, 2, 1> Matx21d;
555 typedef Matx<float, 3, 1> Matx31f;
556 typedef Matx<double, 3, 1> Matx31d;
557 typedef Matx<float, 4, 1> Matx41f;
558 typedef Matx<double, 4, 1> Matx41d;
559 typedef Matx<float, 6, 1> Matx61f;
560 typedef Matx<double, 6, 1> Matx61d;
562 typedef Matx<float, 2, 2> Matx22f;
563 typedef Matx<double, 2, 2> Matx22d;
564 typedef Matx<float, 2, 3> Matx23f;
565 typedef Matx<double, 2, 3> Matx23d;
566 typedef Matx<float, 3, 2> Matx32f;
567 typedef Matx<double, 3, 2> Matx32d;
569 typedef Matx<float, 3, 3> Matx33f;
570 typedef Matx<double, 3, 3> Matx33d;
572 typedef Matx<float, 3, 4> Matx34f;
573 typedef Matx<double, 3, 4> Matx34d;
574 typedef Matx<float, 4, 3> Matx43f;
575 typedef Matx<double, 4, 3> Matx43d;
577 typedef Matx<float, 4, 4> Matx44f;
578 typedef Matx<double, 4, 4> Matx44d;
579 typedef Matx<float, 6, 6> Matx66f;
580 typedef Matx<double, 6, 6> Matx66d;
584 A short numerical vector.
586 This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements)
587 on which you can perform basic arithmetical operations, access individual elements using [] operator etc.
588 The vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc.,
589 which elements are dynamically allocated in the heap.
591 The template takes 2 parameters:
593 -# cn the number of elements
595 In addition to the universal notation like Vec<float, 3>, you can use shorter aliases
596 for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec<float, 3>.
598 template<typename _Tp, int cn> class CV_EXPORTS Vec : public Matx<_Tp, cn, 1>
601 typedef _Tp value_type;
602 enum { depth = DataDepth<_Tp>::value, channels = cn, type = CV_MAKETYPE(depth, channels) };
604 //! default constructor
607 Vec(_Tp v0); //!< 1-element vector constructor
608 Vec(_Tp v0, _Tp v1); //!< 2-element vector constructor
609 Vec(_Tp v0, _Tp v1, _Tp v2); //!< 3-element vector constructor
610 Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 4-element vector constructor
611 Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 5-element vector constructor
612 Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 6-element vector constructor
613 Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 7-element vector constructor
614 Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 8-element vector constructor
615 Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 9-element vector constructor
616 Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 10-element vector constructor
617 explicit Vec(const _Tp* values);
619 Vec(const Vec<_Tp, cn>& v);
621 static Vec all(_Tp alpha);
623 //! per-element multiplication
624 Vec mul(const Vec<_Tp, cn>& v) const;
626 //! conjugation (makes sense for complex numbers and quaternions)
630 cross product of the two 3D vectors.
632 For other dimensionalities the exception is raised
634 Vec cross(const Vec& v) const;
635 //! convertion to another data type
636 template<typename T2> operator Vec<T2, cn>() const;
637 //! conversion to 4-element CvScalar.
638 operator CvScalar() const;
640 /*! element access */
641 const _Tp& operator [](int i) const;
642 _Tp& operator[](int i);
643 const _Tp& operator ()(int i) const;
644 _Tp& operator ()(int i);
646 Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp);
647 Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp);
648 template<typename _T2> Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp);
654 Shorter aliases for the most popular specializations of Vec<T,n>
656 typedef Vec<uchar, 2> Vec2b;
657 typedef Vec<uchar, 3> Vec3b;
658 typedef Vec<uchar, 4> Vec4b;
660 typedef Vec<short, 2> Vec2s;
661 typedef Vec<short, 3> Vec3s;
662 typedef Vec<short, 4> Vec4s;
664 typedef Vec<ushort, 2> Vec2w;
665 typedef Vec<ushort, 3> Vec3w;
666 typedef Vec<ushort, 4> Vec4w;
668 typedef Vec<int, 2> Vec2i;
669 typedef Vec<int, 3> Vec3i;
670 typedef Vec<int, 4> Vec4i;
671 typedef Vec<int, 6> Vec6i;
672 typedef Vec<int, 8> Vec8i;
674 typedef Vec<float, 2> Vec2f;
675 typedef Vec<float, 3> Vec3f;
676 typedef Vec<float, 4> Vec4f;
677 typedef Vec<float, 6> Vec6f;
679 typedef Vec<double, 2> Vec2d;
680 typedef Vec<double, 3> Vec3d;
681 typedef Vec<double, 4> Vec4d;
682 typedef Vec<double, 6> Vec6d;
685 //////////////////////////////// Complex //////////////////////////////
688 A complex number class.
690 The template class is similar and compatible with std::complex, however it provides slightly
691 more convenient access to the real and imaginary parts using through the simple field access, as opposite
692 to std::complex::real() and std::complex::imag().
694 template<typename _Tp> class CV_EXPORTS Complex
700 Complex( _Tp _re, _Tp _im=0 );
701 Complex( const std::complex<_Tp>& c );
703 //! conversion to another data type
704 template<typename T2> operator Complex<T2>() const;
706 Complex conj() const;
707 //! conversion to std::complex
708 operator std::complex<_Tp>() const;
710 _Tp re, im; //< the real and the imaginary parts
717 typedef Complex<float> Complexf;
718 typedef Complex<double> Complexd;
721 //////////////////////////////// Point_ ////////////////////////////////
724 template 2D point class.
726 The class defines a point in 2D space. Data type of the point coordinates is specified
727 as a template parameter. There are a few shorter aliases available for user convenience.
728 See cv::Point, cv::Point2i, cv::Point2f and cv::Point2d.
730 template<typename _Tp> class CV_EXPORTS Point_
733 typedef _Tp value_type;
735 // various constructors
737 Point_(_Tp _x, _Tp _y);
738 Point_(const Point_& pt);
739 Point_(const CvPoint& pt);
740 Point_(const CvPoint2D32f& pt);
741 Point_(const Size_<_Tp>& sz);
742 Point_(const Vec<_Tp, 2>& v);
744 Point_& operator = (const Point_& pt);
745 //! conversion to another data type
746 template<typename _Tp2> operator Point_<_Tp2>() const;
748 //! conversion to the old-style C structures
749 operator CvPoint() const;
750 operator CvPoint2D32f() const;
751 operator Vec<_Tp, 2>() const;
754 _Tp dot(const Point_& pt) const;
755 //! dot product computed in double-precision arithmetics
756 double ddot(const Point_& pt) const;
758 double cross(const Point_& pt) const;
759 //! checks whether the point is inside the specified rectangle
760 bool inside(const Rect_<_Tp>& r) const;
762 _Tp x, y; //< the point coordinates
766 template 3D point class.
768 The class defines a point in 3D space. Data type of the point coordinates is specified
769 as a template parameter.
771 \see cv::Point3i, cv::Point3f and cv::Point3d
773 template<typename _Tp> class CV_EXPORTS Point3_
776 typedef _Tp value_type;
778 // various constructors
780 Point3_(_Tp _x, _Tp _y, _Tp _z);
781 Point3_(const Point3_& pt);
782 explicit Point3_(const Point_<_Tp>& pt);
783 Point3_(const CvPoint3D32f& pt);
784 Point3_(const Vec<_Tp, 3>& v);
786 Point3_& operator = (const Point3_& pt);
787 //! conversion to another data type
788 template<typename _Tp2> operator Point3_<_Tp2>() const;
789 //! conversion to the old-style CvPoint...
790 operator CvPoint3D32f() const;
791 //! conversion to cv::Vec<>
792 operator Vec<_Tp, 3>() const;
795 _Tp dot(const Point3_& pt) const;
796 //! dot product computed in double-precision arithmetics
797 double ddot(const Point3_& pt) const;
798 //! cross product of the 2 3D points
799 Point3_ cross(const Point3_& pt) const;
801 _Tp x, y, z; //< the point coordinates
804 //////////////////////////////// Size_ ////////////////////////////////
809 The class represents the size of a 2D rectangle, image size, matrix size etc.
810 Normally, cv::Size ~ cv::Size_<int> is used.
812 template<typename _Tp> class CV_EXPORTS Size_
815 typedef _Tp value_type;
817 //! various constructors
819 Size_(_Tp _width, _Tp _height);
820 Size_(const Size_& sz);
821 Size_(const CvSize& sz);
822 Size_(const CvSize2D32f& sz);
823 Size_(const Point_<_Tp>& pt);
825 Size_& operator = (const Size_& sz);
826 //! the area (width*height)
829 //! conversion of another data type.
830 template<typename _Tp2> operator Size_<_Tp2>() const;
832 //! conversion to the old-style OpenCV types
833 operator CvSize() const;
834 operator CvSize2D32f() const;
836 _Tp width, height; // the width and the height
839 //////////////////////////////// Rect_ ////////////////////////////////
842 The 2D up-right rectangle class
844 The class represents a 2D rectangle with coordinates of the specified data type.
845 Normally, cv::Rect ~ cv::Rect_<int> is used.
847 template<typename _Tp> class CV_EXPORTS Rect_
850 typedef _Tp value_type;
852 //! various constructors
854 Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height);
855 Rect_(const Rect_& r);
856 Rect_(const CvRect& r);
857 Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz);
858 Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2);
860 Rect_& operator = ( const Rect_& r );
861 //! the top-left corner
862 Point_<_Tp> tl() const;
863 //! the bottom-right corner
864 Point_<_Tp> br() const;
866 //! size (width, height) of the rectangle
867 Size_<_Tp> size() const;
868 //! area (width*height) of the rectangle
871 //! conversion to another data type
872 template<typename _Tp2> operator Rect_<_Tp2>() const;
873 //! conversion to the old-style CvRect
874 operator CvRect() const;
876 //! checks whether the rectangle contains the point
877 bool contains(const Point_<_Tp>& pt) const;
879 _Tp x, y, width, height; //< the top-left corner, as well as width and height of the rectangle
886 shorter aliases for the most popular cv::Point_<>, cv::Size_<> and cv::Rect_<> specializations
888 typedef Point_<int> Point2i;
889 typedef Point2i Point;
890 typedef Size_<int> Size2i;
892 typedef Rect_<int> Rect;
893 typedef Point_<float> Point2f;
894 typedef Point_<double> Point2d;
895 typedef Size_<float> Size2f;
896 typedef Point3_<int> Point3i;
897 typedef Point3_<float> Point3f;
898 typedef Point3_<double> Point3d;
902 The rotated 2D rectangle.
904 The class represents rotated (i.e. not up-right) rectangles on a plane.
905 Each rectangle is described by the center point (mass center), length of each side
906 (represented by cv::Size2f structure) and the rotation angle in degrees.
908 class CV_EXPORTS RotatedRect
911 //! various constructors
913 RotatedRect(const Point2f& center, const Size2f& size, float angle);
914 RotatedRect(const CvBox2D& box);
916 //! returns 4 vertices of the rectangle
917 void points(Point2f pts[]) const;
918 //! returns the minimal up-right rectangle containing the rotated rectangle
919 Rect boundingRect() const;
920 //! conversion to the old-style CvBox2D structure
921 operator CvBox2D() const;
923 Point2f center; //< the rectangle mass center
924 Size2f size; //< width and height of the rectangle
925 float angle; //< the rotation angle. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle.
928 //////////////////////////////// Scalar_ ///////////////////////////////
931 The template scalar class.
933 This is partially specialized cv::Vec class with the number of elements = 4, i.e. a short vector of four elements.
934 Normally, cv::Scalar ~ cv::Scalar_<double> is used.
936 template<typename _Tp> class CV_EXPORTS Scalar_ : public Vec<_Tp, 4>
939 //! various constructors
941 Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0);
942 Scalar_(const CvScalar& s);
945 //! returns a scalar with all elements set to v0
946 static Scalar_<_Tp> all(_Tp v0);
947 //! conversion to the old-style CvScalar
948 operator CvScalar() const;
950 //! conversion to another data type
951 template<typename T2> operator Scalar_<T2>() const;
953 //! per-element product
954 Scalar_<_Tp> mul(const Scalar_<_Tp>& t, double scale=1 ) const;
956 // returns (v0, -v1, -v2, -v3)
957 Scalar_<_Tp> conj() const;
959 // returns true iff v1 == v2 == v3 == 0
963 typedef Scalar_<double> Scalar;
965 CV_EXPORTS void scalarToRawData(const Scalar& s, void* buf, int type, int unroll_to=0);
967 //////////////////////////////// Range /////////////////////////////////
972 This is the class used to specify a continuous subsequence, i.e. part of a contour, or a column span in a matrix.
974 class CV_EXPORTS Range
978 Range(int _start, int _end);
979 Range(const CvSlice& slice);
983 operator CvSlice() const;
988 /////////////////////////////// DataType ////////////////////////////////
991 Informative template class for OpenCV "scalars".
993 The class is specialized for each primitive numerical type supported by OpenCV (such as unsigned char or float),
994 as well as for more complex types, like cv::Complex<>, std::complex<>, cv::Vec<> etc.
995 The common property of all such types (called "scalars", do not confuse it with cv::Scalar_)
996 is that each of them is basically a tuple of numbers of the same type. Each "scalar" can be represented
997 by the depth id (CV_8U ... CV_64F) and the number of channels.
998 OpenCV matrices, 2D or nD, dense or sparse, can store "scalars",
999 as long as the number of channels does not exceed CV_CN_MAX.
1001 template<typename _Tp> class DataType
1004 typedef _Tp value_type;
1005 typedef value_type work_type;
1006 typedef value_type channel_type;
1007 typedef value_type vec_type;
1008 enum { generic_type = 1, depth = -1, channels = 1, fmt=0,
1009 type = CV_MAKETYPE(depth, channels) };
1012 template<> class DataType<bool>
1015 typedef bool value_type;
1016 typedef int work_type;
1017 typedef value_type channel_type;
1018 typedef value_type vec_type;
1019 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1020 fmt=DataDepth<channel_type>::fmt,
1021 type = CV_MAKETYPE(depth, channels) };
1024 template<> class DataType<uchar>
1027 typedef uchar value_type;
1028 typedef int work_type;
1029 typedef value_type channel_type;
1030 typedef value_type vec_type;
1031 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1032 fmt=DataDepth<channel_type>::fmt,
1033 type = CV_MAKETYPE(depth, channels) };
1036 template<> class DataType<schar>
1039 typedef schar value_type;
1040 typedef int work_type;
1041 typedef value_type channel_type;
1042 typedef value_type vec_type;
1043 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1044 fmt=DataDepth<channel_type>::fmt,
1045 type = CV_MAKETYPE(depth, channels) };
1048 template<> class DataType<char>
1051 typedef schar value_type;
1052 typedef int work_type;
1053 typedef value_type channel_type;
1054 typedef value_type vec_type;
1055 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1056 fmt=DataDepth<channel_type>::fmt,
1057 type = CV_MAKETYPE(depth, channels) };
1060 template<> class DataType<ushort>
1063 typedef ushort value_type;
1064 typedef int work_type;
1065 typedef value_type channel_type;
1066 typedef value_type vec_type;
1067 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1068 fmt=DataDepth<channel_type>::fmt,
1069 type = CV_MAKETYPE(depth, channels) };
1072 template<> class DataType<short>
1075 typedef short value_type;
1076 typedef int work_type;
1077 typedef value_type channel_type;
1078 typedef value_type vec_type;
1079 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1080 fmt=DataDepth<channel_type>::fmt,
1081 type = CV_MAKETYPE(depth, channels) };
1084 template<> class DataType<int>
1087 typedef int value_type;
1088 typedef value_type work_type;
1089 typedef value_type channel_type;
1090 typedef value_type vec_type;
1091 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1092 fmt=DataDepth<channel_type>::fmt,
1093 type = CV_MAKETYPE(depth, channels) };
1096 template<> class DataType<float>
1099 typedef float value_type;
1100 typedef value_type work_type;
1101 typedef value_type channel_type;
1102 typedef value_type vec_type;
1103 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1104 fmt=DataDepth<channel_type>::fmt,
1105 type = CV_MAKETYPE(depth, channels) };
1108 template<> class DataType<double>
1111 typedef double value_type;
1112 typedef value_type work_type;
1113 typedef value_type channel_type;
1114 typedef value_type vec_type;
1115 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1116 fmt=DataDepth<channel_type>::fmt,
1117 type = CV_MAKETYPE(depth, channels) };
1120 template<typename _Tp, int m, int n> class DataType<Matx<_Tp, m, n> >
1123 typedef Matx<_Tp, m, n> value_type;
1124 typedef Matx<typename DataType<_Tp>::work_type, m, n> work_type;
1125 typedef _Tp channel_type;
1126 typedef value_type vec_type;
1127 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = m*n,
1128 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1129 type = CV_MAKETYPE(depth, channels) };
1132 template<typename _Tp, int cn> class DataType<Vec<_Tp, cn> >
1135 typedef Vec<_Tp, cn> value_type;
1136 typedef Vec<typename DataType<_Tp>::work_type, cn> work_type;
1137 typedef _Tp channel_type;
1138 typedef value_type vec_type;
1139 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = cn,
1140 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1141 type = CV_MAKETYPE(depth, channels) };
1144 template<typename _Tp> class DataType<std::complex<_Tp> >
1147 typedef std::complex<_Tp> value_type;
1148 typedef value_type work_type;
1149 typedef _Tp channel_type;
1150 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1151 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1152 type = CV_MAKETYPE(depth, channels) };
1153 typedef Vec<channel_type, channels> vec_type;
1156 template<typename _Tp> class DataType<Complex<_Tp> >
1159 typedef Complex<_Tp> value_type;
1160 typedef value_type work_type;
1161 typedef _Tp channel_type;
1162 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1163 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1164 type = CV_MAKETYPE(depth, channels) };
1165 typedef Vec<channel_type, channels> vec_type;
1168 template<typename _Tp> class DataType<Point_<_Tp> >
1171 typedef Point_<_Tp> value_type;
1172 typedef Point_<typename DataType<_Tp>::work_type> work_type;
1173 typedef _Tp channel_type;
1174 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1175 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1176 type = CV_MAKETYPE(depth, channels) };
1177 typedef Vec<channel_type, channels> vec_type;
1180 template<typename _Tp> class DataType<Point3_<_Tp> >
1183 typedef Point3_<_Tp> value_type;
1184 typedef Point3_<typename DataType<_Tp>::work_type> work_type;
1185 typedef _Tp channel_type;
1186 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 3,
1187 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1188 type = CV_MAKETYPE(depth, channels) };
1189 typedef Vec<channel_type, channels> vec_type;
1192 template<typename _Tp> class DataType<Size_<_Tp> >
1195 typedef Size_<_Tp> value_type;
1196 typedef Size_<typename DataType<_Tp>::work_type> work_type;
1197 typedef _Tp channel_type;
1198 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1199 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1200 type = CV_MAKETYPE(depth, channels) };
1201 typedef Vec<channel_type, channels> vec_type;
1204 template<typename _Tp> class DataType<Rect_<_Tp> >
1207 typedef Rect_<_Tp> value_type;
1208 typedef Rect_<typename DataType<_Tp>::work_type> work_type;
1209 typedef _Tp channel_type;
1210 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 4,
1211 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1212 type = CV_MAKETYPE(depth, channels) };
1213 typedef Vec<channel_type, channels> vec_type;
1216 template<typename _Tp> class DataType<Scalar_<_Tp> >
1219 typedef Scalar_<_Tp> value_type;
1220 typedef Scalar_<typename DataType<_Tp>::work_type> work_type;
1221 typedef _Tp channel_type;
1222 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 4,
1223 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1224 type = CV_MAKETYPE(depth, channels) };
1225 typedef Vec<channel_type, channels> vec_type;
1228 template<> class DataType<Range>
1231 typedef Range value_type;
1232 typedef value_type work_type;
1233 typedef int channel_type;
1234 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1235 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1236 type = CV_MAKETYPE(depth, channels) };
1237 typedef Vec<channel_type, channels> vec_type;
1240 //////////////////// generic_type ref-counting pointer class for C/C++ objects ////////////////////////
1243 Smart pointer to dynamically allocated objects.
1245 This is template pointer-wrapping class that stores the associated reference counter along with the
1246 object pointer. The class is similar to std::smart_ptr<> from the recent addons to the C++ standard,
1247 but is shorter to write :) and self-contained (i.e. does add any dependency on the compiler or an external library).
1249 Basically, you can use "Ptr<MyObjectType> ptr" (or faster "const Ptr<MyObjectType>& ptr" for read-only access)
1250 everywhere instead of "MyObjectType* ptr", where MyObjectType is some C structure or a C++ class.
1251 To make it all work, you need to specialize Ptr<>::delete_obj(), like:
1254 template<> void Ptr<MyObjectType>::delete_obj() { call_destructor_func(obj); }
1257 \note{if MyObjectType is a C++ class with a destructor, you do not need to specialize delete_obj(),
1258 since the default implementation calls "delete obj;"}
1260 \note{Another good property of the class is that the operations on the reference counter are atomic,
1261 i.e. it is safe to use the class in multi-threaded applications}
1263 template<typename _Tp> class CV_EXPORTS Ptr
1266 //! empty constructor
1268 //! take ownership of the pointer. The associated reference counter is allocated and set to 1
1272 //! copy constructor. Copies the members and calls addref()
1273 Ptr(const Ptr& ptr);
1274 template<typename _Tp2> Ptr(const Ptr<_Tp2>& ptr);
1275 //! copy operator. Calls ptr.addref() and release() before copying the members
1276 Ptr& operator = (const Ptr& ptr);
1277 //! increments the reference counter
1279 //! decrements the reference counter. If it reaches 0, delete_obj() is called
1281 //! deletes the object. Override if needed
1283 //! returns true iff obj==NULL
1286 //! cast pointer to another type
1287 template<typename _Tp2> Ptr<_Tp2> ptr();
1288 template<typename _Tp2> const Ptr<_Tp2> ptr() const;
1290 //! helper operators making "Ptr<T> ptr" use very similar to "T* ptr".
1291 _Tp* operator -> ();
1292 const _Tp* operator -> () const;
1295 operator const _Tp*() const;
1297 _Tp* obj; //< the object pointer.
1298 int* refcount; //< the associated reference counter
1302 //////////////////////// Input/Output Array Arguments /////////////////////////////////
1305 Proxy datatype for passing Mat's and vector<>'s as input parameters
1307 class CV_EXPORTS _InputArray
1312 FIXED_TYPE = 0x8000 << KIND_SHIFT,
1313 FIXED_SIZE = 0x4000 << KIND_SHIFT,
1314 KIND_MASK = ~(FIXED_TYPE|FIXED_SIZE) - (1 << KIND_SHIFT) + 1,
1316 NONE = 0 << KIND_SHIFT,
1317 MAT = 1 << KIND_SHIFT,
1318 MATX = 2 << KIND_SHIFT,
1319 STD_VECTOR = 3 << KIND_SHIFT,
1320 STD_VECTOR_VECTOR = 4 << KIND_SHIFT,
1321 STD_VECTOR_MAT = 5 << KIND_SHIFT,
1322 EXPR = 6 << KIND_SHIFT,
1323 OPENGL_BUFFER = 7 << KIND_SHIFT,
1324 OPENGL_TEXTURE = 8 << KIND_SHIFT,
1325 GPU_MAT = 9 << KIND_SHIFT
1329 _InputArray(const Mat& m);
1330 _InputArray(const MatExpr& expr);
1331 template<typename _Tp> _InputArray(const _Tp* vec, int n);
1332 template<typename _Tp> _InputArray(const vector<_Tp>& vec);
1333 template<typename _Tp> _InputArray(const vector<vector<_Tp> >& vec);
1334 _InputArray(const vector<Mat>& vec);
1335 template<typename _Tp> _InputArray(const vector<Mat_<_Tp> >& vec);
1336 template<typename _Tp> _InputArray(const Mat_<_Tp>& m);
1337 template<typename _Tp, int m, int n> _InputArray(const Matx<_Tp, m, n>& matx);
1338 _InputArray(const Scalar& s);
1339 _InputArray(const double& val);
1341 _InputArray(const GlBuffer& buf);
1342 _InputArray(const GlTexture& tex);
1344 _InputArray(const gpu::GpuMat& d_mat);
1345 _InputArray(const ogl::Buffer& buf);
1346 _InputArray(const ogl::Texture2D& tex);
1348 virtual Mat getMat(int i=-1) const;
1349 virtual void getMatVector(vector<Mat>& mv) const;
1351 virtual GlBuffer getGlBuffer() const;
1352 virtual GlTexture getGlTexture() const;
1354 virtual gpu::GpuMat getGpuMat() const;
1355 /*virtual*/ ogl::Buffer getOGlBuffer() const;
1356 /*virtual*/ ogl::Texture2D getOGlTexture2D() const;
1358 virtual int kind() const;
1359 virtual Size size(int i=-1) const;
1360 virtual size_t total(int i=-1) const;
1361 virtual int type(int i=-1) const;
1362 virtual int depth(int i=-1) const;
1363 virtual int channels(int i=-1) const;
1364 virtual bool empty() const;
1366 #ifdef OPENCV_CAN_BREAK_BINARY_COMPATIBILITY
1367 virtual ~_InputArray();
1378 DEPTH_MASK_8U = 1 << CV_8U,
1379 DEPTH_MASK_8S = 1 << CV_8S,
1380 DEPTH_MASK_16U = 1 << CV_16U,
1381 DEPTH_MASK_16S = 1 << CV_16S,
1382 DEPTH_MASK_32S = 1 << CV_32S,
1383 DEPTH_MASK_32F = 1 << CV_32F,
1384 DEPTH_MASK_64F = 1 << CV_64F,
1385 DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1,
1386 DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S,
1387 DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F
1392 Proxy datatype for passing Mat's and vector<>'s as input parameters
1394 class CV_EXPORTS _OutputArray : public _InputArray
1399 _OutputArray(Mat& m);
1400 template<typename _Tp> _OutputArray(vector<_Tp>& vec);
1401 template<typename _Tp> _OutputArray(vector<vector<_Tp> >& vec);
1402 _OutputArray(vector<Mat>& vec);
1403 template<typename _Tp> _OutputArray(vector<Mat_<_Tp> >& vec);
1404 template<typename _Tp> _OutputArray(Mat_<_Tp>& m);
1405 template<typename _Tp, int m, int n> _OutputArray(Matx<_Tp, m, n>& matx);
1406 template<typename _Tp> _OutputArray(_Tp* vec, int n);
1407 _OutputArray(gpu::GpuMat& d_mat);
1408 _OutputArray(ogl::Buffer& buf);
1409 _OutputArray(ogl::Texture2D& tex);
1411 _OutputArray(const Mat& m);
1412 template<typename _Tp> _OutputArray(const vector<_Tp>& vec);
1413 template<typename _Tp> _OutputArray(const vector<vector<_Tp> >& vec);
1414 _OutputArray(const vector<Mat>& vec);
1415 template<typename _Tp> _OutputArray(const vector<Mat_<_Tp> >& vec);
1416 template<typename _Tp> _OutputArray(const Mat_<_Tp>& m);
1417 template<typename _Tp, int m, int n> _OutputArray(const Matx<_Tp, m, n>& matx);
1418 template<typename _Tp> _OutputArray(const _Tp* vec, int n);
1419 _OutputArray(const gpu::GpuMat& d_mat);
1420 _OutputArray(const ogl::Buffer& buf);
1421 _OutputArray(const ogl::Texture2D& tex);
1423 virtual bool fixedSize() const;
1424 virtual bool fixedType() const;
1425 virtual bool needed() const;
1426 virtual Mat& getMatRef(int i=-1) const;
1427 /*virtual*/ gpu::GpuMat& getGpuMatRef() const;
1428 /*virtual*/ ogl::Buffer& getOGlBufferRef() const;
1429 /*virtual*/ ogl::Texture2D& getOGlTexture2DRef() const;
1430 virtual void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
1431 virtual void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
1432 virtual void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
1433 virtual void release() const;
1434 virtual void clear() const;
1436 #ifdef OPENCV_CAN_BREAK_BINARY_COMPATIBILITY
1437 virtual ~_OutputArray();
1441 typedef const _InputArray& InputArray;
1442 typedef InputArray InputArrayOfArrays;
1443 typedef const _OutputArray& OutputArray;
1444 typedef OutputArray OutputArrayOfArrays;
1445 typedef OutputArray InputOutputArray;
1446 typedef OutputArray InputOutputArrayOfArrays;
1448 CV_EXPORTS OutputArray noArray();
1450 /////////////////////////////////////// Mat ///////////////////////////////////////////
1452 enum { MAGIC_MASK=0xFFFF0000, TYPE_MASK=0x00000FFF, DEPTH_MASK=7 };
1454 static inline size_t getElemSize(int type) { return CV_ELEM_SIZE(type); }
1457 Custom array allocator
1460 class CV_EXPORTS MatAllocator
1464 virtual ~MatAllocator() {}
1465 virtual void allocate(int dims, const int* sizes, int type, int*& refcount,
1466 uchar*& datastart, uchar*& data, size_t* step) = 0;
1467 virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0;
1471 The n-dimensional matrix class.
1473 The class represents an n-dimensional dense numerical array that can act as
1474 a matrix, image, optical flow map, 3-focal tensor etc.
1475 It is very similar to CvMat and CvMatND types from earlier versions of OpenCV,
1476 and similarly to those types, the matrix can be multi-channel. It also fully supports ROI mechanism.
1478 There are many different ways to create cv::Mat object. Here are the some popular ones:
1480 <li> using cv::Mat::create(nrows, ncols, type) method or
1481 the similar constructor cv::Mat::Mat(nrows, ncols, type[, fill_value]) constructor.
1482 A new matrix of the specified size and specifed type will be allocated.
1483 "type" has the same meaning as in cvCreateMat function,
1484 e.g. CV_8UC1 means 8-bit single-channel matrix, CV_32FC2 means 2-channel (i.e. complex)
1485 floating-point matrix etc:
1488 // make 7x7 complex matrix filled with 1+3j.
1489 cv::Mat M(7,7,CV_32FC2,Scalar(1,3));
1490 // and now turn M to 100x60 15-channel 8-bit matrix.
1491 // The old content will be deallocated
1492 M.create(100,60,CV_8UC(15));
1495 As noted in the introduction of this chapter, Mat::create()
1496 will only allocate a new matrix when the current matrix dimensionality
1497 or type are different from the specified.
1499 <li> by using a copy constructor or assignment operator, where on the right side it can
1500 be a matrix or expression, see below. Again, as noted in the introduction,
1501 matrix assignment is O(1) operation because it only copies the header
1502 and increases the reference counter. cv::Mat::clone() method can be used to get a full
1503 (a.k.a. deep) copy of the matrix when you need it.
1505 <li> by constructing a header for a part of another matrix. It can be a single row, single column,
1506 several rows, several columns, rectangular region in the matrix (called a minor in algebra) or
1507 a diagonal. Such operations are also O(1), because the new header will reference the same data.
1508 You can actually modify a part of the matrix using this feature, e.g.
1511 // add 5-th row, multiplied by 3 to the 3rd row
1512 M.row(3) = M.row(3) + M.row(5)*3;
1514 // now copy 7-th column to the 1-st column
1515 // M.col(1) = M.col(7); // this will not work
1517 M.col(7).copyTo(M1);
1519 // create new 320x240 image
1520 cv::Mat img(Size(320,240),CV_8UC3);
1522 cv::Mat roi(img, Rect(10,10,100,100));
1523 // fill the ROI with (0,255,0) (which is green in RGB space);
1524 // the original 320x240 image will be modified
1525 roi = Scalar(0,255,0);
1528 Thanks to the additional cv::Mat::datastart and cv::Mat::dataend members, it is possible to
1529 compute the relative sub-matrix position in the main "container" matrix using cv::Mat::locateROI():
1532 Mat A = Mat::eye(10, 10, CV_32S);
1533 // extracts A columns, 1 (inclusive) to 3 (exclusive).
1534 Mat B = A(Range::all(), Range(1, 3));
1535 // extracts B rows, 5 (inclusive) to 9 (exclusive).
1536 // that is, C ~ A(Range(5, 9), Range(1, 3))
1537 Mat C = B(Range(5, 9), Range::all());
1538 Size size; Point ofs;
1539 C.locateROI(size, ofs);
1540 // size will be (width=10,height=10) and the ofs will be (x=1, y=5)
1543 As in the case of whole matrices, if you need a deep copy, use cv::Mat::clone() method
1544 of the extracted sub-matrices.
1546 <li> by making a header for user-allocated-data. It can be useful for
1548 <li> processing "foreign" data using OpenCV (e.g. when you implement
1549 a DirectShow filter or a processing module for gstreamer etc.), e.g.
1552 void process_video_frame(const unsigned char* pixels,
1553 int width, int height, int step)
1555 cv::Mat img(height, width, CV_8UC3, pixels, step);
1556 cv::GaussianBlur(img, img, cv::Size(7,7), 1.5, 1.5);
1560 <li> for quick initialization of small matrices and/or super-fast element access
1563 double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
1564 cv::Mat M = cv::Mat(3, 3, CV_64F, m).inv();
1568 partial yet very common cases of this "user-allocated data" case are conversions
1569 from CvMat and IplImage to cv::Mat. For this purpose there are special constructors
1570 taking pointers to CvMat or IplImage and the optional
1571 flag indicating whether to copy the data or not.
1573 Backward conversion from cv::Mat to CvMat or IplImage is provided via cast operators
1574 cv::Mat::operator CvMat() an cv::Mat::operator IplImage().
1575 The operators do not copy the data.
1579 IplImage* img = cvLoadImage("greatwave.jpg", 1);
1580 Mat mtx(img); // convert IplImage* -> cv::Mat
1581 CvMat oldmat = mtx; // convert cv::Mat -> CvMat
1582 CV_Assert(oldmat.cols == img->width && oldmat.rows == img->height &&
1583 oldmat.data.ptr == (uchar*)img->imageData && oldmat.step == img->widthStep);
1586 <li> by using MATLAB-style matrix initializers, cv::Mat::zeros(), cv::Mat::ones(), cv::Mat::eye(), e.g.:
1589 // create a double-precision identity martix and add it to M.
1590 M += Mat::eye(M.rows, M.cols, CV_64F);
1593 <li> by using comma-separated initializer:
1596 // create 3x3 double-precision identity matrix
1597 Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
1600 here we first call constructor of cv::Mat_ class (that we describe further) with the proper matrix,
1601 and then we just put "<<" operator followed by comma-separated values that can be constants,
1602 variables, expressions etc. Also, note the extra parentheses that are needed to avoid compiler errors.
1606 Once matrix is created, it will be automatically managed by using reference-counting mechanism
1607 (unless the matrix header is built on top of user-allocated data,
1608 in which case you should handle the data by yourself).
1609 The matrix data will be deallocated when no one points to it;
1610 if you want to release the data pointed by a matrix header before the matrix destructor is called,
1611 use cv::Mat::release().
1613 The next important thing to learn about the matrix class is element access. Here is how the matrix is stored.
1614 The elements are stored in row-major order (row by row). The cv::Mat::data member points to the first element of the first row,
1615 cv::Mat::rows contains the number of matrix rows and cv::Mat::cols - the number of matrix columns. There is yet another member,
1616 cv::Mat::step that is used to actually compute address of a matrix element. cv::Mat::step is needed because the matrix can be
1617 a part of another matrix or because there can some padding space in the end of each row for a proper alignment.
1621 Given these parameters, address of the matrix element M_{ij} is computed as following:
1623 addr(M_{ij})=M.data + M.step*i + j*M.elemSize()
1625 if you know the matrix element type, e.g. it is float, then you can use cv::Mat::at() method:
1627 addr(M_{ij})=&M.at<float>(i,j)
1629 (where & is used to convert the reference returned by cv::Mat::at() to a pointer).
1630 if you need to process a whole row of matrix, the most efficient way is to get
1631 the pointer to the row first, and then just use plain C operator []:
1634 // compute sum of positive matrix elements
1635 // (assuming that M is double-precision matrix)
1637 for(int i = 0; i < M.rows; i++)
1639 const double* Mi = M.ptr<double>(i);
1640 for(int j = 0; j < M.cols; j++)
1641 sum += std::max(Mi[j], 0.);
1645 Some operations, like the above one, do not actually depend on the matrix shape,
1646 they just process elements of a matrix one by one (or elements from multiple matrices
1647 that are sitting in the same place, e.g. matrix addition). Such operations are called
1648 element-wise and it makes sense to check whether all the input/output matrices are continuous,
1649 i.e. have no gaps in the end of each row, and if yes, process them as a single long row:
1652 // compute sum of positive matrix elements, optimized variant
1654 int cols = M.cols, rows = M.rows;
1655 if(M.isContinuous())
1660 for(int i = 0; i < rows; i++)
1662 const double* Mi = M.ptr<double>(i);
1663 for(int j = 0; j < cols; j++)
1664 sum += std::max(Mi[j], 0.);
1667 in the case of continuous matrix the outer loop body will be executed just once,
1668 so the overhead will be smaller, which will be especially noticeable in the case of small matrices.
1670 Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:
1672 // compute sum of positive matrix elements, iterator-based variant
1674 MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
1675 for(; it != it_end; ++it)
1676 sum += std::max(*it, 0.);
1679 The matrix iterators are random-access iterators, so they can be passed
1680 to any STL algorithm, including std::sort().
1682 class CV_EXPORTS Mat
1685 //! default constructor
1687 //! constructs 2D matrix of the specified size and type
1688 // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
1689 Mat(int rows, int cols, int type);
1690 Mat(Size size, int type);
1691 //! constucts 2D matrix and fills it with the specified value _s.
1692 Mat(int rows, int cols, int type, const Scalar& s);
1693 Mat(Size size, int type, const Scalar& s);
1695 //! constructs n-dimensional matrix
1696 Mat(int ndims, const int* sizes, int type);
1697 Mat(int ndims, const int* sizes, int type, const Scalar& s);
1699 //! copy constructor
1701 //! constructor for matrix headers pointing to user-allocated data
1702 Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP);
1703 Mat(Size size, int type, void* data, size_t step=AUTO_STEP);
1704 Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0);
1706 //! creates a matrix header for a part of the bigger matrix
1707 Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all());
1708 Mat(const Mat& m, const Rect& roi);
1709 Mat(const Mat& m, const Range* ranges);
1710 //! converts old-style CvMat to the new matrix; the data is not copied by default
1711 Mat(const CvMat* m, bool copyData=false);
1712 //! converts old-style CvMatND to the new matrix; the data is not copied by default
1713 Mat(const CvMatND* m, bool copyData=false);
1714 //! converts old-style IplImage to the new matrix; the data is not copied by default
1715 Mat(const IplImage* img, bool copyData=false);
1716 //! builds matrix from std::vector with or without copying the data
1717 template<typename _Tp> explicit Mat(const vector<_Tp>& vec, bool copyData=false);
1718 //! builds matrix from cv::Vec; the data is copied by default
1719 template<typename _Tp, int n> explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true);
1720 //! builds matrix from cv::Matx; the data is copied by default
1721 template<typename _Tp, int m, int n> explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
1722 //! builds matrix from a 2D point
1723 template<typename _Tp> explicit Mat(const Point_<_Tp>& pt, bool copyData=true);
1724 //! builds matrix from a 3D point
1725 template<typename _Tp> explicit Mat(const Point3_<_Tp>& pt, bool copyData=true);
1726 //! builds matrix from comma initializer
1727 template<typename _Tp> explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer);
1729 //! download data from GpuMat
1730 explicit Mat(const gpu::GpuMat& m);
1732 //! destructor - calls release()
1734 //! assignment operators
1735 Mat& operator = (const Mat& m);
1736 Mat& operator = (const MatExpr& expr);
1738 //! returns a new matrix header for the specified row
1739 Mat row(int y) const;
1740 //! returns a new matrix header for the specified column
1741 Mat col(int x) const;
1742 //! ... for the specified row span
1743 Mat rowRange(int startrow, int endrow) const;
1744 Mat rowRange(const Range& r) const;
1745 //! ... for the specified column span
1746 Mat colRange(int startcol, int endcol) const;
1747 Mat colRange(const Range& r) const;
1748 //! ... for the specified diagonal
1749 // (d=0 - the main diagonal,
1750 // >0 - a diagonal from the lower half,
1751 // <0 - a diagonal from the upper half)
1752 Mat diag(int d=0) const;
1753 //! constructs a square diagonal matrix which main diagonal is vector "d"
1754 static Mat diag(const Mat& d);
1756 //! returns deep copy of the matrix, i.e. the data is copied
1758 //! copies the matrix content to "m".
1759 // It calls m.create(this->size(), this->type()).
1760 void copyTo( OutputArray m ) const;
1761 //! copies those matrix elements to "m" that are marked with non-zero mask elements.
1762 void copyTo( OutputArray m, InputArray mask ) const;
1763 //! converts matrix to another datatype with optional scalng. See cvConvertScale.
1764 void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
1766 void assignTo( Mat& m, int type=-1 ) const;
1768 //! sets every matrix element to s
1769 Mat& operator = (const Scalar& s);
1770 //! sets some of the matrix elements to s, according to the mask
1771 Mat& setTo(InputArray value, InputArray mask=noArray());
1772 //! creates alternative matrix header for the same data, with different
1773 // number of channels and/or different number of rows. see cvReshape.
1774 Mat reshape(int cn, int rows=0) const;
1775 Mat reshape(int cn, int newndims, const int* newsz) const;
1777 //! matrix transposition by means of matrix expressions
1779 //! matrix inversion by means of matrix expressions
1780 MatExpr inv(int method=DECOMP_LU) const;
1781 //! per-element matrix multiplication by means of matrix expressions
1782 MatExpr mul(InputArray m, double scale=1) const;
1784 //! computes cross-product of 2 3D vectors
1785 Mat cross(InputArray m) const;
1786 //! computes dot-product
1787 double dot(InputArray m) const;
1789 //! Matlab-style matrix initialization
1790 static MatExpr zeros(int rows, int cols, int type);
1791 static MatExpr zeros(Size size, int type);
1792 static MatExpr zeros(int ndims, const int* sz, int type);
1793 static MatExpr ones(int rows, int cols, int type);
1794 static MatExpr ones(Size size, int type);
1795 static MatExpr ones(int ndims, const int* sz, int type);
1796 static MatExpr eye(int rows, int cols, int type);
1797 static MatExpr eye(Size size, int type);
1799 //! allocates new matrix data unless the matrix already has specified size and type.
1800 // previous data is unreferenced if needed.
1801 void create(int rows, int cols, int type);
1802 void create(Size size, int type);
1803 void create(int ndims, const int* sizes, int type);
1805 //! increases the reference counter; use with care to avoid memleaks
1807 //! decreases reference counter;
1808 // deallocates the data when reference counter reaches 0.
1811 //! deallocates the matrix data
1813 //! internal use function; properly re-allocates _size, _step arrays
1814 void copySize(const Mat& m);
1816 //! reserves enough space to fit sz hyper-planes
1817 void reserve(size_t sz);
1818 //! resizes matrix to the specified number of hyper-planes
1819 void resize(size_t sz);
1820 //! resizes matrix to the specified number of hyper-planes; initializes the newly added elements
1821 void resize(size_t sz, const Scalar& s);
1822 //! internal function
1823 void push_back_(const void* elem);
1824 //! adds element to the end of 1d matrix (or possibly multiple elements when _Tp=Mat)
1825 template<typename _Tp> void push_back(const _Tp& elem);
1826 template<typename _Tp> void push_back(const Mat_<_Tp>& elem);
1827 void push_back(const Mat& m);
1828 //! removes several hyper-planes from bottom of the matrix
1829 void pop_back(size_t nelems=1);
1831 //! locates matrix header within a parent matrix. See below
1832 void locateROI( Size& wholeSize, Point& ofs ) const;
1833 //! moves/resizes the current matrix ROI inside the parent matrix.
1834 Mat& adjustROI( int dtop, int dbottom, int dleft, int dright );
1835 //! extracts a rectangular sub-matrix
1836 // (this is a generalized form of row, rowRange etc.)
1837 Mat operator()( Range rowRange, Range colRange ) const;
1838 Mat operator()( const Rect& roi ) const;
1839 Mat operator()( const Range* ranges ) const;
1841 //! converts header to CvMat; no data is copied
1842 operator CvMat() const;
1843 //! converts header to CvMatND; no data is copied
1844 operator CvMatND() const;
1845 //! converts header to IplImage; no data is copied
1846 operator IplImage() const;
1848 template<typename _Tp> operator vector<_Tp>() const;
1849 template<typename _Tp, int n> operator Vec<_Tp, n>() const;
1850 template<typename _Tp, int m, int n> operator Matx<_Tp, m, n>() const;
1852 //! returns true iff the matrix data is continuous
1853 // (i.e. when there are no gaps between successive rows).
1854 // similar to CV_IS_MAT_CONT(cvmat->type)
1855 bool isContinuous() const;
1857 //! returns true if the matrix is a submatrix of another matrix
1858 bool isSubmatrix() const;
1860 //! returns element size in bytes,
1861 // similar to CV_ELEM_SIZE(cvmat->type)
1862 size_t elemSize() const;
1863 //! returns the size of element channel in bytes.
1864 size_t elemSize1() const;
1865 //! returns element type, similar to CV_MAT_TYPE(cvmat->type)
1867 //! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
1869 //! returns element type, similar to CV_MAT_CN(cvmat->type)
1870 int channels() const;
1871 //! returns step/elemSize1()
1872 size_t step1(int i=0) const;
1873 //! returns true if matrix data is NULL
1875 //! returns the total number of matrix elements
1876 size_t total() const;
1878 //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
1879 int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
1881 //! returns pointer to i0-th submatrix along the dimension #0
1882 uchar* ptr(int i0=0);
1883 const uchar* ptr(int i0=0) const;
1885 //! returns pointer to (i0,i1) submatrix along the dimensions #0 and #1
1886 uchar* ptr(int i0, int i1);
1887 const uchar* ptr(int i0, int i1) const;
1889 //! returns pointer to (i0,i1,i3) submatrix along the dimensions #0, #1, #2
1890 uchar* ptr(int i0, int i1, int i2);
1891 const uchar* ptr(int i0, int i1, int i2) const;
1893 //! returns pointer to the matrix element
1894 uchar* ptr(const int* idx);
1895 //! returns read-only pointer to the matrix element
1896 const uchar* ptr(const int* idx) const;
1898 template<int n> uchar* ptr(const Vec<int, n>& idx);
1899 template<int n> const uchar* ptr(const Vec<int, n>& idx) const;
1901 //! template version of the above method
1902 template<typename _Tp> _Tp* ptr(int i0=0);
1903 template<typename _Tp> const _Tp* ptr(int i0=0) const;
1905 template<typename _Tp> _Tp* ptr(int i0, int i1);
1906 template<typename _Tp> const _Tp* ptr(int i0, int i1) const;
1908 template<typename _Tp> _Tp* ptr(int i0, int i1, int i2);
1909 template<typename _Tp> const _Tp* ptr(int i0, int i1, int i2) const;
1911 template<typename _Tp> _Tp* ptr(const int* idx);
1912 template<typename _Tp> const _Tp* ptr(const int* idx) const;
1914 template<typename _Tp, int n> _Tp* ptr(const Vec<int, n>& idx);
1915 template<typename _Tp, int n> const _Tp* ptr(const Vec<int, n>& idx) const;
1917 //! the same as above, with the pointer dereferencing
1918 template<typename _Tp> _Tp& at(int i0=0);
1919 template<typename _Tp> const _Tp& at(int i0=0) const;
1921 template<typename _Tp> _Tp& at(int i0, int i1);
1922 template<typename _Tp> const _Tp& at(int i0, int i1) const;
1924 template<typename _Tp> _Tp& at(int i0, int i1, int i2);
1925 template<typename _Tp> const _Tp& at(int i0, int i1, int i2) const;
1927 template<typename _Tp> _Tp& at(const int* idx);
1928 template<typename _Tp> const _Tp& at(const int* idx) const;
1930 template<typename _Tp, int n> _Tp& at(const Vec<int, n>& idx);
1931 template<typename _Tp, int n> const _Tp& at(const Vec<int, n>& idx) const;
1933 //! special versions for 2D arrays (especially convenient for referencing image pixels)
1934 template<typename _Tp> _Tp& at(Point pt);
1935 template<typename _Tp> const _Tp& at(Point pt) const;
1937 //! template methods for iteration over matrix elements.
1938 // the iterators take care of skipping gaps in the end of rows (if any)
1939 template<typename _Tp> MatIterator_<_Tp> begin();
1940 template<typename _Tp> MatIterator_<_Tp> end();
1941 template<typename _Tp> MatConstIterator_<_Tp> begin() const;
1942 template<typename _Tp> MatConstIterator_<_Tp> end() const;
1944 enum { MAGIC_VAL=0x42FF0000, AUTO_STEP=0, CONTINUOUS_FLAG=CV_MAT_CONT_FLAG, SUBMATRIX_FLAG=CV_SUBMAT_FLAG };
1946 /*! includes several bit-fields:
1947 - the magic signature
1950 - number of channels
1953 //! the matrix dimensionality, >= 2
1955 //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
1957 //! pointer to the data
1960 //! pointer to the reference counter;
1961 // when matrix points to user-allocated data, the pointer is NULL
1964 //! helper fields used in locateROI and adjustROI
1969 //! custom allocator
1970 MatAllocator* allocator;
1972 struct CV_EXPORTS MSize
1975 Size operator()() const;
1976 const int& operator[](int i) const;
1977 int& operator[](int i);
1978 operator const int*() const;
1979 bool operator == (const MSize& sz) const;
1980 bool operator != (const MSize& sz) const;
1985 struct CV_EXPORTS MStep
1989 const size_t& operator[](int i) const;
1990 size_t& operator[](int i);
1991 operator size_t() const;
1992 MStep& operator = (size_t s);
1997 MStep& operator = (const MStep&);
2009 Random Number Generator
2011 The class implements RNG using Multiply-with-Carry algorithm
2013 class CV_EXPORTS RNG
2016 enum { UNIFORM=0, NORMAL=1 };
2020 //! updates the state and returns the next 32-bit unsigned integer random number
2027 operator unsigned();
2028 //! returns a random integer sampled uniformly from [0, N).
2029 unsigned operator ()(unsigned N);
2030 unsigned operator ()();
2034 //! returns uniformly distributed integer random number from [a,b) range
2035 int uniform(int a, int b);
2036 //! returns uniformly distributed floating-point random number from [a,b) range
2037 float uniform(float a, float b);
2038 //! returns uniformly distributed double-precision floating-point random number from [a,b) range
2039 double uniform(double a, double b);
2040 void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange=false );
2041 //! returns Gaussian random variate with mean zero.
2042 double gaussian(double sigma);
2048 Random Number Generator - MT
2050 The class implements RNG using the Mersenne Twister algorithm
2052 class CV_EXPORTS RNG_MT19937
2056 RNG_MT19937(unsigned s);
2057 void seed(unsigned s);
2062 operator unsigned();
2066 unsigned operator ()(unsigned N);
2067 unsigned operator ()();
2069 //! returns uniformly distributed integer random number from [a,b) range
2070 int uniform(int a, int b);
2071 //! returns uniformly distributed floating-point random number from [a,b) range
2072 float uniform(float a, float b);
2073 //! returns uniformly distributed double-precision floating-point random number from [a,b) range
2074 double uniform(double a, double b);
2077 enum PeriodParameters {N = 624, M = 397};
2083 Termination criteria in iterative algorithms
2085 class CV_EXPORTS TermCriteria
2090 COUNT=1, //!< the maximum number of iterations or elements to compute
2091 MAX_ITER=COUNT, //!< ditto
2092 EPS=2 //!< the desired accuracy or change in parameters at which the iterative algorithm stops
2095 //! default constructor
2097 //! full constructor
2098 TermCriteria(int type, int maxCount, double epsilon);
2099 //! conversion from CvTermCriteria
2100 TermCriteria(const CvTermCriteria& criteria);
2101 //! conversion to CvTermCriteria
2102 operator CvTermCriteria() const;
2104 int type; //!< the type of termination criteria: COUNT, EPS or COUNT + EPS
2105 int maxCount; // the maximum number of iterations/elements
2106 double epsilon; // the desired accuracy
2110 typedef void (*BinaryFunc)(const uchar* src1, size_t step1,
2111 const uchar* src2, size_t step2,
2112 uchar* dst, size_t step, Size sz,
2115 CV_EXPORTS BinaryFunc getConvertFunc(int sdepth, int ddepth);
2116 CV_EXPORTS BinaryFunc getConvertScaleFunc(int sdepth, int ddepth);
2117 CV_EXPORTS BinaryFunc getCopyMaskFunc(size_t esz);
2119 //! swaps two matrices
2120 CV_EXPORTS void swap(Mat& a, Mat& b);
2122 //! converts array (CvMat or IplImage) to cv::Mat
2123 CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false,
2124 bool allowND=true, int coiMode=0);
2125 //! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it.
2126 CV_EXPORTS void extractImageCOI(const CvArr* arr, OutputArray coiimg, int coi=-1);
2127 //! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage
2128 CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1);
2130 //! adds one matrix to another (dst = src1 + src2)
2131 CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst,
2132 InputArray mask=noArray(), int dtype=-1);
2133 //! subtracts one matrix from another (dst = src1 - src2)
2134 CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst,
2135 InputArray mask=noArray(), int dtype=-1);
2137 //! computes element-wise weighted product of the two arrays (dst = scale*src1*src2)
2138 CV_EXPORTS_W void multiply(InputArray src1, InputArray src2,
2139 OutputArray dst, double scale=1, int dtype=-1);
2141 //! computes element-wise weighted quotient of the two arrays (dst = scale*src1/src2)
2142 CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst,
2143 double scale=1, int dtype=-1);
2145 //! computes element-wise weighted reciprocal of an array (dst = scale/src2)
2146 CV_EXPORTS_W void divide(double scale, InputArray src2,
2147 OutputArray dst, int dtype=-1);
2149 //! adds scaled array to another one (dst = alpha*src1 + src2)
2150 CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst);
2152 //! computes weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma)
2153 CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2,
2154 double beta, double gamma, OutputArray dst, int dtype=-1);
2156 //! 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)
2157 CV_EXPORTS_W void convertScaleAbs(InputArray src, OutputArray dst,
2158 double alpha=1, double beta=0);
2159 //! transforms array of numbers using a lookup table: dst(i)=lut(src(i))
2160 CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst,
2161 int interpolation=0);
2163 //! computes sum of array elements
2164 CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src);
2165 //! computes the number of nonzero array elements
2166 CV_EXPORTS_W int countNonZero( InputArray src );
2167 //! returns the list of locations of non-zero pixels
2168 CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx );
2170 //! computes mean value of selected array elements
2171 CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask=noArray());
2172 //! computes mean value and standard deviation of all or selected array elements
2173 CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev,
2174 InputArray mask=noArray());
2175 //! computes norm of the selected array part
2176 CV_EXPORTS_W double norm(InputArray src1, int normType=NORM_L2, InputArray mask=noArray());
2177 //! computes norm of selected part of the difference between two arrays
2178 CV_EXPORTS_W double norm(InputArray src1, InputArray src2,
2179 int normType=NORM_L2, InputArray mask=noArray());
2181 //! naive nearest neighbor finder
2182 CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2,
2183 OutputArray dist, int dtype, OutputArray nidx,
2184 int normType=NORM_L2, int K=0,
2185 InputArray mask=noArray(), int update=0,
2186 bool crosscheck=false);
2188 //! 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
2189 CV_EXPORTS_W void normalize( InputArray src, OutputArray dst, double alpha=1, double beta=0,
2190 int norm_type=NORM_L2, int dtype=-1, InputArray mask=noArray());
2192 //! finds global minimum and maximum array elements and returns their values and their locations
2193 CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal,
2194 CV_OUT double* maxVal=0, CV_OUT Point* minLoc=0,
2195 CV_OUT Point* maxLoc=0, InputArray mask=noArray());
2196 CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal,
2197 int* minIdx=0, int* maxIdx=0, InputArray mask=noArray());
2199 //! transforms 2D matrix to 1D row or column vector by taking sum, minimum, maximum or mean value over all the rows
2200 CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype=-1);
2202 //! makes multi-channel array out of several single-channel arrays
2203 CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst);
2204 CV_EXPORTS void merge(const vector<Mat>& mv, OutputArray dst );
2206 //! makes multi-channel array out of several single-channel arrays
2207 CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst);
2209 //! copies each plane of a multi-channel array to a dedicated array
2210 CV_EXPORTS void split(const Mat& src, Mat* mvbegin);
2211 CV_EXPORTS void split(const Mat& m, vector<Mat>& mv );
2213 //! copies each plane of a multi-channel array to a dedicated array
2214 CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv);
2216 //! copies selected channels from the input arrays to the selected channels of the output arrays
2217 CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts,
2218 const int* fromTo, size_t npairs);
2219 CV_EXPORTS void mixChannels(const vector<Mat>& src, vector<Mat>& dst,
2220 const int* fromTo, size_t npairs);
2221 CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputArrayOfArrays dst,
2222 const vector<int>& fromTo);
2224 //! extracts a single channel from src (coi is 0-based index)
2225 CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi);
2227 //! inserts a single channel to dst (coi is 0-based index)
2228 CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi);
2230 //! reverses the order of the rows, columns or both in a matrix
2231 CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode);
2233 //! replicates the input matrix the specified number of times in the horizontal and/or vertical direction
2234 CV_EXPORTS_W void repeat(InputArray src, int ny, int nx, OutputArray dst);
2235 CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx);
2237 CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, OutputArray dst);
2238 CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst);
2239 CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst);
2241 CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst);
2242 CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst);
2243 CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst);
2245 //! computes bitwise conjunction of the two arrays (dst = src1 & src2)
2246 CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2,
2247 OutputArray dst, InputArray mask=noArray());
2248 //! computes bitwise disjunction of the two arrays (dst = src1 | src2)
2249 CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2,
2250 OutputArray dst, InputArray mask=noArray());
2251 //! computes bitwise exclusive-or of the two arrays (dst = src1 ^ src2)
2252 CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2,
2253 OutputArray dst, InputArray mask=noArray());
2254 //! inverts each bit of array (dst = ~src)
2255 CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst,
2256 InputArray mask=noArray());
2257 //! computes element-wise absolute difference of two arrays (dst = abs(src1 - src2))
2258 CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst);
2259 //! set mask elements for those array elements which are within the element-specific bounding box (dst = lowerb <= src && src < upperb)
2260 CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb,
2261 InputArray upperb, OutputArray dst);
2262 //! compares elements of two arrays (dst = src1 <cmpop> src2)
2263 CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop);
2264 //! computes per-element minimum of two arrays (dst = min(src1, src2))
2265 CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst);
2266 //! computes per-element maximum of two arrays (dst = max(src1, src2))
2267 CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst);
2269 //! computes per-element minimum of two arrays (dst = min(src1, src2))
2270 CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst);
2271 //! computes per-element minimum of array and scalar (dst = min(src1, src2))
2272 CV_EXPORTS void min(const Mat& src1, double src2, Mat& dst);
2273 //! computes per-element maximum of two arrays (dst = max(src1, src2))
2274 CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst);
2275 //! computes per-element maximum of array and scalar (dst = max(src1, src2))
2276 CV_EXPORTS void max(const Mat& src1, double src2, Mat& dst);
2278 //! computes square root of each matrix element (dst = src**0.5)
2279 CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst);
2280 //! raises the input matrix elements to the specified power (b = a**power)
2281 CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst);
2282 //! computes exponent of each matrix element (dst = e**src)
2283 CV_EXPORTS_W void exp(InputArray src, OutputArray dst);
2284 //! computes natural logarithm of absolute value of each matrix element: dst = log(abs(src))
2285 CV_EXPORTS_W void log(InputArray src, OutputArray dst);
2286 //! computes cube root of the argument
2287 CV_EXPORTS_W float cubeRoot(float val);
2288 //! computes the angle in degrees (0..360) of the vector (x,y)
2289 CV_EXPORTS_W float fastAtan2(float y, float x);
2291 CV_EXPORTS void exp(const float* src, float* dst, int n);
2292 CV_EXPORTS void log(const float* src, float* dst, int n);
2293 CV_EXPORTS void fastAtan2(const float* y, const float* x, float* dst, int n, bool angleInDegrees);
2294 CV_EXPORTS void magnitude(const float* x, const float* y, float* dst, int n);
2296 //! converts polar coordinates to Cartesian
2297 CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle,
2298 OutputArray x, OutputArray y, bool angleInDegrees=false);
2299 //! converts Cartesian coordinates to polar
2300 CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y,
2301 OutputArray magnitude, OutputArray angle,
2302 bool angleInDegrees=false);
2303 //! computes angle (angle(i)) of each (x(i), y(i)) vector
2304 CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle,
2305 bool angleInDegrees=false);
2306 //! computes magnitude (magnitude(i)) of each (x(i), y(i)) vector
2307 CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude);
2308 //! checks that each matrix element is within the specified range.
2309 CV_EXPORTS_W bool checkRange(InputArray a, bool quiet=true, CV_OUT Point* pos=0,
2310 double minVal=-DBL_MAX, double maxVal=DBL_MAX);
2311 //! converts NaN's to the given number
2312 CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val=0);
2314 //! implements generalized matrix product algorithm GEMM from BLAS
2315 CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha,
2316 InputArray src3, double gamma, OutputArray dst, int flags=0);
2317 //! multiplies matrix by its transposition from the left or from the right
2318 CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa,
2319 InputArray delta=noArray(),
2320 double scale=1, int dtype=-1 );
2321 //! transposes the matrix
2322 CV_EXPORTS_W void transpose(InputArray src, OutputArray dst);
2323 //! performs affine transformation of each element of multi-channel input matrix
2324 CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m );
2325 //! performs perspective transformation of each element of multi-channel input matrix
2326 CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m );
2328 //! extends the symmetrical matrix from the lower half or from the upper half
2329 CV_EXPORTS_W void completeSymm(InputOutputArray mtx, bool lowerToUpper=false);
2330 //! initializes scaled identity matrix
2331 CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s=Scalar(1));
2332 //! computes determinant of a square matrix
2333 CV_EXPORTS_W double determinant(InputArray mtx);
2334 //! computes trace of a matrix
2335 CV_EXPORTS_W Scalar trace(InputArray mtx);
2336 //! computes inverse or pseudo-inverse matrix
2337 CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags=DECOMP_LU);
2338 //! solves linear system or a least-square problem
2339 CV_EXPORTS_W bool solve(InputArray src1, InputArray src2,
2340 OutputArray dst, int flags=DECOMP_LU);
2345 SORT_EVERY_COLUMN=1,
2350 //! sorts independently each matrix row or each matrix column
2351 CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags);
2352 //! sorts independently each matrix row or each matrix column
2353 CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags);
2354 //! finds real roots of a cubic polynomial
2355 CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots);
2356 //! finds real and complex roots of a polynomial
2357 CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters=300);
2358 //! finds eigenvalues of a symmetric matrix
2359 CV_EXPORTS bool eigen(InputArray src, OutputArray eigenvalues, int lowindex=-1,
2361 //! finds eigenvalues and eigenvectors of a symmetric matrix
2362 CV_EXPORTS bool eigen(InputArray src, OutputArray eigenvalues,
2363 OutputArray eigenvectors,
2364 int lowindex=-1, int highindex=-1);
2365 CV_EXPORTS_W bool eigen(InputArray src, bool computeEigenvectors,
2366 OutputArray eigenvalues, OutputArray eigenvectors);
2378 //! computes covariation matrix of a set of samples
2379 CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean,
2380 int flags, int ctype=CV_64F);
2381 //! computes covariation matrix of a set of samples
2382 CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar,
2383 OutputArray mean, int flags, int ctype=CV_64F);
2386 Principal Component Analysis
2388 The class PCA is used to compute the special basis for a set of vectors.
2389 The basis will consist of eigenvectors of the covariance matrix computed
2390 from the input set of vectors. After PCA is performed, vectors can be transformed from
2391 the original high-dimensional space to the subspace formed by a few most
2392 prominent eigenvectors (called the principal components),
2393 corresponding to the largest eigenvalues of the covariation matrix.
2394 Thus the dimensionality of the vector and the correlation between the coordinates is reduced.
2396 The following sample is the function that takes two matrices. The first one stores the set
2397 of vectors (a row per vector) that is used to compute PCA, the second one stores another
2398 "test" set of vectors (a row per vector) that are first compressed with PCA,
2399 then reconstructed back and then the reconstruction error norm is computed and printed for each vector.
2404 PCA compressPCA(const Mat& pcaset, int maxComponents,
2405 const Mat& testset, Mat& compressed)
2407 PCA pca(pcaset, // pass the data
2408 Mat(), // we do not have a pre-computed mean vector,
2409 // so let the PCA engine to compute it
2410 CV_PCA_DATA_AS_ROW, // indicate that the vectors
2411 // are stored as matrix rows
2412 // (use CV_PCA_DATA_AS_COL if the vectors are
2413 // the matrix columns)
2414 maxComponents // specify, how many principal components to retain
2416 // if there is no test data, just return the computed basis, ready-to-use
2419 CV_Assert( testset.cols == pcaset.cols );
2421 compressed.create(testset.rows, maxComponents, testset.type());
2424 for( int i = 0; i < testset.rows; i++ )
2426 Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed;
2427 // compress the vector, the result will be stored
2428 // in the i-th row of the output matrix
2429 pca.project(vec, coeffs);
2430 // and then reconstruct it
2431 pca.backProject(coeffs, reconstructed);
2432 // and measure the error
2433 printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2));
2439 class CV_EXPORTS PCA
2442 //! default constructor
2444 //! the constructor that performs PCA
2445 PCA(InputArray data, InputArray mean, int flags, int maxComponents=0);
2446 PCA(InputArray data, InputArray mean, int flags, double retainedVariance);
2447 //! operator that performs PCA. The previously stored data, if any, is released
2448 PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents=0);
2449 PCA& computeVar(InputArray data, InputArray mean, int flags, double retainedVariance);
2450 //! projects vector from the original space to the principal components subspace
2451 Mat project(InputArray vec) const;
2452 //! projects vector from the original space to the principal components subspace
2453 void project(InputArray vec, OutputArray result) const;
2454 //! reconstructs the original vector from the projection
2455 Mat backProject(InputArray vec) const;
2456 //! reconstructs the original vector from the projection
2457 void backProject(InputArray vec, OutputArray result) const;
2459 Mat eigenvectors; //!< eigenvectors of the covariation matrix
2460 Mat eigenvalues; //!< eigenvalues of the covariation matrix
2461 Mat mean; //!< mean value subtracted before the projection and added after the back projection
2464 CV_EXPORTS_W void PCACompute(InputArray data, CV_OUT InputOutputArray mean,
2465 OutputArray eigenvectors, int maxComponents=0);
2467 CV_EXPORTS_W void PCAComputeVar(InputArray data, CV_OUT InputOutputArray mean,
2468 OutputArray eigenvectors, double retainedVariance);
2470 CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean,
2471 InputArray eigenvectors, OutputArray result);
2473 CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean,
2474 InputArray eigenvectors, OutputArray result);
2478 Singular Value Decomposition class
2480 The class is used to compute Singular Value Decomposition of a floating-point matrix and then
2481 use it to solve least-square problems, under-determined linear systems, invert matrices,
2482 compute condition numbers etc.
2484 For a bit faster operation you can pass flags=SVD::MODIFY_A|... to modify the decomposed matrix
2485 when it is not necessarily to preserve it. If you want to compute condition number of a matrix
2486 or absolute value of its determinant - you do not need SVD::u or SVD::vt,
2487 so you can pass flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that the full-size SVD::u and SVD::vt
2488 must be computed, which is not necessary most of the time.
2490 class CV_EXPORTS SVD
2493 enum { MODIFY_A=1, NO_UV=2, FULL_UV=4 };
2494 //! the default constructor
2496 //! the constructor that performs SVD
2497 SVD( InputArray src, int flags=0 );
2498 //! the operator that performs SVD. The previously allocated SVD::u, SVD::w are SVD::vt are released.
2499 SVD& operator ()( InputArray src, int flags=0 );
2501 //! decomposes matrix and stores the results to user-provided matrices
2502 static void compute( InputArray src, OutputArray w,
2503 OutputArray u, OutputArray vt, int flags=0 );
2504 //! computes singular values of a matrix
2505 static void compute( InputArray src, OutputArray w, int flags=0 );
2506 //! performs back substitution
2507 static void backSubst( InputArray w, InputArray u,
2508 InputArray vt, InputArray rhs,
2511 template<typename _Tp, int m, int n, int nm> static void compute( const Matx<_Tp, m, n>& a,
2512 Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt );
2513 template<typename _Tp, int m, int n, int nm> static void compute( const Matx<_Tp, m, n>& a,
2514 Matx<_Tp, nm, 1>& w );
2515 template<typename _Tp, int m, int n, int nm, int nb> static void backSubst( const Matx<_Tp, nm, 1>& w,
2516 const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst );
2518 //! finds dst = arg min_{|dst|=1} |m*dst|
2519 static void solveZ( InputArray src, OutputArray dst );
2520 //! performs back substitution, so that dst is the solution or pseudo-solution of m*dst = rhs, where m is the decomposed matrix
2521 void backSubst( InputArray rhs, OutputArray dst ) const;
2526 //! computes SVD of src
2527 CV_EXPORTS_W void SVDecomp( InputArray src, CV_OUT OutputArray w,
2528 CV_OUT OutputArray u, CV_OUT OutputArray vt, int flags=0 );
2530 //! performs back substitution for the previously computed SVD
2531 CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt,
2532 InputArray rhs, CV_OUT OutputArray dst );
2534 //! computes Mahalanobis distance between two vectors: sqrt((v1-v2)'*icovar*(v1-v2)), where icovar is the inverse covariation matrix
2535 CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar);
2536 //! a synonym for Mahalanobis
2537 CV_EXPORTS double Mahalonobis(InputArray v1, InputArray v2, InputArray icovar);
2539 //! performs forward or inverse 1D or 2D Discrete Fourier Transformation
2540 CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags=0, int nonzeroRows=0);
2541 //! performs inverse 1D or 2D Discrete Fourier Transformation
2542 CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags=0, int nonzeroRows=0);
2543 //! performs forward or inverse 1D or 2D Discrete Cosine Transformation
2544 CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags=0);
2545 //! performs inverse 1D or 2D Discrete Cosine Transformation
2546 CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags=0);
2547 //! computes element-wise product of the two Fourier spectrums. The second spectrum can optionally be conjugated before the multiplication
2548 CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c,
2549 int flags, bool conjB=false);
2550 //! computes the minimal vector size vecsize1 >= vecsize so that the dft() of the vector of length vecsize1 can be computed efficiently
2551 CV_EXPORTS_W int getOptimalDFTSize(int vecsize);
2554 Various k-Means flags
2558 KMEANS_RANDOM_CENTERS=0, // Chooses random centers for k-Means initialization
2559 KMEANS_PP_CENTERS=2, // Uses k-Means++ algorithm for initialization
2560 KMEANS_USE_INITIAL_LABELS=1 // Uses the user-provided labels for K-Means initialization
2562 //! clusters the input data using k-Means algorithm
2563 CV_EXPORTS_W double kmeans( InputArray data, int K, CV_OUT InputOutputArray bestLabels,
2564 TermCriteria criteria, int attempts,
2565 int flags, OutputArray centers=noArray() );
2567 //! returns the thread-local Random number generator
2568 CV_EXPORTS RNG& theRNG();
2570 //! returns the next unifomly-distributed random number of the specified type
2571 template<typename _Tp> static inline _Tp randu() { return (_Tp)theRNG(); }
2573 //! fills array with uniformly-distributed random numbers from the range [low, high)
2574 CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high);
2576 //! fills array with normally-distributed random numbers with the specified mean and the standard deviation
2577 CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev);
2579 //! shuffles the input array elements
2580 CV_EXPORTS void randShuffle(InputOutputArray dst, double iterFactor=1., RNG* rng=0);
2581 CV_EXPORTS_AS(randShuffle) void randShuffle_(InputOutputArray dst, double iterFactor=1.);
2583 //! draws the line segment (pt1, pt2) in the image
2584 CV_EXPORTS_W void line(CV_IN_OUT Mat& img, Point pt1, Point pt2, const Scalar& color,
2585 int thickness=1, int lineType=8, int shift=0);
2587 //! draws the rectangle outline or a solid rectangle with the opposite corners pt1 and pt2 in the image
2588 CV_EXPORTS_W void rectangle(CV_IN_OUT Mat& img, Point pt1, Point pt2,
2589 const Scalar& color, int thickness=1,
2590 int lineType=8, int shift=0);
2592 //! draws the rectangle outline or a solid rectangle covering rec in the image
2593 CV_EXPORTS void rectangle(CV_IN_OUT Mat& img, Rect rec,
2594 const Scalar& color, int thickness=1,
2595 int lineType=8, int shift=0);
2597 //! draws the circle outline or a solid circle in the image
2598 CV_EXPORTS_W void circle(CV_IN_OUT Mat& img, Point center, int radius,
2599 const Scalar& color, int thickness=1,
2600 int lineType=8, int shift=0);
2602 //! draws an elliptic arc, ellipse sector or a rotated ellipse in the image
2603 CV_EXPORTS_W void ellipse(CV_IN_OUT Mat& img, Point center, Size axes,
2604 double angle, double startAngle, double endAngle,
2605 const Scalar& color, int thickness=1,
2606 int lineType=8, int shift=0);
2608 //! draws a rotated ellipse in the image
2609 CV_EXPORTS_W void ellipse(CV_IN_OUT Mat& img, const RotatedRect& box, const Scalar& color,
2610 int thickness=1, int lineType=8);
2612 //! draws a filled convex polygon in the image
2613 CV_EXPORTS void fillConvexPoly(Mat& img, const Point* pts, int npts,
2614 const Scalar& color, int lineType=8,
2616 CV_EXPORTS_W void fillConvexPoly(InputOutputArray img, InputArray points,
2617 const Scalar& color, int lineType=8,
2620 //! fills an area bounded by one or more polygons
2621 CV_EXPORTS void fillPoly(Mat& img, const Point** pts,
2622 const int* npts, int ncontours,
2623 const Scalar& color, int lineType=8, int shift=0,
2624 Point offset=Point() );
2626 CV_EXPORTS_W void fillPoly(InputOutputArray img, InputArrayOfArrays pts,
2627 const Scalar& color, int lineType=8, int shift=0,
2628 Point offset=Point() );
2630 //! draws one or more polygonal curves
2631 CV_EXPORTS void polylines(Mat& img, const Point** pts, const int* npts,
2632 int ncontours, bool isClosed, const Scalar& color,
2633 int thickness=1, int lineType=8, int shift=0 );
2635 CV_EXPORTS_W void polylines(InputOutputArray img, InputArrayOfArrays pts,
2636 bool isClosed, const Scalar& color,
2637 int thickness=1, int lineType=8, int shift=0 );
2639 //! clips the line segment by the rectangle Rect(0, 0, imgSize.width, imgSize.height)
2640 CV_EXPORTS bool clipLine(Size imgSize, CV_IN_OUT Point& pt1, CV_IN_OUT Point& pt2);
2642 //! clips the line segment by the rectangle imgRect
2643 CV_EXPORTS_W bool clipLine(Rect imgRect, CV_OUT CV_IN_OUT Point& pt1, CV_OUT CV_IN_OUT Point& pt2);
2648 The class is used to iterate over all the pixels on the raster line
2649 segment connecting two specified points.
2651 class CV_EXPORTS LineIterator
2654 //! intializes the iterator
2655 LineIterator( const Mat& img, Point pt1, Point pt2,
2656 int connectivity=8, bool leftToRight=false );
2657 //! returns pointer to the current pixel
2658 uchar* operator *();
2659 //! prefix increment operator (++it). shifts iterator to the next pixel
2660 LineIterator& operator ++();
2661 //! postfix increment operator (it++). shifts iterator to the next pixel
2662 LineIterator operator ++(int);
2663 //! returns coordinates of the current pixel
2670 int minusDelta, plusDelta;
2671 int minusStep, plusStep;
2674 //! converts elliptic arc to a polygonal curve
2675 CV_EXPORTS_W void ellipse2Poly( Point center, Size axes, int angle,
2676 int arcStart, int arcEnd, int delta,
2677 CV_OUT vector<Point>& pts );
2681 FONT_HERSHEY_SIMPLEX = 0,
2682 FONT_HERSHEY_PLAIN = 1,
2683 FONT_HERSHEY_DUPLEX = 2,
2684 FONT_HERSHEY_COMPLEX = 3,
2685 FONT_HERSHEY_TRIPLEX = 4,
2686 FONT_HERSHEY_COMPLEX_SMALL = 5,
2687 FONT_HERSHEY_SCRIPT_SIMPLEX = 6,
2688 FONT_HERSHEY_SCRIPT_COMPLEX = 7,
2692 //! renders text string in the image
2693 CV_EXPORTS_W void putText( Mat& img, const string& text, Point org,
2694 int fontFace, double fontScale, Scalar color,
2695 int thickness=1, int lineType=8,
2696 bool bottomLeftOrigin=false );
2698 //! returns bounding box of the text string
2699 CV_EXPORTS_W Size getTextSize(const string& text, int fontFace,
2700 double fontScale, int thickness,
2701 CV_OUT int* baseLine);
2703 ///////////////////////////////// Mat_<_Tp> ////////////////////////////////////
2706 Template matrix class derived from Mat
2708 The class Mat_ is a "thin" template wrapper on top of cv::Mat. It does not have any extra data fields,
2709 nor it or cv::Mat have any virtual methods and thus references or pointers to these two classes
2710 can be safely converted one to another. But do it with care, for example:
2713 // create 100x100 8-bit matrix
2714 Mat M(100,100,CV_8U);
2715 // this will compile fine. no any data conversion will be done.
2716 Mat_<float>& M1 = (Mat_<float>&)M;
2717 // the program will likely crash at the statement below
2721 While cv::Mat is sufficient in most cases, cv::Mat_ can be more convenient if you use a lot of element
2722 access operations and if you know matrix type at compile time.
2723 Note that cv::Mat::at<_Tp>(int y, int x) and cv::Mat_<_Tp>::operator ()(int y, int x) do absolutely the
2724 same thing and run at the same speed, but the latter is certainly shorter:
2727 Mat_<double> M(20,20);
2728 for(int i = 0; i < M.rows; i++)
2729 for(int j = 0; j < M.cols; j++)
2730 M(i,j) = 1./(i+j+1);
2733 cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
2736 It is easy to use Mat_ for multi-channel images/matrices - just pass cv::Vec as cv::Mat_ template parameter:
2739 // allocate 320x240 color image and fill it with green (in RGB space)
2740 Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
2741 // now draw a diagonal white line
2742 for(int i = 0; i < 100; i++)
2743 img(i,i)=Vec3b(255,255,255);
2744 // and now modify the 2nd (red) channel of each pixel
2745 for(int i = 0; i < img.rows; i++)
2746 for(int j = 0; j < img.cols; j++)
2747 img(i,j)[2] ^= (uchar)(i ^ j); // img(y,x)[c] accesses c-th channel of the pixel (x,y)
2750 template<typename _Tp> class CV_EXPORTS Mat_ : public Mat
2753 typedef _Tp value_type;
2754 typedef typename DataType<_Tp>::channel_type channel_type;
2755 typedef MatIterator_<_Tp> iterator;
2756 typedef MatConstIterator_<_Tp> const_iterator;
2758 //! default constructor
2760 //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type)
2761 Mat_(int _rows, int _cols);
2762 //! constructor that sets each matrix element to specified value
2763 Mat_(int _rows, int _cols, const _Tp& value);
2764 //! equivalent to Mat(_size, DataType<_Tp>::type)
2765 explicit Mat_(Size _size);
2766 //! constructor that sets each matrix element to specified value
2767 Mat_(Size _size, const _Tp& value);
2768 //! n-dim array constructor
2769 Mat_(int _ndims, const int* _sizes);
2770 //! n-dim array constructor that sets each matrix element to specified value
2771 Mat_(int _ndims, const int* _sizes, const _Tp& value);
2772 //! copy/conversion contructor. If m is of different type, it's converted
2774 //! copy constructor
2775 Mat_(const Mat_& m);
2776 //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type
2777 Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP);
2778 //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type
2779 Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0);
2780 //! selects a submatrix
2781 Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all());
2782 //! selects a submatrix
2783 Mat_(const Mat_& m, const Rect& roi);
2784 //! selects a submatrix, n-dim version
2785 Mat_(const Mat_& m, const Range* ranges);
2786 //! from a matrix expression
2787 explicit Mat_(const MatExpr& e);
2788 //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column
2789 explicit Mat_(const vector<_Tp>& vec, bool copyData=false);
2790 template<int n> explicit Mat_(const Vec<typename DataType<_Tp>::channel_type, n>& vec, bool copyData=true);
2791 template<int m, int n> explicit Mat_(const Matx<typename DataType<_Tp>::channel_type, m, n>& mtx, bool copyData=true);
2792 explicit Mat_(const Point_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
2793 explicit Mat_(const Point3_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
2794 explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer);
2796 Mat_& operator = (const Mat& m);
2797 Mat_& operator = (const Mat_& m);
2798 //! set all the elements to s.
2799 Mat_& operator = (const _Tp& s);
2800 //! assign a matrix expression
2801 Mat_& operator = (const MatExpr& e);
2803 //! iterators; they are smart enough to skip gaps in the end of rows
2806 const_iterator begin() const;
2807 const_iterator end() const;
2809 //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type)
2810 void create(int _rows, int _cols);
2811 //! equivalent to Mat::create(_size, DataType<_Tp>::type)
2812 void create(Size _size);
2813 //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type)
2814 void create(int _ndims, const int* _sizes);
2816 Mat_ cross(const Mat_& m) const;
2817 //! data type conversion
2818 template<typename T2> operator Mat_<T2>() const;
2819 //! overridden forms of Mat::row() etc.
2820 Mat_ row(int y) const;
2821 Mat_ col(int x) const;
2822 Mat_ diag(int d=0) const;
2825 //! overridden forms of Mat::elemSize() etc.
2826 size_t elemSize() const;
2827 size_t elemSize1() const;
2830 int channels() const;
2831 size_t step1(int i=0) const;
2832 //! returns step()/sizeof(_Tp)
2833 size_t stepT(int i=0) const;
2835 //! overridden forms of Mat::zeros() etc. Data type is omitted, of course
2836 static MatExpr zeros(int rows, int cols);
2837 static MatExpr zeros(Size size);
2838 static MatExpr zeros(int _ndims, const int* _sizes);
2839 static MatExpr ones(int rows, int cols);
2840 static MatExpr ones(Size size);
2841 static MatExpr ones(int _ndims, const int* _sizes);
2842 static MatExpr eye(int rows, int cols);
2843 static MatExpr eye(Size size);
2845 //! some more overriden methods
2846 Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright );
2847 Mat_ operator()( const Range& rowRange, const Range& colRange ) const;
2848 Mat_ operator()( const Rect& roi ) const;
2849 Mat_ operator()( const Range* ranges ) const;
2851 //! more convenient forms of row and element access operators
2852 _Tp* operator [](int y);
2853 const _Tp* operator [](int y) const;
2855 //! returns reference to the specified element
2856 _Tp& operator ()(const int* idx);
2857 //! returns read-only reference to the specified element
2858 const _Tp& operator ()(const int* idx) const;
2860 //! returns reference to the specified element
2861 template<int n> _Tp& operator ()(const Vec<int, n>& idx);
2862 //! returns read-only reference to the specified element
2863 template<int n> const _Tp& operator ()(const Vec<int, n>& idx) const;
2865 //! returns reference to the specified element (1D case)
2866 _Tp& operator ()(int idx0);
2867 //! returns read-only reference to the specified element (1D case)
2868 const _Tp& operator ()(int idx0) const;
2869 //! returns reference to the specified element (2D case)
2870 _Tp& operator ()(int idx0, int idx1);
2871 //! returns read-only reference to the specified element (2D case)
2872 const _Tp& operator ()(int idx0, int idx1) const;
2873 //! returns reference to the specified element (3D case)
2874 _Tp& operator ()(int idx0, int idx1, int idx2);
2875 //! returns read-only reference to the specified element (3D case)
2876 const _Tp& operator ()(int idx0, int idx1, int idx2) const;
2878 _Tp& operator ()(Point pt);
2879 const _Tp& operator ()(Point pt) const;
2881 //! conversion to vector.
2882 operator vector<_Tp>() const;
2883 //! conversion to Vec
2884 template<int n> operator Vec<typename DataType<_Tp>::channel_type, n>() const;
2885 //! conversion to Matx
2886 template<int m, int n> operator Matx<typename DataType<_Tp>::channel_type, m, n>() const;
2889 typedef Mat_<uchar> Mat1b;
2890 typedef Mat_<Vec2b> Mat2b;
2891 typedef Mat_<Vec3b> Mat3b;
2892 typedef Mat_<Vec4b> Mat4b;
2894 typedef Mat_<short> Mat1s;
2895 typedef Mat_<Vec2s> Mat2s;
2896 typedef Mat_<Vec3s> Mat3s;
2897 typedef Mat_<Vec4s> Mat4s;
2899 typedef Mat_<ushort> Mat1w;
2900 typedef Mat_<Vec2w> Mat2w;
2901 typedef Mat_<Vec3w> Mat3w;
2902 typedef Mat_<Vec4w> Mat4w;
2904 typedef Mat_<int> Mat1i;
2905 typedef Mat_<Vec2i> Mat2i;
2906 typedef Mat_<Vec3i> Mat3i;
2907 typedef Mat_<Vec4i> Mat4i;
2909 typedef Mat_<float> Mat1f;
2910 typedef Mat_<Vec2f> Mat2f;
2911 typedef Mat_<Vec3f> Mat3f;
2912 typedef Mat_<Vec4f> Mat4f;
2914 typedef Mat_<double> Mat1d;
2915 typedef Mat_<Vec2d> Mat2d;
2916 typedef Mat_<Vec3d> Mat3d;
2917 typedef Mat_<Vec4d> Mat4d;
2919 //////////// Iterators & Comma initializers //////////////////
2921 class CV_EXPORTS MatConstIterator
2924 typedef uchar* value_type;
2925 typedef ptrdiff_t difference_type;
2926 typedef const uchar** pointer;
2927 typedef uchar* reference;
2928 typedef std::random_access_iterator_tag iterator_category;
2930 //! default constructor
2932 //! constructor that sets the iterator to the beginning of the matrix
2933 MatConstIterator(const Mat* _m);
2934 //! constructor that sets the iterator to the specified element of the matrix
2935 MatConstIterator(const Mat* _m, int _row, int _col=0);
2936 //! constructor that sets the iterator to the specified element of the matrix
2937 MatConstIterator(const Mat* _m, Point _pt);
2938 //! constructor that sets the iterator to the specified element of the matrix
2939 MatConstIterator(const Mat* _m, const int* _idx);
2940 //! copy constructor
2941 MatConstIterator(const MatConstIterator& it);
2944 MatConstIterator& operator = (const MatConstIterator& it);
2945 //! returns the current matrix element
2946 uchar* operator *() const;
2947 //! returns the i-th matrix element, relative to the current
2948 uchar* operator [](ptrdiff_t i) const;
2950 //! shifts the iterator forward by the specified number of elements
2951 MatConstIterator& operator += (ptrdiff_t ofs);
2952 //! shifts the iterator backward by the specified number of elements
2953 MatConstIterator& operator -= (ptrdiff_t ofs);
2954 //! decrements the iterator
2955 MatConstIterator& operator --();
2956 //! decrements the iterator
2957 MatConstIterator operator --(int);
2958 //! increments the iterator
2959 MatConstIterator& operator ++();
2960 //! increments the iterator
2961 MatConstIterator operator ++(int);
2962 //! returns the current iterator position
2964 //! returns the current iterator position
2965 void pos(int* _idx) const;
2966 ptrdiff_t lpos() const;
2967 void seek(ptrdiff_t ofs, bool relative=false);
2968 void seek(const int* _idx, bool relative=false);
2978 Matrix read-only iterator
2981 template<typename _Tp>
2982 class CV_EXPORTS MatConstIterator_ : public MatConstIterator
2985 typedef _Tp value_type;
2986 typedef ptrdiff_t difference_type;
2987 typedef const _Tp* pointer;
2988 typedef const _Tp& reference;
2989 typedef std::random_access_iterator_tag iterator_category;
2991 //! default constructor
2992 MatConstIterator_();
2993 //! constructor that sets the iterator to the beginning of the matrix
2994 MatConstIterator_(const Mat_<_Tp>* _m);
2995 //! constructor that sets the iterator to the specified element of the matrix
2996 MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0);
2997 //! constructor that sets the iterator to the specified element of the matrix
2998 MatConstIterator_(const Mat_<_Tp>* _m, Point _pt);
2999 //! constructor that sets the iterator to the specified element of the matrix
3000 MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx);
3001 //! copy constructor
3002 MatConstIterator_(const MatConstIterator_& it);
3005 MatConstIterator_& operator = (const MatConstIterator_& it);
3006 //! returns the current matrix element
3007 _Tp operator *() const;
3008 //! returns the i-th matrix element, relative to the current
3009 _Tp operator [](ptrdiff_t i) const;
3011 //! shifts the iterator forward by the specified number of elements
3012 MatConstIterator_& operator += (ptrdiff_t ofs);
3013 //! shifts the iterator backward by the specified number of elements
3014 MatConstIterator_& operator -= (ptrdiff_t ofs);
3015 //! decrements the iterator
3016 MatConstIterator_& operator --();
3017 //! decrements the iterator
3018 MatConstIterator_ operator --(int);
3019 //! increments the iterator
3020 MatConstIterator_& operator ++();
3021 //! increments the iterator
3022 MatConstIterator_ operator ++(int);
3023 //! returns the current iterator position
3029 Matrix read-write iterator
3032 template<typename _Tp>
3033 class CV_EXPORTS MatIterator_ : public MatConstIterator_<_Tp>
3036 typedef _Tp* pointer;
3037 typedef _Tp& reference;
3038 typedef std::random_access_iterator_tag iterator_category;
3040 //! the default constructor
3042 //! constructor that sets the iterator to the beginning of the matrix
3043 MatIterator_(Mat_<_Tp>* _m);
3044 //! constructor that sets the iterator to the specified element of the matrix
3045 MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0);
3046 //! constructor that sets the iterator to the specified element of the matrix
3047 MatIterator_(const Mat_<_Tp>* _m, Point _pt);
3048 //! constructor that sets the iterator to the specified element of the matrix
3049 MatIterator_(const Mat_<_Tp>* _m, const int* _idx);
3050 //! copy constructor
3051 MatIterator_(const MatIterator_& it);
3053 MatIterator_& operator = (const MatIterator_<_Tp>& it );
3055 //! returns the current matrix element
3056 _Tp& operator *() const;
3057 //! returns the i-th matrix element, relative to the current
3058 _Tp& operator [](ptrdiff_t i) const;
3060 //! shifts the iterator forward by the specified number of elements
3061 MatIterator_& operator += (ptrdiff_t ofs);
3062 //! shifts the iterator backward by the specified number of elements
3063 MatIterator_& operator -= (ptrdiff_t ofs);
3064 //! decrements the iterator
3065 MatIterator_& operator --();
3066 //! decrements the iterator
3067 MatIterator_ operator --(int);
3068 //! increments the iterator
3069 MatIterator_& operator ++();
3070 //! increments the iterator
3071 MatIterator_ operator ++(int);
3074 template<typename _Tp> class CV_EXPORTS MatOp_Iter_;
3077 Comma-separated Matrix Initializer
3079 The class instances are usually not created explicitly.
3080 Instead, they are created on "matrix << firstValue" operator.
3082 The sample below initializes 2x2 rotation matrix:
3085 double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180);
3086 Mat R = (Mat_<double>(2,2) << a, -b, b, a);
3089 template<typename _Tp> class CV_EXPORTS MatCommaInitializer_
3092 //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat
3093 MatCommaInitializer_(Mat_<_Tp>* _m);
3094 //! the operator that takes the next value and put it to the matrix
3095 template<typename T2> MatCommaInitializer_<_Tp>& operator , (T2 v);
3096 //! another form of conversion operator
3097 Mat_<_Tp> operator *() const;
3098 operator Mat_<_Tp>() const;
3100 MatIterator_<_Tp> it;
3104 template<typename _Tp, int m, int n> class CV_EXPORTS MatxCommaInitializer
3107 MatxCommaInitializer(Matx<_Tp, m, n>* _mtx);
3108 template<typename T2> MatxCommaInitializer<_Tp, m, n>& operator , (T2 val);
3109 Matx<_Tp, m, n> operator *() const;
3111 Matx<_Tp, m, n>* dst;
3115 template<typename _Tp, int m> class CV_EXPORTS VecCommaInitializer : public MatxCommaInitializer<_Tp, m, 1>
3118 VecCommaInitializer(Vec<_Tp, m>* _vec);
3119 template<typename T2> VecCommaInitializer<_Tp, m>& operator , (T2 val);
3120 Vec<_Tp, m> operator *() const;
3124 Automatically Allocated Buffer Class
3126 The class is used for temporary buffers in functions and methods.
3127 If a temporary buffer is usually small (a few K's of memory),
3128 but its size depends on the parameters, it makes sense to create a small
3129 fixed-size array on stack and use it if it's large enough. If the required buffer size
3130 is larger than the fixed size, another buffer of sufficient size is allocated dynamically
3131 and released after the processing. Therefore, in typical cases, when the buffer size is small,
3132 there is no overhead associated with malloc()/free().
3133 At the same time, there is no limit on the size of processed data.
3135 This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and
3136 the number of stack-allocated elements. Here is how the class is used:
3139 void my_func(const cv::Mat& m)
3141 cv::AutoBuffer<float, 1000> buf; // create automatic buffer containing 1000 floats
3143 buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used,
3144 // otherwise the buffer of "m.rows" floats will be allocated
3145 // dynamically and deallocated in cv::AutoBuffer destructor
3150 template<typename _Tp, size_t fixed_size=4096/sizeof(_Tp)+8> class CV_EXPORTS AutoBuffer
3153 typedef _Tp value_type;
3154 enum { buffer_padding = (int)((16 + sizeof(_Tp) - 1)/sizeof(_Tp)) };
3156 //! the default contructor
3158 //! constructor taking the real buffer size
3159 AutoBuffer(size_t _size);
3160 //! destructor. calls deallocate()
3163 //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used
3164 void allocate(size_t _size);
3165 //! deallocates the buffer if it was dynamically allocated
3167 //! returns pointer to the real buffer, stack-allocated or head-allocated
3169 //! returns read-only pointer to the real buffer, stack-allocated or head-allocated
3170 operator const _Tp* () const;
3173 //! pointer to the real buffer, can point to buf if the buffer is small enough
3175 //! size of the real buffer
3177 //! pre-allocated buffer
3178 _Tp buf[fixed_size+buffer_padding];
3181 /////////////////////////// multi-dimensional dense matrix //////////////////////////
3184 n-Dimensional Dense Matrix Iterator Class.
3186 The class cv::NAryMatIterator is used for iterating over one or more n-dimensional dense arrays (cv::Mat's).
3188 The iterator is completely different from cv::Mat_ and cv::SparseMat_ iterators.
3189 It iterates through the slices (or planes), not the elements, where "slice" is a continuous part of the arrays.
3191 Here is the example on how the iterator can be used to normalize 3D histogram:
3194 void normalizeColorHist(Mat& hist)
3197 // intialize iterator (the style is different from STL).
3198 // after initialization the iterator will contain
3199 // the number of slices or planes
3200 // the iterator will go through
3201 Mat* arrays[] = { &hist, 0 };
3203 NAryMatIterator it(arrays, planes);
3205 // iterate through the matrix. on each iteration
3206 // it.planes[i] (of type Mat) will be set to the current plane of
3207 // i-th n-dim matrix passed to the iterator constructor.
3208 for(int p = 0; p < it.nplanes; p++, ++it)
3209 s += sum(it.planes[0])[0];
3210 it = NAryMatIterator(hist);
3212 for(int p = 0; p < it.nplanes; p++, ++it)
3215 // this is a shorter implementation of the above
3216 // using built-in operations on Mat
3217 double s = sum(hist)[0];
3218 hist.convertTo(hist, hist.type(), 1./s, 0);
3220 // and this is even shorter one
3221 // (assuming that the histogram elements are non-negative)
3222 normalize(hist, hist, 1, 0, NORM_L1);
3227 You can iterate through several matrices simultaneously as long as they have the same geometry
3228 (dimensionality and all the dimension sizes are the same), which is useful for binary
3229 and n-ary operations on such matrices. Just pass those matrices to cv::MatNDIterator.
3230 Then, during the iteration it.planes[0], it.planes[1], ... will
3231 be the slices of the corresponding matrices
3233 class CV_EXPORTS NAryMatIterator
3236 //! the default constructor
3238 //! the full constructor taking arbitrary number of n-dim matrices
3239 NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1);
3240 //! the full constructor taking arbitrary number of n-dim matrices
3241 NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1);
3242 //! the separate iterator initialization method
3243 void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1);
3245 //! proceeds to the next plane of every iterated matrix
3246 NAryMatIterator& operator ++();
3247 //! proceeds to the next plane of every iterated matrix (postfix increment operator)
3248 NAryMatIterator operator ++(int);
3250 //! the iterated arrays
3252 //! the current planes
3256 //! the number of arrays
3258 //! the number of hyper-planes that the iterator steps through
3260 //! the size of each segment (in elements)
3267 //typedef NAryMatIterator NAryMatNDIterator;
3269 typedef void (*ConvertData)(const void* from, void* to, int cn);
3270 typedef void (*ConvertScaleData)(const void* from, void* to, int cn, double alpha, double beta);
3272 //! returns the function for converting pixels from one data type to another
3273 CV_EXPORTS ConvertData getConvertElem(int fromType, int toType);
3274 //! returns the function for converting pixels from one data type to another with the optional scaling
3275 CV_EXPORTS ConvertScaleData getConvertScaleElem(int fromType, int toType);
3278 /////////////////////////// multi-dimensional sparse matrix //////////////////////////
3280 class SparseMatIterator;
3281 class SparseMatConstIterator;
3282 template<typename _Tp> class SparseMatIterator_;
3283 template<typename _Tp> class SparseMatConstIterator_;
3286 Sparse matrix class.
3288 The class represents multi-dimensional sparse numerical arrays. Such a sparse array can store elements
3289 of any type that cv::Mat is able to store. "Sparse" means that only non-zero elements
3290 are stored (though, as a result of some operations on a sparse matrix, some of its stored elements
3291 can actually become 0. It's user responsibility to detect such elements and delete them using cv::SparseMat::erase().
3292 The non-zero elements are stored in a hash table that grows when it's filled enough,
3293 so that the search time remains O(1) in average. Elements can be accessed using the following methods:
3296 <li>Query operations: cv::SparseMat::ptr() and the higher-level cv::SparseMat::ref(),
3297 cv::SparseMat::value() and cv::SparseMat::find, for example:
3300 int size[] = {10, 10, 10, 10, 10};
3301 SparseMat sparse_mat(dims, size, CV_32F);
3302 for(int i = 0; i < 1000; i++)
3305 for(int k = 0; k < dims; k++)
3306 idx[k] = rand()%sparse_mat.size(k);
3307 sparse_mat.ref<float>(idx) += 1.f;
3311 <li>Sparse matrix iterators. Like cv::Mat iterators and unlike cv::Mat iterators, the sparse matrix iterators are STL-style,
3312 that is, the iteration is done as following:
3314 // prints elements of a sparse floating-point matrix and the sum of elements.
3315 SparseMatConstIterator_<float>
3316 it = sparse_mat.begin<float>(),
3317 it_end = sparse_mat.end<float>();
3319 int dims = sparse_mat.dims();
3320 for(; it != it_end; ++it)
3322 // print element indices and the element value
3323 const Node* n = it.node();
3325 for(int i = 0; i < dims; i++)
3326 printf("%3d%c", n->idx[i], i < dims-1 ? ',' : ')');
3327 printf(": %f\n", *it);
3330 printf("Element sum is %g\n", s);
3332 If you run this loop, you will notice that elements are enumerated
3333 in no any logical order (lexicographical etc.),
3334 they come in the same order as they stored in the hash table, i.e. semi-randomly.
3336 You may collect pointers to the nodes and sort them to get the proper ordering.
3337 Note, however, that pointers to the nodes may become invalid when you add more
3338 elements to the matrix; this is because of possible buffer reallocation.
3340 <li>A combination of the above 2 methods when you need to process 2 or more sparse
3341 matrices simultaneously, e.g. this is how you can compute unnormalized
3342 cross-correlation of the 2 floating-point sparse matrices:
3344 double crossCorr(const SparseMat& a, const SparseMat& b)
3346 const SparseMat *_a = &a, *_b = &b;
3347 // if b contains less elements than a,
3348 // it's faster to iterate through b
3349 if(_a->nzcount() > _b->nzcount())
3351 SparseMatConstIterator_<float> it = _a->begin<float>(),
3352 it_end = _a->end<float>();
3354 for(; it != it_end; ++it)
3356 // take the next element from the first matrix
3358 const Node* anode = it.node();
3359 // and try to find element with the same index in the second matrix.
3360 // since the hash value depends only on the element index,
3361 // we reuse hashvalue stored in the node
3362 float bvalue = _b->value<float>(anode->idx,&anode->hashval);
3363 ccorr += avalue*bvalue;
3370 class CV_EXPORTS SparseMat
3373 typedef SparseMatIterator iterator;
3374 typedef SparseMatConstIterator const_iterator;
3376 //! the sparse matrix header
3377 struct CV_EXPORTS Hdr
3379 Hdr(int _dims, const int* _sizes, int _type);
3388 vector<size_t> hashtab;
3389 int size[CV_MAX_DIM];
3392 //! sparse matrix node - element of a hash table
3393 struct CV_EXPORTS Node
3397 //! index of the next node in the same hash table entry
3399 //! index of the matrix element
3400 int idx[CV_MAX_DIM];
3403 //! default constructor
3405 //! creates matrix of the specified size and type
3406 SparseMat(int dims, const int* _sizes, int _type);
3407 //! copy constructor
3408 SparseMat(const SparseMat& m);
3409 //! converts dense 2d matrix to the sparse form
3411 \param m the input matrix
3412 \param try1d if true and m is a single-column matrix (Nx1),
3413 then the sparse matrix will be 1-dimensional.
3415 explicit SparseMat(const Mat& m);
3416 //! converts old-style sparse matrix to the new-style. All the data is copied
3417 SparseMat(const CvSparseMat* m);
3421 //! assignment operator. This is O(1) operation, i.e. no data is copied
3422 SparseMat& operator = (const SparseMat& m);
3423 //! equivalent to the corresponding constructor
3424 SparseMat& operator = (const Mat& m);
3426 //! creates full copy of the matrix
3427 SparseMat clone() const;
3429 //! copies all the data to the destination matrix. All the previous content of m is erased
3430 void copyTo( SparseMat& m ) const;
3431 //! converts sparse matrix to dense matrix.
3432 void copyTo( Mat& m ) const;
3433 //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type
3434 void convertTo( SparseMat& m, int rtype, double alpha=1 ) const;
3435 //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling.
3437 \param rtype The output matrix data type. When it is =-1, the output array will have the same data type as (*this)
3438 \param alpha The scale factor
3439 \param beta The optional delta added to the scaled values before the conversion
3441 void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
3444 void assignTo( SparseMat& m, int type=-1 ) const;
3446 //! reallocates sparse matrix.
3448 If the matrix already had the proper size and type,
3449 it is simply cleared with clear(), otherwise,
3450 the old matrix is released (using release()) and the new one is allocated.
3452 void create(int dims, const int* _sizes, int _type);
3453 //! sets all the sparse matrix elements to 0, which means clearing the hash table.
3455 //! manually increments the reference counter to the header.
3457 // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated.
3460 //! converts sparse matrix to the old-style representation; all the elements are copied.
3461 operator CvSparseMat*() const;
3462 //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements)
3463 size_t elemSize() const;
3464 //! returns elemSize()/channels()
3465 size_t elemSize1() const;
3467 //! returns type of sparse matrix elements
3469 //! returns the depth of sparse matrix elements
3471 //! returns the number of channels
3472 int channels() const;
3474 //! returns the array of sizes, or NULL if the matrix is not allocated
3475 const int* size() const;
3476 //! returns the size of i-th matrix dimension (or 0)
3477 int size(int i) const;
3478 //! returns the matrix dimensionality
3480 //! returns the number of non-zero elements (=the number of hash table nodes)
3481 size_t nzcount() const;
3483 //! computes the element hash value (1D case)
3484 size_t hash(int i0) const;
3485 //! computes the element hash value (2D case)
3486 size_t hash(int i0, int i1) const;
3487 //! computes the element hash value (3D case)
3488 size_t hash(int i0, int i1, int i2) const;
3489 //! computes the element hash value (nD case)
3490 size_t hash(const int* idx) const;
3494 specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case.
3496 return pointer to the matrix element.
3498 <li>if the element is there (it's non-zero), the pointer to it is returned
3499 <li>if it's not there and createMissing=false, NULL pointer is returned
3500 <li>if it's not there and createMissing=true, then the new element
3501 is created and initialized with 0. Pointer to it is returned
3502 <li>if the optional hashval pointer is not NULL, the element hash value is
3503 not computed, but *hashval is taken instead.
3506 //! returns pointer to the specified element (1D case)
3507 uchar* ptr(int i0, bool createMissing, size_t* hashval=0);
3508 //! returns pointer to the specified element (2D case)
3509 uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0);
3510 //! returns pointer to the specified element (3D case)
3511 uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0);
3512 //! returns pointer to the specified element (nD case)
3513 uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0);
3518 return read-write reference to the specified sparse matrix element.
3520 ref<_Tp>(i0,...[,hashval]) is equivalent to *(_Tp*)ptr(i0,...,true[,hashval]).
3521 The methods always return a valid reference.
3522 If the element did not exist, it is created and initialiazed with 0.
3524 //! returns reference to the specified element (1D case)
3525 template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0);
3526 //! returns reference to the specified element (2D case)
3527 template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0);
3528 //! returns reference to the specified element (3D case)
3529 template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
3530 //! returns reference to the specified element (nD case)
3531 template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0);
3536 return value of the specified sparse matrix element.
3538 value<_Tp>(i0,...[,hashval]) is equivalent
3541 { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); }
3544 That is, if the element did not exist, the methods return 0.
3546 //! returns value of the specified element (1D case)
3547 template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const;
3548 //! returns value of the specified element (2D case)
3549 template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const;
3550 //! returns value of the specified element (3D case)
3551 template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0) const;
3552 //! returns value of the specified element (nD case)
3553 template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const;
3558 Return pointer to the specified sparse matrix element if it exists
3560 find<_Tp>(i0,...[,hashval]) is equivalent to (_const Tp*)ptr(i0,...false[,hashval]).
3562 If the specified element does not exist, the methods return NULL.
3564 //! returns pointer to the specified element (1D case)
3565 template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const;
3566 //! returns pointer to the specified element (2D case)
3567 template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0) const;
3568 //! returns pointer to the specified element (3D case)
3569 template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const;
3570 //! returns pointer to the specified element (nD case)
3571 template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0) const;
3573 //! erases the specified element (2D case)
3574 void erase(int i0, int i1, size_t* hashval=0);
3575 //! erases the specified element (3D case)
3576 void erase(int i0, int i1, int i2, size_t* hashval=0);
3577 //! erases the specified element (nD case)
3578 void erase(const int* idx, size_t* hashval=0);
3582 return the sparse matrix iterator pointing to the first sparse matrix element
3584 //! returns the sparse matrix iterator at the matrix beginning
3585 SparseMatIterator begin();
3586 //! returns the sparse matrix iterator at the matrix beginning
3587 template<typename _Tp> SparseMatIterator_<_Tp> begin();
3588 //! returns the read-only sparse matrix iterator at the matrix beginning
3589 SparseMatConstIterator begin() const;
3590 //! returns the read-only sparse matrix iterator at the matrix beginning
3591 template<typename _Tp> SparseMatConstIterator_<_Tp> begin() const;
3594 return the sparse matrix iterator pointing to the element following the last sparse matrix element
3596 //! returns the sparse matrix iterator at the matrix end
3597 SparseMatIterator end();
3598 //! returns the read-only sparse matrix iterator at the matrix end
3599 SparseMatConstIterator end() const;
3600 //! returns the typed sparse matrix iterator at the matrix end
3601 template<typename _Tp> SparseMatIterator_<_Tp> end();
3602 //! returns the typed read-only sparse matrix iterator at the matrix end
3603 template<typename _Tp> SparseMatConstIterator_<_Tp> end() const;
3605 //! returns the value stored in the sparse martix node
3606 template<typename _Tp> _Tp& value(Node* n);
3607 //! returns the value stored in the sparse martix node
3608 template<typename _Tp> const _Tp& value(const Node* n) const;
3610 ////////////// some internal-use methods ///////////////
3611 Node* node(size_t nidx);
3612 const Node* node(size_t nidx) const;
3614 uchar* newNode(const int* idx, size_t hashval);
3615 void removeNode(size_t hidx, size_t nidx, size_t previdx);
3616 void resizeHashTab(size_t newsize);
3618 enum { MAGIC_VAL=0x42FD0000, MAX_DIM=CV_MAX_DIM, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 };
3624 //! finds global minimum and maximum sparse array elements and returns their values and their locations
3625 CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal,
3626 double* maxVal, int* minIdx=0, int* maxIdx=0);
3627 //! computes norm of a sparse matrix
3628 CV_EXPORTS double norm( const SparseMat& src, int normType );
3629 //! 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
3630 CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType );
3633 Read-Only Sparse Matrix Iterator.
3634 Here is how to use the iterator to compute the sum of floating-point sparse matrix elements:
3637 SparseMatConstIterator it = m.begin(), it_end = m.end();
3639 CV_Assert( m.type() == CV_32F );
3640 for( ; it != it_end; ++it )
3641 s += it.value<float>();
3644 class CV_EXPORTS SparseMatConstIterator
3647 //! the default constructor
3648 SparseMatConstIterator();
3649 //! the full constructor setting the iterator to the first sparse matrix element
3650 SparseMatConstIterator(const SparseMat* _m);
3651 //! the copy constructor
3652 SparseMatConstIterator(const SparseMatConstIterator& it);
3654 //! the assignment operator
3655 SparseMatConstIterator& operator = (const SparseMatConstIterator& it);
3657 //! template method returning the current matrix element
3658 template<typename _Tp> const _Tp& value() const;
3659 //! returns the current node of the sparse matrix. it.node->idx is the current element index
3660 const SparseMat::Node* node() const;
3662 //! moves iterator to the previous element
3663 SparseMatConstIterator& operator --();
3664 //! moves iterator to the previous element
3665 SparseMatConstIterator operator --(int);
3666 //! moves iterator to the next element
3667 SparseMatConstIterator& operator ++();
3668 //! moves iterator to the next element
3669 SparseMatConstIterator operator ++(int);
3671 //! moves iterator to the element after the last element
3680 Read-write Sparse Matrix Iterator
3682 The class is similar to cv::SparseMatConstIterator,
3683 but can be used for in-place modification of the matrix elements.
3685 class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator
3688 //! the default constructor
3689 SparseMatIterator();
3690 //! the full constructor setting the iterator to the first sparse matrix element
3691 SparseMatIterator(SparseMat* _m);
3692 //! the full constructor setting the iterator to the specified sparse matrix element
3693 SparseMatIterator(SparseMat* _m, const int* idx);
3694 //! the copy constructor
3695 SparseMatIterator(const SparseMatIterator& it);
3697 //! the assignment operator
3698 SparseMatIterator& operator = (const SparseMatIterator& it);
3699 //! returns read-write reference to the current sparse matrix element
3700 template<typename _Tp> _Tp& value() const;
3701 //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!)
3702 SparseMat::Node* node() const;
3704 //! moves iterator to the next element
3705 SparseMatIterator& operator ++();
3706 //! moves iterator to the next element
3707 SparseMatIterator operator ++(int);
3711 The Template Sparse Matrix class derived from cv::SparseMat
3713 The class provides slightly more convenient operations for accessing elements.
3718 SparseMat_<int> m_ = (SparseMat_<int>&)m;
3719 m_.ref(1)++; // equivalent to m.ref<int>(1)++;
3720 m_.ref(2) += m_(3); // equivalent to m.ref<int>(2) += m.value<int>(3);
3723 template<typename _Tp> class CV_EXPORTS SparseMat_ : public SparseMat
3726 typedef SparseMatIterator_<_Tp> iterator;
3727 typedef SparseMatConstIterator_<_Tp> const_iterator;
3729 //! the default constructor
3731 //! the full constructor equivelent to SparseMat(dims, _sizes, DataType<_Tp>::type)
3732 SparseMat_(int dims, const int* _sizes);
3733 //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted
3734 SparseMat_(const SparseMat& m);
3735 //! the copy constructor. This is O(1) operation - no data is copied
3736 SparseMat_(const SparseMat_& m);
3737 //! converts dense matrix to the sparse form
3738 SparseMat_(const Mat& m);
3739 //! converts the old-style sparse matrix to the C++ class. All the elements are copied
3740 SparseMat_(const CvSparseMat* m);
3741 //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted
3742 SparseMat_& operator = (const SparseMat& m);
3743 //! the assignment operator. This is O(1) operation - no data is copied
3744 SparseMat_& operator = (const SparseMat_& m);
3745 //! converts dense matrix to the sparse form
3746 SparseMat_& operator = (const Mat& m);
3748 //! makes full copy of the matrix. All the elements are duplicated
3749 SparseMat_ clone() const;
3750 //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type)
3751 void create(int dims, const int* _sizes);
3752 //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied
3753 operator CvSparseMat*() const;
3755 //! returns type of the matrix elements
3757 //! returns depth of the matrix elements
3759 //! returns the number of channels in each matrix element
3760 int channels() const;
3762 //! equivalent to SparseMat::ref<_Tp>(i0, hashval)
3763 _Tp& ref(int i0, size_t* hashval=0);
3764 //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval)
3765 _Tp& ref(int i0, int i1, size_t* hashval=0);
3766 //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval)
3767 _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
3768 //! equivalent to SparseMat::ref<_Tp>(idx, hashval)
3769 _Tp& ref(const int* idx, size_t* hashval=0);
3771 //! equivalent to SparseMat::value<_Tp>(i0, hashval)
3772 _Tp operator()(int i0, size_t* hashval=0) const;
3773 //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval)
3774 _Tp operator()(int i0, int i1, size_t* hashval=0) const;
3775 //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval)
3776 _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const;
3777 //! equivalent to SparseMat::value<_Tp>(idx, hashval)
3778 _Tp operator()(const int* idx, size_t* hashval=0) const;
3780 //! returns sparse matrix iterator pointing to the first sparse matrix element
3781 SparseMatIterator_<_Tp> begin();
3782 //! returns read-only sparse matrix iterator pointing to the first sparse matrix element
3783 SparseMatConstIterator_<_Tp> begin() const;
3784 //! returns sparse matrix iterator pointing to the element following the last sparse matrix element
3785 SparseMatIterator_<_Tp> end();
3786 //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element
3787 SparseMatConstIterator_<_Tp> end() const;
3792 Template Read-Only Sparse Matrix Iterator Class.
3794 This is the derived from SparseMatConstIterator class that
3795 introduces more convenient operator *() for accessing the current element.
3797 template<typename _Tp> class CV_EXPORTS SparseMatConstIterator_ : public SparseMatConstIterator
3800 typedef std::forward_iterator_tag iterator_category;
3802 //! the default constructor
3803 SparseMatConstIterator_();
3804 //! the full constructor setting the iterator to the first sparse matrix element
3805 SparseMatConstIterator_(const SparseMat_<_Tp>* _m);
3806 SparseMatConstIterator_(const SparseMat* _m);
3807 //! the copy constructor
3808 SparseMatConstIterator_(const SparseMatConstIterator_& it);
3810 //! the assignment operator
3811 SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it);
3812 //! the element access operator
3813 const _Tp& operator *() const;
3815 //! moves iterator to the next element
3816 SparseMatConstIterator_& operator ++();
3817 //! moves iterator to the next element
3818 SparseMatConstIterator_ operator ++(int);
3822 Template Read-Write Sparse Matrix Iterator Class.
3824 This is the derived from cv::SparseMatConstIterator_ class that
3825 introduces more convenient operator *() for accessing the current element.
3827 template<typename _Tp> class CV_EXPORTS SparseMatIterator_ : public SparseMatConstIterator_<_Tp>
3830 typedef std::forward_iterator_tag iterator_category;
3832 //! the default constructor
3833 SparseMatIterator_();
3834 //! the full constructor setting the iterator to the first sparse matrix element
3835 SparseMatIterator_(SparseMat_<_Tp>* _m);
3836 SparseMatIterator_(SparseMat* _m);
3837 //! the copy constructor
3838 SparseMatIterator_(const SparseMatIterator_& it);
3840 //! the assignment operator
3841 SparseMatIterator_& operator = (const SparseMatIterator_& it);
3842 //! returns the reference to the current element
3843 _Tp& operator *() const;
3845 //! moves the iterator to the next element
3846 SparseMatIterator_& operator ++();
3847 //! moves the iterator to the next element
3848 SparseMatIterator_ operator ++(int);
3851 //////////////////// Fast Nearest-Neighbor Search Structure ////////////////////
3854 Fast Nearest Neighbor Search Class.
3856 The class implements D. Lowe BBF (Best-Bin-First) algorithm for the last
3857 approximate (or accurate) nearest neighbor search in multi-dimensional spaces.
3859 First, a set of vectors is passed to KDTree::KDTree() constructor
3860 or KDTree::build() method, where it is reordered.
3862 Then arbitrary vectors can be passed to KDTree::findNearest() methods, which
3863 find the K nearest neighbors among the vectors from the initial set.
3864 The user can balance between the speed and accuracy of the search by varying Emax
3865 parameter, which is the number of leaves that the algorithm checks.
3866 The larger parameter values yield more accurate results at the expense of lower processing speed.
3869 KDTree T(points, false);
3870 const int K = 3, Emax = INT_MAX;
3873 T.findNearest(query_vec, K, Emax, idx, 0, dist);
3874 CV_Assert(dist[0] <= dist[1] && dist[1] <= dist[2]);
3877 class CV_EXPORTS_W KDTree
3881 The node of the search tree.
3885 Node() : idx(-1), left(-1), right(-1), boundary(0.f) {}
3886 Node(int _idx, int _left, int _right, float _boundary)
3887 : idx(_idx), left(_left), right(_right), boundary(_boundary) {}
3888 //! split dimension; >=0 for nodes (dim), < 0 for leaves (index of the point)
3890 //! node indices of the left and the right branches
3892 //! go to the left if query_vec[node.idx]<=node.boundary, otherwise go to the right
3896 //! the default constructor
3898 //! the full constructor that builds the search tree
3899 CV_WRAP KDTree(InputArray points, bool copyAndReorderPoints=false);
3900 //! the full constructor that builds the search tree
3901 CV_WRAP KDTree(InputArray points, InputArray _labels,
3902 bool copyAndReorderPoints=false);
3903 //! builds the search tree
3904 CV_WRAP void build(InputArray points, bool copyAndReorderPoints=false);
3905 //! builds the search tree
3906 CV_WRAP void build(InputArray points, InputArray labels,
3907 bool copyAndReorderPoints=false);
3908 //! finds the K nearest neighbors of "vec" while looking at Emax (at most) leaves
3909 CV_WRAP int findNearest(InputArray vec, int K, int Emax,
3910 OutputArray neighborsIdx,
3911 OutputArray neighbors=noArray(),
3912 OutputArray dist=noArray(),
3913 OutputArray labels=noArray()) const;
3914 //! finds all the points from the initial set that belong to the specified box
3915 CV_WRAP void findOrthoRange(InputArray minBounds,
3916 InputArray maxBounds,
3917 OutputArray neighborsIdx,
3918 OutputArray neighbors=noArray(),
3919 OutputArray labels=noArray()) const;
3920 //! returns vectors with the specified indices
3921 CV_WRAP void getPoints(InputArray idx, OutputArray pts,
3922 OutputArray labels=noArray()) const;
3923 //! return a vector with the specified index
3924 const float* getPoint(int ptidx, int* label=0) const;
3925 //! returns the search space dimensionality
3926 CV_WRAP int dims() const;
3928 vector<Node> nodes; //!< all the tree nodes
3929 CV_PROP Mat points; //!< all the points. It can be a reordered copy of the input vector set or the original vector set.
3930 CV_PROP vector<int> labels; //!< the parallel array of labels.
3931 CV_PROP int maxDepth; //!< maximum depth of the search tree. Do not modify it
3932 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
3935 //////////////////////////////////////// XML & YAML I/O ////////////////////////////////////
3937 class CV_EXPORTS FileNode;
3940 XML/YAML File Storage Class.
3942 The class describes an object associated with XML or YAML file.
3943 It can be used to store data to such a file or read and decode the data.
3945 The storage is organized as a tree of nested sequences (or lists) and mappings.
3946 Sequence is a heterogenious array, which elements are accessed by indices or sequentially using an iterator.
3947 Mapping is analogue of std::map or C structure, which elements are accessed by names.
3948 The most top level structure is a mapping.
3949 Leaves of the file storage tree are integers, floating-point numbers and text strings.
3951 For example, the following code:
3954 // open file storage for writing. Type of the file is determined from the extension
3955 FileStorage fs("test.yml", FileStorage::WRITE);
3956 fs << "test_int" << 5 << "test_real" << 3.1 << "test_string" << "ABCDEFGH";
3957 fs << "test_mat" << Mat::eye(3,3,CV_32F);
3959 fs << "test_list" << "[" << 0.0000000000001 << 2 << CV_PI << -3435345 << "2-502 2-029 3egegeg" <<
3960 "{:" << "month" << 12 << "day" << 31 << "year" << 1969 << "}" << "]";
3961 fs << "test_map" << "{" << "x" << 1 << "y" << 2 << "width" << 100 << "height" << 200 << "lbp" << "[:";
3963 const uchar arr[] = {0, 1, 1, 0, 1, 1, 0, 1};
3964 fs.writeRaw("u", arr, (int)(sizeof(arr)/sizeof(arr[0])));
3969 will produce the following file:
3974 test_real: 3.1000000000000001e+00
3975 test_string: ABCDEFGH
3976 test_mat: !!opencv-matrix
3980 data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1. ]
3982 - 1.0000000000000000e-13
3984 - 3.1415926535897931e+00
3986 - "2-502 2-029 3egegeg"
3987 - { month:12, day:31, year:1969 }
3993 lbp: [ 0, 1, 1, 0, 1, 1, 0, 1 ]
3996 and to read the file above, the following code can be used:
3999 // open file storage for reading.
4000 // Type of the file is determined from the content, not the extension
4001 FileStorage fs("test.yml", FileStorage::READ);
4002 int test_int = (int)fs["test_int"];
4003 double test_real = (double)fs["test_real"];
4004 string test_string = (string)fs["test_string"];
4007 fs["test_mat"] >> M;
4009 FileNode tl = fs["test_list"];
4010 CV_Assert(tl.type() == FileNode::SEQ && tl.size() == 6);
4011 double tl0 = (double)tl[0];
4012 int tl1 = (int)tl[1];
4013 double tl2 = (double)tl[2];
4014 int tl3 = (int)tl[3];
4015 string tl4 = (string)tl[4];
4016 CV_Assert(tl[5].type() == FileNode::MAP && tl[5].size() == 3);
4018 int month = (int)tl[5]["month"];
4019 int day = (int)tl[5]["day"];
4020 int year = (int)tl[5]["year"];
4022 FileNode tm = fs["test_map"];
4024 int x = (int)tm["x"];
4025 int y = (int)tm["y"];
4026 int width = (int)tm["width"];
4027 int height = (int)tm["height"];
4030 FileNodeIterator it = tm["lbp"].begin();
4032 for(int k = 0; k < 8; k++, ++it)
4033 lbp_val |= ((int)*it) << k;
4036 class CV_EXPORTS_W FileStorage
4039 //! file storage mode
4042 READ=0, //! read mode
4043 WRITE=1, //! write mode
4044 APPEND=2, //! append mode
4058 //! the default constructor
4059 CV_WRAP FileStorage();
4060 //! the full constructor that opens file storage for reading or writing
4061 CV_WRAP FileStorage(const string& source, int flags, const string& encoding=string());
4062 //! the constructor that takes pointer to the C FileStorage structure
4063 FileStorage(CvFileStorage* fs);
4064 //! the destructor. calls release()
4065 virtual ~FileStorage();
4067 //! opens file storage for reading or writing. The previous storage is closed with release()
4068 CV_WRAP virtual bool open(const string& filename, int flags, const string& encoding=string());
4069 //! returns true if the object is associated with currently opened file.
4070 CV_WRAP virtual bool isOpened() const;
4071 //! closes the file and releases all the memory buffers
4072 CV_WRAP virtual void release();
4073 //! closes the file, releases all the memory buffers and returns the text string
4074 CV_WRAP string releaseAndGetString();
4076 //! returns the first element of the top-level mapping
4077 CV_WRAP FileNode getFirstTopLevelNode() const;
4078 //! returns the top-level mapping. YAML supports multiple streams
4079 CV_WRAP FileNode root(int streamidx=0) const;
4080 //! returns the specified element of the top-level mapping
4081 FileNode operator[](const string& nodename) const;
4082 //! returns the specified element of the top-level mapping
4083 CV_WRAP FileNode operator[](const char* nodename) const;
4085 //! returns pointer to the underlying C FileStorage structure
4086 CvFileStorage* operator *() { return fs; }
4087 //! returns pointer to the underlying C FileStorage structure
4088 const CvFileStorage* operator *() const { return fs; }
4089 //! writes one or more numbers of the specified format to the currently written structure
4090 void writeRaw( const string& fmt, const uchar* vec, size_t len );
4091 //! writes the registered C structure (CvMat, CvMatND, CvSeq). See cvWrite()
4092 void writeObj( const string& name, const void* obj );
4094 //! returns the normalized object name for the specified file name
4095 static string getDefaultObjectName(const string& filename);
4097 Ptr<CvFileStorage> fs; //!< the underlying C FileStorage structure
4098 string elname; //!< the currently written element
4099 vector<char> structs; //!< the stack of written structures
4100 int state; //!< the writer state
4103 class CV_EXPORTS FileNodeIterator;
4106 File Storage Node class
4108 The node is used to store each and every element of the file storage opened for reading -
4109 from the primitive objects, such as numbers and text strings, to the complex nodes:
4110 sequences, mappings and the registered objects.
4112 Note that file nodes are only used for navigating file storages opened for reading.
4113 When a file storage is opened for writing, no data is stored in memory after it is written.
4115 class CV_EXPORTS_W_SIMPLE FileNode
4118 //! type of the file storage node
4121 NONE=0, //!< empty node
4122 INT=1, //!< an integer
4123 REAL=2, //!< floating-point number
4124 FLOAT=REAL, //!< synonym or REAL
4125 STR=3, //!< text string in UTF-8 encoding
4126 STRING=STR, //!< synonym for STR
4127 REF=4, //!< integer of size size_t. Typically used for storing complex dynamic structures where some elements reference the others
4128 SEQ=5, //!< sequence
4131 FLOW=8, //!< compact representation of a sequence or mapping. Used only by YAML writer
4132 USER=16, //!< a registered object (e.g. a matrix)
4133 EMPTY=32, //!< empty structure (sequence or mapping)
4134 NAMED=64 //!< the node has a name (i.e. it is element of a mapping)
4136 //! the default constructor
4138 //! the full constructor wrapping CvFileNode structure.
4139 FileNode(const CvFileStorage* fs, const CvFileNode* node);
4140 //! the copy constructor
4141 FileNode(const FileNode& node);
4142 //! returns element of a mapping node
4143 FileNode operator[](const string& nodename) const;
4144 //! returns element of a mapping node
4145 CV_WRAP FileNode operator[](const char* nodename) const;
4146 //! returns element of a sequence node
4147 CV_WRAP FileNode operator[](int i) const;
4148 //! returns type of the node
4149 CV_WRAP int type() const;
4151 //! returns true if the node is empty
4152 CV_WRAP bool empty() const;
4153 //! returns true if the node is a "none" object
4154 CV_WRAP bool isNone() const;
4155 //! returns true if the node is a sequence
4156 CV_WRAP bool isSeq() const;
4157 //! returns true if the node is a mapping
4158 CV_WRAP bool isMap() const;
4159 //! returns true if the node is an integer
4160 CV_WRAP bool isInt() const;
4161 //! returns true if the node is a floating-point number
4162 CV_WRAP bool isReal() const;
4163 //! returns true if the node is a text string
4164 CV_WRAP bool isString() const;
4165 //! returns true if the node has a name
4166 CV_WRAP bool isNamed() const;
4167 //! returns the node name or an empty string if the node is nameless
4168 CV_WRAP string name() const;
4169 //! returns the number of elements in the node, if it is a sequence or mapping, or 1 otherwise.
4170 CV_WRAP size_t size() const;
4171 //! returns the node content as an integer. If the node stores floating-point number, it is rounded.
4172 operator int() const;
4173 //! returns the node content as float
4174 operator float() const;
4175 //! returns the node content as double
4176 operator double() const;
4177 //! returns the node content as text string
4178 operator string() const;
4180 //! returns pointer to the underlying file node
4181 CvFileNode* operator *();
4182 //! returns pointer to the underlying file node
4183 const CvFileNode* operator* () const;
4185 //! returns iterator pointing to the first node element
4186 FileNodeIterator begin() const;
4187 //! returns iterator pointing to the element following the last node element
4188 FileNodeIterator end() const;
4190 //! reads node elements to the buffer with the specified format
4191 void readRaw( const string& fmt, uchar* vec, size_t len ) const;
4192 //! reads the registered object and returns pointer to it
4193 void* readObj() const;
4195 // do not use wrapper pointer classes for better efficiency
4196 const CvFileStorage* fs;
4197 const CvFileNode* node;
4204 The class is used for iterating sequences (usually) and mappings.
4206 class CV_EXPORTS FileNodeIterator
4209 //! the default constructor
4211 //! the full constructor set to the ofs-th element of the node
4212 FileNodeIterator(const CvFileStorage* fs, const CvFileNode* node, size_t ofs=0);
4213 //! the copy constructor
4214 FileNodeIterator(const FileNodeIterator& it);
4215 //! returns the currently observed element
4216 FileNode operator *() const;
4217 //! accesses the currently observed element methods
4218 FileNode operator ->() const;
4220 //! moves iterator to the next node
4221 FileNodeIterator& operator ++ ();
4222 //! moves iterator to the next node
4223 FileNodeIterator operator ++ (int);
4224 //! moves iterator to the previous node
4225 FileNodeIterator& operator -- ();
4226 //! moves iterator to the previous node
4227 FileNodeIterator operator -- (int);
4228 //! moves iterator forward by the specified offset (possibly negative)
4229 FileNodeIterator& operator += (int ofs);
4230 //! moves iterator backward by the specified offset (possibly negative)
4231 FileNodeIterator& operator -= (int ofs);
4233 //! reads the next maxCount elements (or less, if the sequence/mapping last element occurs earlier) to the buffer with the specified format
4234 FileNodeIterator& readRaw( const string& fmt, uchar* vec,
4235 size_t maxCount=(size_t)INT_MAX );
4237 const CvFileStorage* fs;
4238 const CvFileNode* container;
4243 ////////////// convenient wrappers for operating old-style dynamic structures //////////////
4245 template<typename _Tp> class SeqIterator;
4247 typedef Ptr<CvMemStorage> MemStorage;
4250 Template Sequence Class derived from CvSeq
4252 The class provides more convenient access to sequence elements,
4253 STL-style operations and iterators.
4255 \note The class is targeted for simple data types,
4256 i.e. no constructors or destructors
4257 are called for the sequence elements.
4259 template<typename _Tp> class CV_EXPORTS Seq
4262 typedef SeqIterator<_Tp> iterator;
4263 typedef SeqIterator<_Tp> const_iterator;
4265 //! the default constructor
4267 //! the constructor for wrapping CvSeq structure. The real element type in CvSeq should match _Tp.
4268 Seq(const CvSeq* seq);
4269 //! creates the empty sequence that resides in the specified storage
4270 Seq(MemStorage& storage, int headerSize = sizeof(CvSeq));
4271 //! returns read-write reference to the specified element
4272 _Tp& operator [](int idx);
4273 //! returns read-only reference to the specified element
4274 const _Tp& operator[](int idx) const;
4275 //! returns iterator pointing to the beginning of the sequence
4276 SeqIterator<_Tp> begin() const;
4277 //! returns iterator pointing to the element following the last sequence element
4278 SeqIterator<_Tp> end() const;
4279 //! returns the number of elements in the sequence
4280 size_t size() const;
4281 //! returns the type of sequence elements (CV_8UC1 ... CV_64FC(CV_CN_MAX) ...)
4283 //! returns the depth of sequence elements (CV_8U ... CV_64F)
4285 //! returns the number of channels in each sequence element
4286 int channels() const;
4287 //! returns the size of each sequence element
4288 size_t elemSize() const;
4289 //! returns index of the specified sequence element
4290 size_t index(const _Tp& elem) const;
4291 //! appends the specified element to the end of the sequence
4292 void push_back(const _Tp& elem);
4293 //! appends the specified element to the front of the sequence
4294 void push_front(const _Tp& elem);
4295 //! appends zero or more elements to the end of the sequence
4296 void push_back(const _Tp* elems, size_t count);
4297 //! appends zero or more elements to the front of the sequence
4298 void push_front(const _Tp* elems, size_t count);
4299 //! inserts the specified element to the specified position
4300 void insert(int idx, const _Tp& elem);
4301 //! inserts zero or more elements to the specified position
4302 void insert(int idx, const _Tp* elems, size_t count);
4303 //! removes element at the specified position
4304 void remove(int idx);
4305 //! removes the specified subsequence
4306 void remove(const Range& r);
4308 //! returns reference to the first sequence element
4310 //! returns read-only reference to the first sequence element
4311 const _Tp& front() const;
4312 //! returns reference to the last sequence element
4314 //! returns read-only reference to the last sequence element
4315 const _Tp& back() const;
4316 //! returns true iff the sequence contains no elements
4319 //! removes all the elements from the sequence
4321 //! removes the first element from the sequence
4323 //! removes the last element from the sequence
4325 //! removes zero or more elements from the beginning of the sequence
4326 void pop_front(_Tp* elems, size_t count);
4327 //! removes zero or more elements from the end of the sequence
4328 void pop_back(_Tp* elems, size_t count);
4330 //! copies the whole sequence or the sequence slice to the specified vector
4331 void copyTo(vector<_Tp>& vec, const Range& range=Range::all()) const;
4332 //! returns the vector containing all the sequence elements
4333 operator vector<_Tp>() const;
4340 STL-style Sequence Iterator inherited from the CvSeqReader structure
4342 template<typename _Tp> class CV_EXPORTS SeqIterator : public CvSeqReader
4345 //! the default constructor
4347 //! the constructor setting the iterator to the beginning or to the end of the sequence
4348 SeqIterator(const Seq<_Tp>& seq, bool seekEnd=false);
4349 //! positions the iterator within the sequence
4350 void seek(size_t pos);
4351 //! reports the current iterator position
4352 size_t tell() const;
4353 //! returns reference to the current sequence element
4355 //! returns read-only reference to the current sequence element
4356 const _Tp& operator *() const;
4357 //! moves iterator to the next sequence element
4358 SeqIterator& operator ++();
4359 //! moves iterator to the next sequence element
4360 SeqIterator operator ++(int) const;
4361 //! moves iterator to the previous sequence element
4362 SeqIterator& operator --();
4363 //! moves iterator to the previous sequence element
4364 SeqIterator operator --(int) const;
4366 //! moves iterator forward by the specified offset (possibly negative)
4367 SeqIterator& operator +=(int);
4368 //! moves iterator backward by the specified offset (possibly negative)
4369 SeqIterator& operator -=(int);
4371 // this is index of the current element module seq->total*2
4372 // (to distinguish between 0 and seq->total)
4377 class CV_EXPORTS Algorithm;
4378 class CV_EXPORTS AlgorithmInfo;
4379 struct CV_EXPORTS AlgorithmInfoData;
4381 template<typename _Tp> struct ParamType {};
4384 Base class for high-level OpenCV algorithms
4386 class CV_EXPORTS_W Algorithm
4390 virtual ~Algorithm();
4391 string name() const;
4393 template<typename _Tp> typename ParamType<_Tp>::member_type get(const string& name) const;
4394 template<typename _Tp> typename ParamType<_Tp>::member_type get(const char* name) const;
4396 CV_WRAP int getInt(const string& name) const;
4397 CV_WRAP double getDouble(const string& name) const;
4398 CV_WRAP bool getBool(const string& name) const;
4399 CV_WRAP string getString(const string& name) const;
4400 CV_WRAP Mat getMat(const string& name) const;
4401 CV_WRAP vector<Mat> getMatVector(const string& name) const;
4402 CV_WRAP Ptr<Algorithm> getAlgorithm(const string& name) const;
4404 void set(const string& name, int value);
4405 void set(const string& name, double value);
4406 void set(const string& name, bool value);
4407 void set(const string& name, const string& value);
4408 void set(const string& name, const Mat& value);
4409 void set(const string& name, const vector<Mat>& value);
4410 void set(const string& name, const Ptr<Algorithm>& value);
4411 template<typename _Tp> void set(const string& name, const Ptr<_Tp>& value);
4413 CV_WRAP void setInt(const string& name, int value);
4414 CV_WRAP void setDouble(const string& name, double value);
4415 CV_WRAP void setBool(const string& name, bool value);
4416 CV_WRAP void setString(const string& name, const string& value);
4417 CV_WRAP void setMat(const string& name, const Mat& value);
4418 CV_WRAP void setMatVector(const string& name, const vector<Mat>& value);
4419 CV_WRAP void setAlgorithm(const string& name, const Ptr<Algorithm>& value);
4420 template<typename _Tp> void setAlgorithm(const string& name, const Ptr<_Tp>& value);
4422 void set(const char* name, int value);
4423 void set(const char* name, double value);
4424 void set(const char* name, bool value);
4425 void set(const char* name, const string& value);
4426 void set(const char* name, const Mat& value);
4427 void set(const char* name, const vector<Mat>& value);
4428 void set(const char* name, const Ptr<Algorithm>& value);
4429 template<typename _Tp> void set(const char* name, const Ptr<_Tp>& value);
4431 void setInt(const char* name, int value);
4432 void setDouble(const char* name, double value);
4433 void setBool(const char* name, bool value);
4434 void setString(const char* name, const string& value);
4435 void setMat(const char* name, const Mat& value);
4436 void setMatVector(const char* name, const vector<Mat>& value);
4437 void setAlgorithm(const char* name, const Ptr<Algorithm>& value);
4438 template<typename _Tp> void setAlgorithm(const char* name, const Ptr<_Tp>& value);
4440 CV_WRAP string paramHelp(const string& name) const;
4441 int paramType(const char* name) const;
4442 CV_WRAP int paramType(const string& name) const;
4443 CV_WRAP void getParams(CV_OUT vector<string>& names) const;
4446 virtual void write(FileStorage& fs) const;
4447 virtual void read(const FileNode& fn);
4449 typedef Algorithm* (*Constructor)(void);
4450 typedef int (Algorithm::*Getter)() const;
4451 typedef void (Algorithm::*Setter)(int);
4453 CV_WRAP static void getList(CV_OUT vector<string>& algorithms);
4454 CV_WRAP static Ptr<Algorithm> _create(const string& name);
4455 template<typename _Tp> static Ptr<_Tp> create(const string& name);
4457 virtual AlgorithmInfo* info() const /* TODO: make it = 0;*/ { return 0; }
4461 class CV_EXPORTS AlgorithmInfo
4464 friend class Algorithm;
4465 AlgorithmInfo(const string& name, Algorithm::Constructor create);
4467 void get(const Algorithm* algo, const char* name, int argType, void* value) const;
4468 void addParam_(Algorithm& algo, const char* name, int argType,
4469 void* value, bool readOnly,
4470 Algorithm::Getter getter, Algorithm::Setter setter,
4471 const string& help=string());
4472 string paramHelp(const char* name) const;
4473 int paramType(const char* name) const;
4474 void getParams(vector<string>& names) const;
4476 void write(const Algorithm* algo, FileStorage& fs) const;
4477 void read(Algorithm* algo, const FileNode& fn) const;
4478 string name() const;
4480 void addParam(Algorithm& algo, const char* name,
4481 int& value, bool readOnly=false,
4482 int (Algorithm::*getter)()=0,
4483 void (Algorithm::*setter)(int)=0,
4484 const string& help=string());
4485 void addParam(Algorithm& algo, const char* name,
4486 short& value, bool readOnly=false,
4487 int (Algorithm::*getter)()=0,
4488 void (Algorithm::*setter)(int)=0,
4489 const string& help=string());
4490 void addParam(Algorithm& algo, const char* name,
4491 bool& value, bool readOnly=false,
4492 int (Algorithm::*getter)()=0,
4493 void (Algorithm::*setter)(int)=0,
4494 const string& help=string());
4495 void addParam(Algorithm& algo, const char* name,
4496 double& value, bool readOnly=false,
4497 double (Algorithm::*getter)()=0,
4498 void (Algorithm::*setter)(double)=0,
4499 const string& help=string());
4500 void addParam(Algorithm& algo, const char* name,
4501 string& value, bool readOnly=false,
4502 string (Algorithm::*getter)()=0,
4503 void (Algorithm::*setter)(const string&)=0,
4504 const string& help=string());
4505 void addParam(Algorithm& algo, const char* name,
4506 Mat& value, bool readOnly=false,
4507 Mat (Algorithm::*getter)()=0,
4508 void (Algorithm::*setter)(const Mat&)=0,
4509 const string& help=string());
4510 void addParam(Algorithm& algo, const char* name,
4511 vector<Mat>& value, bool readOnly=false,
4512 vector<Mat> (Algorithm::*getter)()=0,
4513 void (Algorithm::*setter)(const vector<Mat>&)=0,
4514 const string& help=string());
4515 void addParam(Algorithm& algo, const char* name,
4516 Ptr<Algorithm>& value, bool readOnly=false,
4517 Ptr<Algorithm> (Algorithm::*getter)()=0,
4518 void (Algorithm::*setter)(const Ptr<Algorithm>&)=0,
4519 const string& help=string());
4520 void addParam(Algorithm& algo, const char* name,
4521 float& value, bool readOnly=false,
4522 float (Algorithm::*getter)()=0,
4523 void (Algorithm::*setter)(float)=0,
4524 const string& help=string());
4525 void addParam(Algorithm& algo, const char* name,
4526 unsigned int& value, bool readOnly=false,
4527 unsigned int (Algorithm::*getter)()=0,
4528 void (Algorithm::*setter)(unsigned int)=0,
4529 const string& help=string());
4530 void addParam(Algorithm& algo, const char* name,
4531 uint64& value, bool readOnly=false,
4532 uint64 (Algorithm::*getter)()=0,
4533 void (Algorithm::*setter)(uint64)=0,
4534 const string& help=string());
4535 void addParam(Algorithm& algo, const char* name,
4536 uchar& value, bool readOnly=false,
4537 uchar (Algorithm::*getter)()=0,
4538 void (Algorithm::*setter)(uchar)=0,
4539 const string& help=string());
4540 template<typename _Tp, typename _Base> void addParam(Algorithm& algo, const char* name,
4541 Ptr<_Tp>& value, bool readOnly=false,
4542 Ptr<_Tp> (Algorithm::*getter)()=0,
4543 void (Algorithm::*setter)(const Ptr<_Tp>&)=0,
4544 const string& help=string());
4545 template<typename _Tp> void addParam(Algorithm& algo, const char* name,
4546 Ptr<_Tp>& value, bool readOnly=false,
4547 Ptr<_Tp> (Algorithm::*getter)()=0,
4548 void (Algorithm::*setter)(const Ptr<_Tp>&)=0,
4549 const string& help=string());
4551 AlgorithmInfoData* data;
4552 void set(Algorithm* algo, const char* name, int argType,
4553 const void* value, bool force=false) const;
4557 struct CV_EXPORTS Param
4559 enum { INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7, UNSIGNED_INT=8, UINT64=9, SHORT=10, UCHAR=11 };
4562 Param(int _type, bool _readonly, int _offset,
4563 Algorithm::Getter _getter=0,
4564 Algorithm::Setter _setter=0,
4565 const string& _help=string());
4569 Algorithm::Getter getter;
4570 Algorithm::Setter setter;
4574 template<> struct ParamType<bool>
4576 typedef bool const_param_type;
4577 typedef bool member_type;
4579 enum { type = Param::BOOLEAN };
4582 template<> struct ParamType<int>
4584 typedef int const_param_type;
4585 typedef int member_type;
4587 enum { type = Param::INT };
4590 template<> struct ParamType<short>
4592 typedef int const_param_type;
4593 typedef int member_type;
4595 enum { type = Param::SHORT };
4598 template<> struct ParamType<double>
4600 typedef double const_param_type;
4601 typedef double member_type;
4603 enum { type = Param::REAL };
4606 template<> struct ParamType<string>
4608 typedef const string& const_param_type;
4609 typedef string member_type;
4611 enum { type = Param::STRING };
4614 template<> struct ParamType<Mat>
4616 typedef const Mat& const_param_type;
4617 typedef Mat member_type;
4619 enum { type = Param::MAT };
4622 template<> struct ParamType<vector<Mat> >
4624 typedef const vector<Mat>& const_param_type;
4625 typedef vector<Mat> member_type;
4627 enum { type = Param::MAT_VECTOR };
4630 template<> struct ParamType<Algorithm>
4632 typedef const Ptr<Algorithm>& const_param_type;
4633 typedef Ptr<Algorithm> member_type;
4635 enum { type = Param::ALGORITHM };
4638 template<> struct ParamType<float>
4640 typedef float const_param_type;
4641 typedef float member_type;
4643 enum { type = Param::FLOAT };
4646 template<> struct ParamType<unsigned>
4648 typedef unsigned const_param_type;
4649 typedef unsigned member_type;
4651 enum { type = Param::UNSIGNED_INT };
4654 template<> struct ParamType<uint64>
4656 typedef uint64 const_param_type;
4657 typedef uint64 member_type;
4659 enum { type = Param::UINT64 };
4662 template<> struct ParamType<uchar>
4664 typedef uchar const_param_type;
4665 typedef uchar member_type;
4667 enum { type = Param::UCHAR };
4671 "\nThe CommandLineParser class is designed for command line arguments parsing\n"
4673 "Before you start to work with CommandLineParser you have to create a map for keys.\n"
4674 " It will look like this\n"
4675 " const char* keys =\n"
4677 " { s| string| 123asd |string parameter}\n"
4678 " { d| digit | 100 |digit parameter }\n"
4679 " { c|noCamera|false |without camera }\n"
4680 " { 1| |some text|help }\n"
4681 " { 2| |333 |another help }\n"
4684 " \"{\" - start of parameter string.\n"
4685 " \"}\" - end of parameter string\n"
4686 " \"|\" - separator between short name, full name, default value and help\n"
4687 "Supported syntax: \n"
4688 " --key1=arg1 <If a key with '--' must has an argument\n"
4689 " you have to assign it through '=' sign.> \n"
4690 "<If the key with '--' doesn't have any argument, it means that it is a bool key>\n"
4691 " -key2=arg2 <If a key with '-' must has an argument \n"
4692 " you have to assign it through '=' sign.> \n"
4693 "If the key with '-' doesn't have any argument, it means that it is a bool key\n"
4694 " key3 <This key can't has any parameter> \n"
4696 " Imagine that the input parameters are next:\n"
4697 " -s=string_value --digit=250 --noCamera lena.jpg 10000\n"
4698 " CommandLineParser parser(argc, argv, keys) - create a parser object\n"
4699 " parser.get<string>(\"s\" or \"string\") will return you first parameter value\n"
4700 " parser.get<string>(\"s\", false or \"string\", false) will return you first parameter value\n"
4701 " without spaces in end and begin\n"
4702 " parser.get<int>(\"d\" or \"digit\") will return you second parameter value.\n"
4703 " It also works with 'unsigned int', 'double', and 'float' types>\n"
4704 " parser.get<bool>(\"c\" or \"noCamera\") will return you true .\n"
4705 " If you enter this key in commandline>\n"
4706 " It return you false otherwise.\n"
4707 " parser.get<string>(\"1\") will return you the first argument without parameter (lena.jpg) \n"
4708 " parser.get<int>(\"2\") will return you the second argument without parameter (10000)\n"
4709 " It also works with 'unsigned int', 'double', and 'float' types \n"
4711 class CV_EXPORTS CommandLineParser
4715 //! the default constructor
4716 CommandLineParser(int argc, const char* const argv[], const char* key_map);
4718 //! get parameter, you can choose: delete spaces in end and begin or not
4719 template<typename _Tp>
4720 _Tp get(const std::string& name, bool space_delete=true)
4726 std::string str = getString(name);
4727 return analyzeValue<_Tp>(str, space_delete);
4730 //! print short name, full name, current value and help for all params
4734 std::map<std::string, std::vector<std::string> > data;
4735 std::string getString(const std::string& name);
4737 bool has(const std::string& keys);
4739 template<typename _Tp>
4740 _Tp analyzeValue(const std::string& str, bool space_delete=false);
4742 template<typename _Tp>
4743 static _Tp getData(const std::string& str)
4746 std::stringstream s1(str);
4751 template<typename _Tp>
4752 _Tp fromStringNumber(const std::string& str);//the default conversion function for numbers
4756 template<> CV_EXPORTS
4757 bool CommandLineParser::get<bool>(const std::string& name, bool space_delete);
4759 template<> CV_EXPORTS
4760 std::string CommandLineParser::analyzeValue<std::string>(const std::string& str, bool space_delete);
4762 template<> CV_EXPORTS
4763 int CommandLineParser::analyzeValue<int>(const std::string& str, bool space_delete);
4765 template<> CV_EXPORTS
4766 unsigned int CommandLineParser::analyzeValue<unsigned int>(const std::string& str, bool space_delete);
4768 template<> CV_EXPORTS
4769 uint64 CommandLineParser::analyzeValue<uint64>(const std::string& str, bool space_delete);
4771 template<> CV_EXPORTS
4772 float CommandLineParser::analyzeValue<float>(const std::string& str, bool space_delete);
4774 template<> CV_EXPORTS
4775 double CommandLineParser::analyzeValue<double>(const std::string& str, bool space_delete);
4778 /////////////////////////////// Parallel Primitives //////////////////////////////////
4780 // a base body class
4781 class CV_EXPORTS ParallelLoopBody
4784 virtual ~ParallelLoopBody();
4785 virtual void operator() (const Range& range) const = 0;
4788 CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.);
4790 /////////////////////////// Synchronization Primitives ///////////////////////////////
4792 class CV_EXPORTS Mutex
4797 Mutex(const Mutex& m);
4798 Mutex& operator = (const Mutex& m);
4809 class CV_EXPORTS AutoLock
4812 AutoLock(Mutex& m) : mutex(&m) { mutex->lock(); }
4813 ~AutoLock() { mutex->unlock(); }
4817 AutoLock(const AutoLock&);
4818 AutoLock& operator = (const AutoLock&);
4823 #endif // __cplusplus
4825 #include "opencv2/core/operations.hpp"
4826 #include "opencv2/core/mat.hpp"
4828 #endif /*__OPENCV_CORE_HPP__*/