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 Size_;
82 template<typename _Tp> class Point_;
83 template<typename _Tp> class Rect_;
84 template<typename _Tp, int cn> class Vec;
85 template<typename _Tp, int m, int n> class 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 Mat_;
116 template<typename _Tp> class MatIterator_;
117 template<typename _Tp> class MatConstIterator_;
118 template<typename _Tp> class 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 getting it
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);
214 #define CV_Func __func__
215 #elif defined _MSC_VER
216 #define CV_Func __FUNCTION__
221 #define CV_Error( code, msg ) cv::error( cv::Exception(code, msg, CV_Func, __FILE__, __LINE__) )
222 #define CV_Error_( code, args ) cv::error( cv::Exception(code, cv::format args, CV_Func, __FILE__, __LINE__) )
223 #define CV_Assert( expr ) if(!!(expr)) ; else cv::error( cv::Exception(CV_StsAssert, #expr, CV_Func, __FILE__, __LINE__) )
226 #define CV_DbgAssert(expr) CV_Assert(expr)
228 #define CV_DbgAssert(expr)
231 CV_EXPORTS void glob(String pattern, std::vector<String>& result, bool recursive = false);
233 CV_EXPORTS void setNumThreads(int nthreads);
234 CV_EXPORTS int getNumThreads();
235 CV_EXPORTS int getThreadNum();
237 CV_EXPORTS_W const string& getBuildInformation();
239 //! Returns the number of ticks.
242 The function returns the number of ticks since the certain event (e.g. when the machine was turned on).
243 It can be used to initialize cv::RNG or to measure a function execution time by reading the tick count
244 before and after the function call. The granularity of ticks depends on the hardware and OS used. Use
245 cv::getTickFrequency() to convert ticks to seconds.
247 CV_EXPORTS_W int64 getTickCount();
250 Returns the number of ticks per seconds.
252 The function returns the number of ticks (as returned by cv::getTickCount()) per second.
253 The following code computes the execution time in milliseconds:
256 double exec_time = (double)getTickCount();
258 exec_time = ((double)getTickCount() - exec_time)*1000./getTickFrequency();
261 CV_EXPORTS_W double getTickFrequency();
264 Returns the number of CPU ticks.
266 On platforms where the feature is available, the function returns the number of CPU ticks
267 since the certain event (normally, the system power-on moment). Using this function
268 one can accurately measure the execution time of very small code fragments,
269 for which cv::getTickCount() granularity is not enough.
271 CV_EXPORTS_W int64 getCPUTickCount();
274 Returns SSE etc. support status
276 The function returns true if certain hardware features are available.
277 Currently, the following features are recognized:
280 - CV_CPU_SSE2 - SSE 2
281 - CV_CPU_SSE3 - SSE 3
282 - CV_CPU_SSSE3 - SSSE 3
283 - CV_CPU_SSE4_1 - SSE 4.1
284 - CV_CPU_SSE4_2 - SSE 4.2
285 - CV_CPU_POPCNT - POPCOUNT
288 \note {Note that the function output is not static. Once you called cv::useOptimized(false),
289 most of the hardware acceleration is disabled and thus the function will returns false,
290 until you call cv::useOptimized(true)}
292 CV_EXPORTS_W bool checkHardwareSupport(int feature);
294 //! returns the number of CPUs (including hyper-threading)
295 CV_EXPORTS_W int getNumberOfCPUs();
298 Allocates memory buffer
300 This is specialized OpenCV memory allocation function that returns properly aligned memory buffers.
301 The usage is identical to malloc(). The allocated buffers must be freed with cv::fastFree().
302 If there is not enough memory, the function calls cv::error(), which raises an exception.
304 \param bufSize buffer size in bytes
305 \return the allocated memory buffer.
307 CV_EXPORTS void* fastMalloc(size_t bufSize);
310 Frees the memory allocated with cv::fastMalloc
312 This is the corresponding deallocation function for cv::fastMalloc().
313 When ptr==NULL, the function has no effect.
315 CV_EXPORTS void fastFree(void* ptr);
317 template<typename _Tp> static inline _Tp* allocate(size_t n)
322 template<typename _Tp> static inline void deallocate(_Tp* ptr, size_t)
328 Aligns pointer by the certain number of bytes
330 This small inline function aligns the pointer by the certian number of bytes by shifting
331 it forward by 0 or a positive offset.
333 template<typename _Tp> static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp))
335 return (_Tp*)(((size_t)ptr + n-1) & -n);
339 Aligns buffer size by the certain number of bytes
341 This small inline function aligns a buffer size by the certian number of bytes by enlarging it.
343 static inline size_t alignSize(size_t sz, int n)
345 assert((n & (n - 1)) == 0); // n is a power of 2
346 return (sz + n-1) & -n;
350 Turns on/off available optimization
352 The function turns on or off the optimized code in OpenCV. Some optimization can not be enabled
353 or disabled, but, for example, most of SSE code in OpenCV can be temporarily turned on or off this way.
355 \note{Since optimization may imply using special data structures, it may be unsafe
356 to call this function anywhere in the code. Instead, call it somewhere at the top level.}
358 CV_EXPORTS_W void setUseOptimized(bool onoff);
361 Returns the current optimization status
363 The function returns the current optimization status, which is controlled by cv::setUseOptimized().
365 CV_EXPORTS_W bool useOptimized();
368 The STL-compilant memory Allocator based on cv::fastMalloc() and cv::fastFree()
370 template<typename _Tp> class Allocator
373 typedef _Tp value_type;
374 typedef value_type* pointer;
375 typedef const value_type* const_pointer;
376 typedef value_type& reference;
377 typedef const value_type& const_reference;
378 typedef size_t size_type;
379 typedef ptrdiff_t difference_type;
380 template<typename U> class rebind { typedef Allocator<U> other; };
382 explicit Allocator() {}
384 explicit Allocator(Allocator const&) {}
386 explicit Allocator(Allocator<U> const&) {}
389 pointer address(reference r) { return &r; }
390 const_pointer address(const_reference r) { return &r; }
392 pointer allocate(size_type count, const void* =0)
393 { return reinterpret_cast<pointer>(fastMalloc(count * sizeof (_Tp))); }
395 void deallocate(pointer p, size_type) {fastFree(p); }
397 size_type max_size() const
398 { return max(static_cast<_Tp>(-1)/sizeof(_Tp), 1); }
400 void construct(pointer p, const _Tp& v) { new(static_cast<void*>(p)) _Tp(v); }
401 void destroy(pointer p) { p->~_Tp(); }
404 /////////////////////// Vec (used as element of multi-channel images /////////////////////
407 A helper class for cv::DataType
409 The class is specialized for each fundamental numerical data type supported by OpenCV.
410 It provides DataDepth<T>::value constant.
412 template<typename _Tp> class DataDepth {};
414 template<> class DataDepth<bool> { public: enum { value = CV_8U, fmt=(int)'u' }; };
415 template<> class DataDepth<uchar> { public: enum { value = CV_8U, fmt=(int)'u' }; };
416 template<> class DataDepth<schar> { public: enum { value = CV_8S, fmt=(int)'c' }; };
417 template<> class DataDepth<char> { public: enum { value = CV_8S, fmt=(int)'c' }; };
418 template<> class DataDepth<ushort> { public: enum { value = CV_16U, fmt=(int)'w' }; };
419 template<> class DataDepth<short> { public: enum { value = CV_16S, fmt=(int)'s' }; };
420 template<> class DataDepth<int> { public: enum { value = CV_32S, fmt=(int)'i' }; };
421 // this is temporary solution to support 32-bit unsigned integers
422 template<> class DataDepth<unsigned> { public: enum { value = CV_32S, fmt=(int)'i' }; };
423 template<> class DataDepth<float> { public: enum { value = CV_32F, fmt=(int)'f' }; };
424 template<> class DataDepth<double> { public: enum { value = CV_64F, fmt=(int)'d' }; };
425 template<typename _Tp> class DataDepth<_Tp*> { public: enum { value = CV_USRTYPE1, fmt=(int)'r' }; };
428 ////////////////////////////// Small Matrix ///////////////////////////
431 A short numerical vector.
433 This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements)
434 on which you can perform basic arithmetical operations, access individual elements using [] operator etc.
435 The vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc.,
436 which elements are dynamically allocated in the heap.
438 The template takes 2 parameters:
440 -# cn the number of elements
442 In addition to the universal notation like Vec<float, 3>, you can use shorter aliases
443 for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec<float, 3>.
446 struct CV_EXPORTS Matx_AddOp {};
447 struct CV_EXPORTS Matx_SubOp {};
448 struct CV_EXPORTS Matx_ScaleOp {};
449 struct CV_EXPORTS Matx_MulOp {};
450 struct CV_EXPORTS Matx_MatMulOp {};
451 struct CV_EXPORTS Matx_TOp {};
453 template<typename _Tp, int m, int n> class Matx
456 typedef _Tp value_type;
457 typedef Matx<_Tp, (m < n ? m : n), 1> diag_type;
458 typedef Matx<_Tp, m, n> mat_type;
459 enum { depth = DataDepth<_Tp>::value, rows = m, cols = n, channels = rows*cols,
460 type = CV_MAKETYPE(depth, channels) };
462 //! default constructor
465 Matx(_Tp v0); //!< 1x1 matrix
466 Matx(_Tp v0, _Tp v1); //!< 1x2 or 2x1 matrix
467 Matx(_Tp v0, _Tp v1, _Tp v2); //!< 1x3 or 3x1 matrix
468 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 1x4, 2x2 or 4x1 matrix
469 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 1x5 or 5x1 matrix
470 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 1x6, 2x3, 3x2 or 6x1 matrix
471 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 1x7 or 7x1 matrix
472 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 1x8, 2x4, 4x2 or 8x1 matrix
473 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 1x9, 3x3 or 9x1 matrix
474 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
475 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3,
476 _Tp v4, _Tp v5, _Tp v6, _Tp v7,
477 _Tp v8, _Tp v9, _Tp v10, _Tp v11); //!< 1x12, 2x6, 3x4, 4x3, 6x2 or 12x1 matrix
478 Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3,
479 _Tp v4, _Tp v5, _Tp v6, _Tp v7,
480 _Tp v8, _Tp v9, _Tp v10, _Tp v11,
481 _Tp v12, _Tp v13, _Tp v14, _Tp v15); //!< 1x16, 4x4 or 16x1 matrix
482 explicit Matx(const _Tp* vals); //!< initialize from a plain array
484 static Matx all(_Tp alpha);
488 static Matx diag(const diag_type& d);
489 static Matx randu(_Tp a, _Tp b);
490 static Matx randn(_Tp a, _Tp b);
492 //! dot product computed with the default precision
493 _Tp dot(const Matx<_Tp, m, n>& v) const;
495 //! dot product computed in double-precision arithmetics
496 double ddot(const Matx<_Tp, m, n>& v) const;
498 //! convertion to another data type
499 template<typename T2> operator Matx<T2, m, n>() const;
501 //! change the matrix shape
502 template<int m1, int n1> Matx<_Tp, m1, n1> reshape() const;
504 //! extract part of the matrix
505 template<int m1, int n1> Matx<_Tp, m1, n1> get_minor(int i, int j) const;
507 //! extract the matrix row
508 Matx<_Tp, 1, n> row(int i) const;
510 //! extract the matrix column
511 Matx<_Tp, m, 1> col(int i) const;
513 //! extract the matrix diagonal
514 diag_type diag() const;
516 //! transpose the matrix
517 Matx<_Tp, n, m> t() const;
519 //! invert matrix the matrix
520 Matx<_Tp, n, m> inv(int method=DECOMP_LU) const;
522 //! solve linear system
523 template<int l> Matx<_Tp, n, l> solve(const Matx<_Tp, m, l>& rhs, int flags=DECOMP_LU) const;
524 Vec<_Tp, n> solve(const Vec<_Tp, m>& rhs, int method) const;
526 //! multiply two matrices element-wise
527 Matx<_Tp, m, n> mul(const Matx<_Tp, m, n>& a) const;
530 const _Tp& operator ()(int i, int j) const;
531 _Tp& operator ()(int i, int j);
533 //! 1D element access
534 const _Tp& operator ()(int i) const;
535 _Tp& operator ()(int i);
537 Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp);
538 Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp);
539 template<typename _T2> Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp);
540 Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp);
541 template<int l> Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp);
542 Matx(const Matx<_Tp, n, m>& a, Matx_TOp);
544 _Tp val[m*n]; //< matrix elements
548 typedef Matx<float, 1, 2> Matx12f;
549 typedef Matx<double, 1, 2> Matx12d;
550 typedef Matx<float, 1, 3> Matx13f;
551 typedef Matx<double, 1, 3> Matx13d;
552 typedef Matx<float, 1, 4> Matx14f;
553 typedef Matx<double, 1, 4> Matx14d;
554 typedef Matx<float, 1, 6> Matx16f;
555 typedef Matx<double, 1, 6> Matx16d;
557 typedef Matx<float, 2, 1> Matx21f;
558 typedef Matx<double, 2, 1> Matx21d;
559 typedef Matx<float, 3, 1> Matx31f;
560 typedef Matx<double, 3, 1> Matx31d;
561 typedef Matx<float, 4, 1> Matx41f;
562 typedef Matx<double, 4, 1> Matx41d;
563 typedef Matx<float, 6, 1> Matx61f;
564 typedef Matx<double, 6, 1> Matx61d;
566 typedef Matx<float, 2, 2> Matx22f;
567 typedef Matx<double, 2, 2> Matx22d;
568 typedef Matx<float, 2, 3> Matx23f;
569 typedef Matx<double, 2, 3> Matx23d;
570 typedef Matx<float, 3, 2> Matx32f;
571 typedef Matx<double, 3, 2> Matx32d;
573 typedef Matx<float, 3, 3> Matx33f;
574 typedef Matx<double, 3, 3> Matx33d;
576 typedef Matx<float, 3, 4> Matx34f;
577 typedef Matx<double, 3, 4> Matx34d;
578 typedef Matx<float, 4, 3> Matx43f;
579 typedef Matx<double, 4, 3> Matx43d;
581 typedef Matx<float, 4, 4> Matx44f;
582 typedef Matx<double, 4, 4> Matx44d;
583 typedef Matx<float, 6, 6> Matx66f;
584 typedef Matx<double, 6, 6> Matx66d;
588 A short numerical vector.
590 This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements)
591 on which you can perform basic arithmetical operations, access individual elements using [] operator etc.
592 The vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc.,
593 which elements are dynamically allocated in the heap.
595 The template takes 2 parameters:
597 -# cn the number of elements
599 In addition to the universal notation like Vec<float, 3>, you can use shorter aliases
600 for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec<float, 3>.
602 template<typename _Tp, int cn> class Vec : public Matx<_Tp, cn, 1>
605 typedef _Tp value_type;
606 enum { depth = DataDepth<_Tp>::value, channels = cn, type = CV_MAKETYPE(depth, channels) };
608 //! default constructor
611 Vec(_Tp v0); //!< 1-element vector constructor
612 Vec(_Tp v0, _Tp v1); //!< 2-element vector constructor
613 Vec(_Tp v0, _Tp v1, _Tp v2); //!< 3-element vector constructor
614 Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 4-element vector constructor
615 Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 5-element vector constructor
616 Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 6-element vector constructor
617 Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 7-element vector constructor
618 Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 8-element vector constructor
619 Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 9-element vector constructor
620 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
621 explicit Vec(const _Tp* values);
623 Vec(const Vec<_Tp, cn>& v);
625 static Vec all(_Tp alpha);
627 //! per-element multiplication
628 Vec mul(const Vec<_Tp, cn>& v) const;
630 //! conjugation (makes sense for complex numbers and quaternions)
634 cross product of the two 3D vectors.
636 For other dimensionalities the exception is raised
638 Vec cross(const Vec& v) const;
639 //! convertion to another data type
640 template<typename T2> operator Vec<T2, cn>() const;
641 //! conversion to 4-element CvScalar.
642 operator CvScalar() const;
644 /*! element access */
645 const _Tp& operator [](int i) const;
646 _Tp& operator[](int i);
647 const _Tp& operator ()(int i) const;
648 _Tp& operator ()(int i);
650 Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp);
651 Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp);
652 template<typename _T2> Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp);
658 Shorter aliases for the most popular specializations of Vec<T,n>
660 typedef Vec<uchar, 2> Vec2b;
661 typedef Vec<uchar, 3> Vec3b;
662 typedef Vec<uchar, 4> Vec4b;
664 typedef Vec<short, 2> Vec2s;
665 typedef Vec<short, 3> Vec3s;
666 typedef Vec<short, 4> Vec4s;
668 typedef Vec<ushort, 2> Vec2w;
669 typedef Vec<ushort, 3> Vec3w;
670 typedef Vec<ushort, 4> Vec4w;
672 typedef Vec<int, 2> Vec2i;
673 typedef Vec<int, 3> Vec3i;
674 typedef Vec<int, 4> Vec4i;
675 typedef Vec<int, 6> Vec6i;
676 typedef Vec<int, 8> Vec8i;
678 typedef Vec<float, 2> Vec2f;
679 typedef Vec<float, 3> Vec3f;
680 typedef Vec<float, 4> Vec4f;
681 typedef Vec<float, 6> Vec6f;
683 typedef Vec<double, 2> Vec2d;
684 typedef Vec<double, 3> Vec3d;
685 typedef Vec<double, 4> Vec4d;
686 typedef Vec<double, 6> Vec6d;
689 //////////////////////////////// Complex //////////////////////////////
692 A complex number class.
694 The template class is similar and compatible with std::complex, however it provides slightly
695 more convenient access to the real and imaginary parts using through the simple field access, as opposite
696 to std::complex::real() and std::complex::imag().
698 template<typename _Tp> class Complex
704 Complex( _Tp _re, _Tp _im=0 );
705 Complex( const std::complex<_Tp>& c );
707 //! conversion to another data type
708 template<typename T2> operator Complex<T2>() const;
710 Complex conj() const;
711 //! conversion to std::complex
712 operator std::complex<_Tp>() const;
714 _Tp re, im; //< the real and the imaginary parts
721 typedef Complex<float> Complexf;
722 typedef Complex<double> Complexd;
725 //////////////////////////////// Point_ ////////////////////////////////
728 template 2D point class.
730 The class defines a point in 2D space. Data type of the point coordinates is specified
731 as a template parameter. There are a few shorter aliases available for user convenience.
732 See cv::Point, cv::Point2i, cv::Point2f and cv::Point2d.
734 template<typename _Tp> class Point_
737 typedef _Tp value_type;
739 // various constructors
741 Point_(_Tp _x, _Tp _y);
742 Point_(const Point_& pt);
743 Point_(const CvPoint& pt);
744 Point_(const CvPoint2D32f& pt);
745 Point_(const Size_<_Tp>& sz);
746 Point_(const Vec<_Tp, 2>& v);
748 Point_& operator = (const Point_& pt);
749 //! conversion to another data type
750 template<typename _Tp2> operator Point_<_Tp2>() const;
752 //! conversion to the old-style C structures
753 operator CvPoint() const;
754 operator CvPoint2D32f() const;
755 operator Vec<_Tp, 2>() const;
758 _Tp dot(const Point_& pt) const;
759 //! dot product computed in double-precision arithmetics
760 double ddot(const Point_& pt) const;
762 double cross(const Point_& pt) const;
763 //! checks whether the point is inside the specified rectangle
764 bool inside(const Rect_<_Tp>& r) const;
766 _Tp x, y; //< the point coordinates
770 template 3D point class.
772 The class defines a point in 3D space. Data type of the point coordinates is specified
773 as a template parameter.
775 \see cv::Point3i, cv::Point3f and cv::Point3d
777 template<typename _Tp> class Point3_
780 typedef _Tp value_type;
782 // various constructors
784 Point3_(_Tp _x, _Tp _y, _Tp _z);
785 Point3_(const Point3_& pt);
786 explicit Point3_(const Point_<_Tp>& pt);
787 Point3_(const CvPoint3D32f& pt);
788 Point3_(const Vec<_Tp, 3>& v);
790 Point3_& operator = (const Point3_& pt);
791 //! conversion to another data type
792 template<typename _Tp2> operator Point3_<_Tp2>() const;
793 //! conversion to the old-style CvPoint...
794 operator CvPoint3D32f() const;
795 //! conversion to cv::Vec<>
796 operator Vec<_Tp, 3>() const;
799 _Tp dot(const Point3_& pt) const;
800 //! dot product computed in double-precision arithmetics
801 double ddot(const Point3_& pt) const;
802 //! cross product of the 2 3D points
803 Point3_ cross(const Point3_& pt) const;
805 _Tp x, y, z; //< the point coordinates
808 //////////////////////////////// Size_ ////////////////////////////////
813 The class represents the size of a 2D rectangle, image size, matrix size etc.
814 Normally, cv::Size ~ cv::Size_<int> is used.
816 template<typename _Tp> class Size_
819 typedef _Tp value_type;
821 //! various constructors
823 Size_(_Tp _width, _Tp _height);
824 Size_(const Size_& sz);
825 Size_(const CvSize& sz);
826 Size_(const CvSize2D32f& sz);
827 Size_(const Point_<_Tp>& pt);
829 Size_& operator = (const Size_& sz);
830 //! the area (width*height)
833 //! conversion of another data type.
834 template<typename _Tp2> operator Size_<_Tp2>() const;
836 //! conversion to the old-style OpenCV types
837 operator CvSize() const;
838 operator CvSize2D32f() const;
840 _Tp width, height; // the width and the height
843 //////////////////////////////// Rect_ ////////////////////////////////
846 The 2D up-right rectangle class
848 The class represents a 2D rectangle with coordinates of the specified data type.
849 Normally, cv::Rect ~ cv::Rect_<int> is used.
851 template<typename _Tp> class Rect_
854 typedef _Tp value_type;
856 //! various constructors
858 Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height);
859 Rect_(const Rect_& r);
860 Rect_(const CvRect& r);
861 Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz);
862 Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2);
864 Rect_& operator = ( const Rect_& r );
865 //! the top-left corner
866 Point_<_Tp> tl() const;
867 //! the bottom-right corner
868 Point_<_Tp> br() const;
870 //! size (width, height) of the rectangle
871 Size_<_Tp> size() const;
872 //! area (width*height) of the rectangle
875 //! conversion to another data type
876 template<typename _Tp2> operator Rect_<_Tp2>() const;
877 //! conversion to the old-style CvRect
878 operator CvRect() const;
880 //! checks whether the rectangle contains the point
881 bool contains(const Point_<_Tp>& pt) const;
883 _Tp x, y, width, height; //< the top-left corner, as well as width and height of the rectangle
890 shorter aliases for the most popular cv::Point_<>, cv::Size_<> and cv::Rect_<> specializations
892 typedef Point_<int> Point2i;
893 typedef Point2i Point;
894 typedef Size_<int> Size2i;
895 typedef Size_<double> Size2d;
897 typedef Rect_<int> Rect;
898 typedef Point_<float> Point2f;
899 typedef Point_<double> Point2d;
900 typedef Size_<float> Size2f;
901 typedef Point3_<int> Point3i;
902 typedef Point3_<float> Point3f;
903 typedef Point3_<double> Point3d;
907 The rotated 2D rectangle.
909 The class represents rotated (i.e. not up-right) rectangles on a plane.
910 Each rectangle is described by the center point (mass center), length of each side
911 (represented by cv::Size2f structure) and the rotation angle in degrees.
913 class CV_EXPORTS RotatedRect
916 //! various constructors
918 RotatedRect(const Point2f& center, const Size2f& size, float angle);
919 RotatedRect(const CvBox2D& box);
921 //! returns 4 vertices of the rectangle
922 void points(Point2f pts[]) const;
923 //! returns the minimal up-right rectangle containing the rotated rectangle
924 Rect boundingRect() const;
925 //! conversion to the old-style CvBox2D structure
926 operator CvBox2D() const;
928 Point2f center; //< the rectangle mass center
929 Size2f size; //< width and height of the rectangle
930 float angle; //< the rotation angle. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle.
933 //////////////////////////////// Scalar_ ///////////////////////////////
936 The template scalar class.
938 This is partially specialized cv::Vec class with the number of elements = 4, i.e. a short vector of four elements.
939 Normally, cv::Scalar ~ cv::Scalar_<double> is used.
941 template<typename _Tp> class Scalar_ : public Vec<_Tp, 4>
944 //! various constructors
946 Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0);
947 Scalar_(const CvScalar& s);
950 //! returns a scalar with all elements set to v0
951 static Scalar_<_Tp> all(_Tp v0);
952 //! conversion to the old-style CvScalar
953 operator CvScalar() const;
955 //! conversion to another data type
956 template<typename T2> operator Scalar_<T2>() const;
958 //! per-element product
959 Scalar_<_Tp> mul(const Scalar_<_Tp>& t, double scale=1 ) const;
961 // returns (v0, -v1, -v2, -v3)
962 Scalar_<_Tp> conj() const;
964 // returns true iff v1 == v2 == v3 == 0
968 typedef Scalar_<double> Scalar;
970 CV_EXPORTS void scalarToRawData(const Scalar& s, void* buf, int type, int unroll_to=0);
972 //////////////////////////////// Range /////////////////////////////////
977 This is the class used to specify a continuous subsequence, i.e. part of a contour, or a column span in a matrix.
979 class CV_EXPORTS Range
983 Range(int _start, int _end);
984 Range(const CvSlice& slice);
988 operator CvSlice() const;
993 /////////////////////////////// DataType ////////////////////////////////
996 Informative template class for OpenCV "scalars".
998 The class is specialized for each primitive numerical type supported by OpenCV (such as unsigned char or float),
999 as well as for more complex types, like cv::Complex<>, std::complex<>, cv::Vec<> etc.
1000 The common property of all such types (called "scalars", do not confuse it with cv::Scalar_)
1001 is that each of them is basically a tuple of numbers of the same type. Each "scalar" can be represented
1002 by the depth id (CV_8U ... CV_64F) and the number of channels.
1003 OpenCV matrices, 2D or nD, dense or sparse, can store "scalars",
1004 as long as the number of channels does not exceed CV_CN_MAX.
1006 template<typename _Tp> class DataType
1009 typedef _Tp value_type;
1010 typedef value_type work_type;
1011 typedef value_type channel_type;
1012 typedef value_type vec_type;
1013 enum { generic_type = 1, depth = -1, channels = 1, fmt=0,
1014 type = CV_MAKETYPE(depth, channels) };
1017 template<> class DataType<bool>
1020 typedef bool value_type;
1021 typedef int work_type;
1022 typedef value_type channel_type;
1023 typedef value_type vec_type;
1024 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1025 fmt=DataDepth<channel_type>::fmt,
1026 type = CV_MAKETYPE(depth, channels) };
1029 template<> class DataType<uchar>
1032 typedef uchar value_type;
1033 typedef int work_type;
1034 typedef value_type channel_type;
1035 typedef value_type vec_type;
1036 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1037 fmt=DataDepth<channel_type>::fmt,
1038 type = CV_MAKETYPE(depth, channels) };
1041 template<> class DataType<schar>
1044 typedef schar value_type;
1045 typedef int work_type;
1046 typedef value_type channel_type;
1047 typedef value_type vec_type;
1048 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1049 fmt=DataDepth<channel_type>::fmt,
1050 type = CV_MAKETYPE(depth, channels) };
1053 template<> class DataType<char>
1056 typedef schar value_type;
1057 typedef int work_type;
1058 typedef value_type channel_type;
1059 typedef value_type vec_type;
1060 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1061 fmt=DataDepth<channel_type>::fmt,
1062 type = CV_MAKETYPE(depth, channels) };
1065 template<> class DataType<ushort>
1068 typedef ushort value_type;
1069 typedef int work_type;
1070 typedef value_type channel_type;
1071 typedef value_type vec_type;
1072 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1073 fmt=DataDepth<channel_type>::fmt,
1074 type = CV_MAKETYPE(depth, channels) };
1077 template<> class DataType<short>
1080 typedef short value_type;
1081 typedef int work_type;
1082 typedef value_type channel_type;
1083 typedef value_type vec_type;
1084 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1085 fmt=DataDepth<channel_type>::fmt,
1086 type = CV_MAKETYPE(depth, channels) };
1089 template<> class DataType<int>
1092 typedef int value_type;
1093 typedef value_type work_type;
1094 typedef value_type channel_type;
1095 typedef value_type vec_type;
1096 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1097 fmt=DataDepth<channel_type>::fmt,
1098 type = CV_MAKETYPE(depth, channels) };
1101 template<> class DataType<float>
1104 typedef float value_type;
1105 typedef value_type work_type;
1106 typedef value_type channel_type;
1107 typedef value_type vec_type;
1108 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1109 fmt=DataDepth<channel_type>::fmt,
1110 type = CV_MAKETYPE(depth, channels) };
1113 template<> class DataType<double>
1116 typedef double value_type;
1117 typedef value_type work_type;
1118 typedef value_type channel_type;
1119 typedef value_type vec_type;
1120 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1121 fmt=DataDepth<channel_type>::fmt,
1122 type = CV_MAKETYPE(depth, channels) };
1125 template<typename _Tp, int m, int n> class DataType<Matx<_Tp, m, n> >
1128 typedef Matx<_Tp, m, n> value_type;
1129 typedef Matx<typename DataType<_Tp>::work_type, m, n> work_type;
1130 typedef _Tp channel_type;
1131 typedef value_type vec_type;
1132 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = m*n,
1133 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1134 type = CV_MAKETYPE(depth, channels) };
1137 template<typename _Tp, int cn> class DataType<Vec<_Tp, cn> >
1140 typedef Vec<_Tp, cn> value_type;
1141 typedef Vec<typename DataType<_Tp>::work_type, cn> work_type;
1142 typedef _Tp channel_type;
1143 typedef value_type vec_type;
1144 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = cn,
1145 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1146 type = CV_MAKETYPE(depth, channels) };
1149 template<typename _Tp> class DataType<std::complex<_Tp> >
1152 typedef std::complex<_Tp> value_type;
1153 typedef value_type work_type;
1154 typedef _Tp channel_type;
1155 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1156 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1157 type = CV_MAKETYPE(depth, channels) };
1158 typedef Vec<channel_type, channels> vec_type;
1161 template<typename _Tp> class DataType<Complex<_Tp> >
1164 typedef Complex<_Tp> value_type;
1165 typedef value_type work_type;
1166 typedef _Tp channel_type;
1167 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1168 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1169 type = CV_MAKETYPE(depth, channels) };
1170 typedef Vec<channel_type, channels> vec_type;
1173 template<typename _Tp> class DataType<Point_<_Tp> >
1176 typedef Point_<_Tp> value_type;
1177 typedef Point_<typename DataType<_Tp>::work_type> work_type;
1178 typedef _Tp channel_type;
1179 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1180 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1181 type = CV_MAKETYPE(depth, channels) };
1182 typedef Vec<channel_type, channels> vec_type;
1185 template<typename _Tp> class DataType<Point3_<_Tp> >
1188 typedef Point3_<_Tp> value_type;
1189 typedef Point3_<typename DataType<_Tp>::work_type> work_type;
1190 typedef _Tp channel_type;
1191 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 3,
1192 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1193 type = CV_MAKETYPE(depth, channels) };
1194 typedef Vec<channel_type, channels> vec_type;
1197 template<typename _Tp> class DataType<Size_<_Tp> >
1200 typedef Size_<_Tp> value_type;
1201 typedef Size_<typename DataType<_Tp>::work_type> work_type;
1202 typedef _Tp channel_type;
1203 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1204 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1205 type = CV_MAKETYPE(depth, channels) };
1206 typedef Vec<channel_type, channels> vec_type;
1209 template<typename _Tp> class DataType<Rect_<_Tp> >
1212 typedef Rect_<_Tp> value_type;
1213 typedef Rect_<typename DataType<_Tp>::work_type> work_type;
1214 typedef _Tp channel_type;
1215 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 4,
1216 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1217 type = CV_MAKETYPE(depth, channels) };
1218 typedef Vec<channel_type, channels> vec_type;
1221 template<typename _Tp> class DataType<Scalar_<_Tp> >
1224 typedef Scalar_<_Tp> value_type;
1225 typedef Scalar_<typename DataType<_Tp>::work_type> work_type;
1226 typedef _Tp channel_type;
1227 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 4,
1228 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1229 type = CV_MAKETYPE(depth, channels) };
1230 typedef Vec<channel_type, channels> vec_type;
1233 template<> class DataType<Range>
1236 typedef Range value_type;
1237 typedef value_type work_type;
1238 typedef int channel_type;
1239 enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1240 fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1241 type = CV_MAKETYPE(depth, channels) };
1242 typedef Vec<channel_type, channels> vec_type;
1245 //////////////////// generic_type ref-counting pointer class for C/C++ objects ////////////////////////
1248 Smart pointer to dynamically allocated objects.
1250 This is template pointer-wrapping class that stores the associated reference counter along with the
1251 object pointer. The class is similar to std::smart_ptr<> from the recent addons to the C++ standard,
1252 but is shorter to write :) and self-contained (i.e. does add any dependency on the compiler or an external library).
1254 Basically, you can use "Ptr<MyObjectType> ptr" (or faster "const Ptr<MyObjectType>& ptr" for read-only access)
1255 everywhere instead of "MyObjectType* ptr", where MyObjectType is some C structure or a C++ class.
1256 To make it all work, you need to specialize Ptr<>::delete_obj(), like:
1259 template<> void Ptr<MyObjectType>::delete_obj() { call_destructor_func(obj); }
1262 \note{if MyObjectType is a C++ class with a destructor, you do not need to specialize delete_obj(),
1263 since the default implementation calls "delete obj;"}
1265 \note{Another good property of the class is that the operations on the reference counter are atomic,
1266 i.e. it is safe to use the class in multi-threaded applications}
1268 template<typename _Tp> class Ptr
1271 //! empty constructor
1273 //! take ownership of the pointer. The associated reference counter is allocated and set to 1
1277 //! copy constructor. Copies the members and calls addref()
1278 Ptr(const Ptr& ptr);
1279 template<typename _Tp2> Ptr(const Ptr<_Tp2>& ptr);
1280 //! copy operator. Calls ptr.addref() and release() before copying the members
1281 Ptr& operator = (const Ptr& ptr);
1282 //! increments the reference counter
1284 //! decrements the reference counter. If it reaches 0, delete_obj() is called
1286 //! deletes the object. Override if needed
1288 //! returns true iff obj==NULL
1291 //! cast pointer to another type
1292 template<typename _Tp2> Ptr<_Tp2> ptr();
1293 template<typename _Tp2> const Ptr<_Tp2> ptr() const;
1295 //! helper operators making "Ptr<T> ptr" use very similar to "T* ptr".
1296 _Tp* operator -> ();
1297 const _Tp* operator -> () const;
1300 operator const _Tp*() const;
1302 _Tp* obj; //< the object pointer.
1303 int* refcount; //< the associated reference counter
1307 //////////////////////// Input/Output Array Arguments /////////////////////////////////
1310 Proxy datatype for passing Mat's and vector<>'s as input parameters
1312 class CV_EXPORTS _InputArray
1317 FIXED_TYPE = 0x8000 << KIND_SHIFT,
1318 FIXED_SIZE = 0x4000 << KIND_SHIFT,
1319 KIND_MASK = ~(FIXED_TYPE|FIXED_SIZE) - (1 << KIND_SHIFT) + 1,
1321 NONE = 0 << KIND_SHIFT,
1322 MAT = 1 << KIND_SHIFT,
1323 MATX = 2 << KIND_SHIFT,
1324 STD_VECTOR = 3 << KIND_SHIFT,
1325 STD_VECTOR_VECTOR = 4 << KIND_SHIFT,
1326 STD_VECTOR_MAT = 5 << KIND_SHIFT,
1327 EXPR = 6 << KIND_SHIFT,
1328 OPENGL_BUFFER = 7 << KIND_SHIFT,
1329 OPENGL_TEXTURE = 8 << KIND_SHIFT,
1330 GPU_MAT = 9 << KIND_SHIFT,
1331 OCL_MAT =10 << KIND_SHIFT
1335 _InputArray(const Mat& m);
1336 _InputArray(const MatExpr& expr);
1337 template<typename _Tp> _InputArray(const _Tp* vec, int n);
1338 template<typename _Tp> _InputArray(const vector<_Tp>& vec);
1339 template<typename _Tp> _InputArray(const vector<vector<_Tp> >& vec);
1340 _InputArray(const vector<Mat>& vec);
1341 template<typename _Tp> _InputArray(const vector<Mat_<_Tp> >& vec);
1342 template<typename _Tp> _InputArray(const Mat_<_Tp>& m);
1343 template<typename _Tp, int m, int n> _InputArray(const Matx<_Tp, m, n>& matx);
1344 _InputArray(const Scalar& s);
1345 _InputArray(const double& val);
1347 _InputArray(const GlBuffer& buf);
1348 _InputArray(const GlTexture& tex);
1350 _InputArray(const gpu::GpuMat& d_mat);
1351 _InputArray(const ogl::Buffer& buf);
1352 _InputArray(const ogl::Texture2D& tex);
1354 virtual Mat getMat(int i=-1) const;
1355 virtual void getMatVector(vector<Mat>& mv) const;
1357 virtual GlBuffer getGlBuffer() const;
1358 virtual GlTexture getGlTexture() const;
1360 virtual gpu::GpuMat getGpuMat() const;
1361 /*virtual*/ ogl::Buffer getOGlBuffer() const;
1362 /*virtual*/ ogl::Texture2D getOGlTexture2D() const;
1364 virtual int kind() const;
1365 virtual Size size(int i=-1) const;
1366 virtual size_t total(int i=-1) const;
1367 virtual int type(int i=-1) const;
1368 virtual int depth(int i=-1) const;
1369 virtual int channels(int i=-1) const;
1370 virtual bool empty() const;
1372 #ifdef OPENCV_CAN_BREAK_BINARY_COMPATIBILITY
1373 virtual ~_InputArray();
1384 DEPTH_MASK_8U = 1 << CV_8U,
1385 DEPTH_MASK_8S = 1 << CV_8S,
1386 DEPTH_MASK_16U = 1 << CV_16U,
1387 DEPTH_MASK_16S = 1 << CV_16S,
1388 DEPTH_MASK_32S = 1 << CV_32S,
1389 DEPTH_MASK_32F = 1 << CV_32F,
1390 DEPTH_MASK_64F = 1 << CV_64F,
1391 DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1,
1392 DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S,
1393 DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F
1398 Proxy datatype for passing Mat's and vector<>'s as input parameters
1400 class CV_EXPORTS _OutputArray : public _InputArray
1405 _OutputArray(Mat& m);
1406 template<typename _Tp> _OutputArray(vector<_Tp>& vec);
1407 template<typename _Tp> _OutputArray(vector<vector<_Tp> >& vec);
1408 _OutputArray(vector<Mat>& vec);
1409 template<typename _Tp> _OutputArray(vector<Mat_<_Tp> >& vec);
1410 template<typename _Tp> _OutputArray(Mat_<_Tp>& m);
1411 template<typename _Tp, int m, int n> _OutputArray(Matx<_Tp, m, n>& matx);
1412 template<typename _Tp> _OutputArray(_Tp* vec, int n);
1413 _OutputArray(gpu::GpuMat& d_mat);
1414 _OutputArray(ogl::Buffer& buf);
1415 _OutputArray(ogl::Texture2D& tex);
1417 _OutputArray(const Mat& m);
1418 template<typename _Tp> _OutputArray(const vector<_Tp>& vec);
1419 template<typename _Tp> _OutputArray(const vector<vector<_Tp> >& vec);
1420 _OutputArray(const vector<Mat>& vec);
1421 template<typename _Tp> _OutputArray(const vector<Mat_<_Tp> >& vec);
1422 template<typename _Tp> _OutputArray(const Mat_<_Tp>& m);
1423 template<typename _Tp, int m, int n> _OutputArray(const Matx<_Tp, m, n>& matx);
1424 template<typename _Tp> _OutputArray(const _Tp* vec, int n);
1425 _OutputArray(const gpu::GpuMat& d_mat);
1426 _OutputArray(const ogl::Buffer& buf);
1427 _OutputArray(const ogl::Texture2D& tex);
1429 virtual bool fixedSize() const;
1430 virtual bool fixedType() const;
1431 virtual bool needed() const;
1432 virtual Mat& getMatRef(int i=-1) const;
1433 /*virtual*/ gpu::GpuMat& getGpuMatRef() const;
1434 /*virtual*/ ogl::Buffer& getOGlBufferRef() const;
1435 /*virtual*/ ogl::Texture2D& getOGlTexture2DRef() const;
1436 virtual void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
1437 virtual void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
1438 virtual void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
1439 virtual void release() const;
1440 virtual void clear() const;
1442 #ifdef OPENCV_CAN_BREAK_BINARY_COMPATIBILITY
1443 virtual ~_OutputArray();
1447 typedef const _InputArray& InputArray;
1448 typedef InputArray InputArrayOfArrays;
1449 typedef const _OutputArray& OutputArray;
1450 typedef OutputArray OutputArrayOfArrays;
1451 typedef OutputArray InputOutputArray;
1452 typedef OutputArray InputOutputArrayOfArrays;
1454 CV_EXPORTS OutputArray noArray();
1456 /////////////////////////////////////// Mat ///////////////////////////////////////////
1458 enum { MAGIC_MASK=0xFFFF0000, TYPE_MASK=0x00000FFF, DEPTH_MASK=7 };
1460 static inline size_t getElemSize(int type) { return CV_ELEM_SIZE(type); }
1463 Custom array allocator
1466 class CV_EXPORTS MatAllocator
1470 virtual ~MatAllocator() {}
1471 virtual void allocate(int dims, const int* sizes, int type, int*& refcount,
1472 uchar*& datastart, uchar*& data, size_t* step) = 0;
1473 virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0;
1477 The n-dimensional matrix class.
1479 The class represents an n-dimensional dense numerical array that can act as
1480 a matrix, image, optical flow map, 3-focal tensor etc.
1481 It is very similar to CvMat and CvMatND types from earlier versions of OpenCV,
1482 and similarly to those types, the matrix can be multi-channel. It also fully supports ROI mechanism.
1484 There are many different ways to create cv::Mat object. Here are the some popular ones:
1486 <li> using cv::Mat::create(nrows, ncols, type) method or
1487 the similar constructor cv::Mat::Mat(nrows, ncols, type[, fill_value]) constructor.
1488 A new matrix of the specified size and specifed type will be allocated.
1489 "type" has the same meaning as in cvCreateMat function,
1490 e.g. CV_8UC1 means 8-bit single-channel matrix, CV_32FC2 means 2-channel (i.e. complex)
1491 floating-point matrix etc:
1494 // make 7x7 complex matrix filled with 1+3j.
1495 cv::Mat M(7,7,CV_32FC2,Scalar(1,3));
1496 // and now turn M to 100x60 15-channel 8-bit matrix.
1497 // The old content will be deallocated
1498 M.create(100,60,CV_8UC(15));
1501 As noted in the introduction of this chapter, Mat::create()
1502 will only allocate a new matrix when the current matrix dimensionality
1503 or type are different from the specified.
1505 <li> by using a copy constructor or assignment operator, where on the right side it can
1506 be a matrix or expression, see below. Again, as noted in the introduction,
1507 matrix assignment is O(1) operation because it only copies the header
1508 and increases the reference counter. cv::Mat::clone() method can be used to get a full
1509 (a.k.a. deep) copy of the matrix when you need it.
1511 <li> by constructing a header for a part of another matrix. It can be a single row, single column,
1512 several rows, several columns, rectangular region in the matrix (called a minor in algebra) or
1513 a diagonal. Such operations are also O(1), because the new header will reference the same data.
1514 You can actually modify a part of the matrix using this feature, e.g.
1517 // add 5-th row, multiplied by 3 to the 3rd row
1518 M.row(3) = M.row(3) + M.row(5)*3;
1520 // now copy 7-th column to the 1-st column
1521 // M.col(1) = M.col(7); // this will not work
1523 M.col(7).copyTo(M1);
1525 // create new 320x240 image
1526 cv::Mat img(Size(320,240),CV_8UC3);
1528 cv::Mat roi(img, Rect(10,10,100,100));
1529 // fill the ROI with (0,255,0) (which is green in RGB space);
1530 // the original 320x240 image will be modified
1531 roi = Scalar(0,255,0);
1534 Thanks to the additional cv::Mat::datastart and cv::Mat::dataend members, it is possible to
1535 compute the relative sub-matrix position in the main "container" matrix using cv::Mat::locateROI():
1538 Mat A = Mat::eye(10, 10, CV_32S);
1539 // extracts A columns, 1 (inclusive) to 3 (exclusive).
1540 Mat B = A(Range::all(), Range(1, 3));
1541 // extracts B rows, 5 (inclusive) to 9 (exclusive).
1542 // that is, C ~ A(Range(5, 9), Range(1, 3))
1543 Mat C = B(Range(5, 9), Range::all());
1544 Size size; Point ofs;
1545 C.locateROI(size, ofs);
1546 // size will be (width=10,height=10) and the ofs will be (x=1, y=5)
1549 As in the case of whole matrices, if you need a deep copy, use cv::Mat::clone() method
1550 of the extracted sub-matrices.
1552 <li> by making a header for user-allocated-data. It can be useful for
1554 <li> processing "foreign" data using OpenCV (e.g. when you implement
1555 a DirectShow filter or a processing module for gstreamer etc.), e.g.
1558 void process_video_frame(const unsigned char* pixels,
1559 int width, int height, int step)
1561 cv::Mat img(height, width, CV_8UC3, pixels, step);
1562 cv::GaussianBlur(img, img, cv::Size(7,7), 1.5, 1.5);
1566 <li> for quick initialization of small matrices and/or super-fast element access
1569 double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
1570 cv::Mat M = cv::Mat(3, 3, CV_64F, m).inv();
1574 partial yet very common cases of this "user-allocated data" case are conversions
1575 from CvMat and IplImage to cv::Mat. For this purpose there are special constructors
1576 taking pointers to CvMat or IplImage and the optional
1577 flag indicating whether to copy the data or not.
1579 Backward conversion from cv::Mat to CvMat or IplImage is provided via cast operators
1580 cv::Mat::operator CvMat() an cv::Mat::operator IplImage().
1581 The operators do not copy the data.
1585 IplImage* img = cvLoadImage("greatwave.jpg", 1);
1586 Mat mtx(img); // convert IplImage* -> cv::Mat
1587 CvMat oldmat = mtx; // convert cv::Mat -> CvMat
1588 CV_Assert(oldmat.cols == img->width && oldmat.rows == img->height &&
1589 oldmat.data.ptr == (uchar*)img->imageData && oldmat.step == img->widthStep);
1592 <li> by using MATLAB-style matrix initializers, cv::Mat::zeros(), cv::Mat::ones(), cv::Mat::eye(), e.g.:
1595 // create a double-precision identity martix and add it to M.
1596 M += Mat::eye(M.rows, M.cols, CV_64F);
1599 <li> by using comma-separated initializer:
1602 // create 3x3 double-precision identity matrix
1603 Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
1606 here we first call constructor of cv::Mat_ class (that we describe further) with the proper matrix,
1607 and then we just put "<<" operator followed by comma-separated values that can be constants,
1608 variables, expressions etc. Also, note the extra parentheses that are needed to avoid compiler errors.
1612 Once matrix is created, it will be automatically managed by using reference-counting mechanism
1613 (unless the matrix header is built on top of user-allocated data,
1614 in which case you should handle the data by yourself).
1615 The matrix data will be deallocated when no one points to it;
1616 if you want to release the data pointed by a matrix header before the matrix destructor is called,
1617 use cv::Mat::release().
1619 The next important thing to learn about the matrix class is element access. Here is how the matrix is stored.
1620 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,
1621 cv::Mat::rows contains the number of matrix rows and cv::Mat::cols - the number of matrix columns. There is yet another member,
1622 cv::Mat::step that is used to actually compute address of a matrix element. cv::Mat::step is needed because the matrix can be
1623 a part of another matrix or because there can some padding space in the end of each row for a proper alignment.
1627 Given these parameters, address of the matrix element M_{ij} is computed as following:
1629 addr(M_{ij})=M.data + M.step*i + j*M.elemSize()
1631 if you know the matrix element type, e.g. it is float, then you can use cv::Mat::at() method:
1633 addr(M_{ij})=&M.at<float>(i,j)
1635 (where & is used to convert the reference returned by cv::Mat::at() to a pointer).
1636 if you need to process a whole row of matrix, the most efficient way is to get
1637 the pointer to the row first, and then just use plain C operator []:
1640 // compute sum of positive matrix elements
1641 // (assuming that M is double-precision matrix)
1643 for(int i = 0; i < M.rows; i++)
1645 const double* Mi = M.ptr<double>(i);
1646 for(int j = 0; j < M.cols; j++)
1647 sum += std::max(Mi[j], 0.);
1651 Some operations, like the above one, do not actually depend on the matrix shape,
1652 they just process elements of a matrix one by one (or elements from multiple matrices
1653 that are sitting in the same place, e.g. matrix addition). Such operations are called
1654 element-wise and it makes sense to check whether all the input/output matrices are continuous,
1655 i.e. have no gaps in the end of each row, and if yes, process them as a single long row:
1658 // compute sum of positive matrix elements, optimized variant
1660 int cols = M.cols, rows = M.rows;
1661 if(M.isContinuous())
1666 for(int i = 0; i < rows; i++)
1668 const double* Mi = M.ptr<double>(i);
1669 for(int j = 0; j < cols; j++)
1670 sum += std::max(Mi[j], 0.);
1673 in the case of continuous matrix the outer loop body will be executed just once,
1674 so the overhead will be smaller, which will be especially noticeable in the case of small matrices.
1676 Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:
1678 // compute sum of positive matrix elements, iterator-based variant
1680 MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
1681 for(; it != it_end; ++it)
1682 sum += std::max(*it, 0.);
1685 The matrix iterators are random-access iterators, so they can be passed
1686 to any STL algorithm, including std::sort().
1688 class CV_EXPORTS Mat
1691 //! default constructor
1693 //! constructs 2D matrix of the specified size and type
1694 // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
1695 Mat(int rows, int cols, int type);
1696 Mat(Size size, int type);
1697 //! constucts 2D matrix and fills it with the specified value _s.
1698 Mat(int rows, int cols, int type, const Scalar& s);
1699 Mat(Size size, int type, const Scalar& s);
1701 //! constructs n-dimensional matrix
1702 Mat(int ndims, const int* sizes, int type);
1703 Mat(int ndims, const int* sizes, int type, const Scalar& s);
1705 //! copy constructor
1707 //! constructor for matrix headers pointing to user-allocated data
1708 Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP);
1709 Mat(Size size, int type, void* data, size_t step=AUTO_STEP);
1710 Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0);
1712 //! creates a matrix header for a part of the bigger matrix
1713 Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all());
1714 Mat(const Mat& m, const Rect& roi);
1715 Mat(const Mat& m, const Range* ranges);
1716 //! converts old-style CvMat to the new matrix; the data is not copied by default
1717 Mat(const CvMat* m, bool copyData=false);
1718 //! converts old-style CvMatND to the new matrix; the data is not copied by default
1719 Mat(const CvMatND* m, bool copyData=false);
1720 //! converts old-style IplImage to the new matrix; the data is not copied by default
1721 Mat(const IplImage* img, bool copyData=false);
1722 //! builds matrix from std::vector with or without copying the data
1723 template<typename _Tp> explicit Mat(const vector<_Tp>& vec, bool copyData=false);
1724 //! builds matrix from cv::Vec; the data is copied by default
1725 template<typename _Tp, int n> explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true);
1726 //! builds matrix from cv::Matx; the data is copied by default
1727 template<typename _Tp, int m, int n> explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
1728 //! builds matrix from a 2D point
1729 template<typename _Tp> explicit Mat(const Point_<_Tp>& pt, bool copyData=true);
1730 //! builds matrix from a 3D point
1731 template<typename _Tp> explicit Mat(const Point3_<_Tp>& pt, bool copyData=true);
1732 //! builds matrix from comma initializer
1733 template<typename _Tp> explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer);
1735 //! download data from GpuMat
1736 explicit Mat(const gpu::GpuMat& m);
1738 //! destructor - calls release()
1740 //! assignment operators
1741 Mat& operator = (const Mat& m);
1742 Mat& operator = (const MatExpr& expr);
1744 //! returns a new matrix header for the specified row
1745 Mat row(int y) const;
1746 //! returns a new matrix header for the specified column
1747 Mat col(int x) const;
1748 //! ... for the specified row span
1749 Mat rowRange(int startrow, int endrow) const;
1750 Mat rowRange(const Range& r) const;
1751 //! ... for the specified column span
1752 Mat colRange(int startcol, int endcol) const;
1753 Mat colRange(const Range& r) const;
1754 //! ... for the specified diagonal
1755 // (d=0 - the main diagonal,
1756 // >0 - a diagonal from the lower half,
1757 // <0 - a diagonal from the upper half)
1758 Mat diag(int d=0) const;
1759 //! constructs a square diagonal matrix which main diagonal is vector "d"
1760 static Mat diag(const Mat& d);
1762 //! returns deep copy of the matrix, i.e. the data is copied
1764 //! copies the matrix content to "m".
1765 // It calls m.create(this->size(), this->type()).
1766 void copyTo( OutputArray m ) const;
1767 //! copies those matrix elements to "m" that are marked with non-zero mask elements.
1768 void copyTo( OutputArray m, InputArray mask ) const;
1769 //! converts matrix to another datatype with optional scalng. See cvConvertScale.
1770 void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
1772 void assignTo( Mat& m, int type=-1 ) const;
1774 //! sets every matrix element to s
1775 Mat& operator = (const Scalar& s);
1776 //! sets some of the matrix elements to s, according to the mask
1777 Mat& setTo(InputArray value, InputArray mask=noArray());
1778 //! creates alternative matrix header for the same data, with different
1779 // number of channels and/or different number of rows. see cvReshape.
1780 Mat reshape(int cn, int rows=0) const;
1781 Mat reshape(int cn, int newndims, const int* newsz) const;
1783 //! matrix transposition by means of matrix expressions
1785 //! matrix inversion by means of matrix expressions
1786 MatExpr inv(int method=DECOMP_LU) const;
1787 //! per-element matrix multiplication by means of matrix expressions
1788 MatExpr mul(InputArray m, double scale=1) const;
1790 //! computes cross-product of 2 3D vectors
1791 Mat cross(InputArray m) const;
1792 //! computes dot-product
1793 double dot(InputArray m) const;
1795 //! Matlab-style matrix initialization
1796 static MatExpr zeros(int rows, int cols, int type);
1797 static MatExpr zeros(Size size, int type);
1798 static MatExpr zeros(int ndims, const int* sz, int type);
1799 static MatExpr ones(int rows, int cols, int type);
1800 static MatExpr ones(Size size, int type);
1801 static MatExpr ones(int ndims, const int* sz, int type);
1802 static MatExpr eye(int rows, int cols, int type);
1803 static MatExpr eye(Size size, int type);
1805 //! allocates new matrix data unless the matrix already has specified size and type.
1806 // previous data is unreferenced if needed.
1807 void create(int rows, int cols, int type);
1808 void create(Size size, int type);
1809 void create(int ndims, const int* sizes, int type);
1811 //! increases the reference counter; use with care to avoid memleaks
1813 //! decreases reference counter;
1814 // deallocates the data when reference counter reaches 0.
1817 //! deallocates the matrix data
1819 //! internal use function; properly re-allocates _size, _step arrays
1820 void copySize(const Mat& m);
1822 //! reserves enough space to fit sz hyper-planes
1823 void reserve(size_t sz);
1824 //! resizes matrix to the specified number of hyper-planes
1825 void resize(size_t sz);
1826 //! resizes matrix to the specified number of hyper-planes; initializes the newly added elements
1827 void resize(size_t sz, const Scalar& s);
1828 //! internal function
1829 void push_back_(const void* elem);
1830 //! adds element to the end of 1d matrix (or possibly multiple elements when _Tp=Mat)
1831 template<typename _Tp> void push_back(const _Tp& elem);
1832 template<typename _Tp> void push_back(const Mat_<_Tp>& elem);
1833 void push_back(const Mat& m);
1834 //! removes several hyper-planes from bottom of the matrix
1835 void pop_back(size_t nelems=1);
1837 //! locates matrix header within a parent matrix. See below
1838 void locateROI( Size& wholeSize, Point& ofs ) const;
1839 //! moves/resizes the current matrix ROI inside the parent matrix.
1840 Mat& adjustROI( int dtop, int dbottom, int dleft, int dright );
1841 //! extracts a rectangular sub-matrix
1842 // (this is a generalized form of row, rowRange etc.)
1843 Mat operator()( Range rowRange, Range colRange ) const;
1844 Mat operator()( const Rect& roi ) const;
1845 Mat operator()( const Range* ranges ) const;
1847 //! converts header to CvMat; no data is copied
1848 operator CvMat() const;
1849 //! converts header to CvMatND; no data is copied
1850 operator CvMatND() const;
1851 //! converts header to IplImage; no data is copied
1852 operator IplImage() const;
1854 template<typename _Tp> operator vector<_Tp>() const;
1855 template<typename _Tp, int n> operator Vec<_Tp, n>() const;
1856 template<typename _Tp, int m, int n> operator Matx<_Tp, m, n>() const;
1858 //! returns true iff the matrix data is continuous
1859 // (i.e. when there are no gaps between successive rows).
1860 // similar to CV_IS_MAT_CONT(cvmat->type)
1861 bool isContinuous() const;
1863 //! returns true if the matrix is a submatrix of another matrix
1864 bool isSubmatrix() const;
1866 //! returns element size in bytes,
1867 // similar to CV_ELEM_SIZE(cvmat->type)
1868 size_t elemSize() const;
1869 //! returns the size of element channel in bytes.
1870 size_t elemSize1() const;
1871 //! returns element type, similar to CV_MAT_TYPE(cvmat->type)
1873 //! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
1875 //! returns element type, similar to CV_MAT_CN(cvmat->type)
1876 int channels() const;
1877 //! returns step/elemSize1()
1878 size_t step1(int i=0) const;
1879 //! returns true if matrix data is NULL
1881 //! returns the total number of matrix elements
1882 size_t total() const;
1884 //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
1885 int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
1887 //! returns pointer to i0-th submatrix along the dimension #0
1888 uchar* ptr(int i0=0);
1889 const uchar* ptr(int i0=0) const;
1891 //! returns pointer to (i0,i1) submatrix along the dimensions #0 and #1
1892 uchar* ptr(int i0, int i1);
1893 const uchar* ptr(int i0, int i1) const;
1895 //! returns pointer to (i0,i1,i3) submatrix along the dimensions #0, #1, #2
1896 uchar* ptr(int i0, int i1, int i2);
1897 const uchar* ptr(int i0, int i1, int i2) const;
1899 //! returns pointer to the matrix element
1900 uchar* ptr(const int* idx);
1901 //! returns read-only pointer to the matrix element
1902 const uchar* ptr(const int* idx) const;
1904 template<int n> uchar* ptr(const Vec<int, n>& idx);
1905 template<int n> const uchar* ptr(const Vec<int, n>& idx) const;
1907 //! template version of the above method
1908 template<typename _Tp> _Tp* ptr(int i0=0);
1909 template<typename _Tp> const _Tp* ptr(int i0=0) const;
1911 template<typename _Tp> _Tp* ptr(int i0, int i1);
1912 template<typename _Tp> const _Tp* ptr(int i0, int i1) const;
1914 template<typename _Tp> _Tp* ptr(int i0, int i1, int i2);
1915 template<typename _Tp> const _Tp* ptr(int i0, int i1, int i2) const;
1917 template<typename _Tp> _Tp* ptr(const int* idx);
1918 template<typename _Tp> const _Tp* ptr(const int* idx) const;
1920 template<typename _Tp, int n> _Tp* ptr(const Vec<int, n>& idx);
1921 template<typename _Tp, int n> const _Tp* ptr(const Vec<int, n>& idx) const;
1923 //! the same as above, with the pointer dereferencing
1924 template<typename _Tp> _Tp& at(int i0=0);
1925 template<typename _Tp> const _Tp& at(int i0=0) const;
1927 template<typename _Tp> _Tp& at(int i0, int i1);
1928 template<typename _Tp> const _Tp& at(int i0, int i1) const;
1930 template<typename _Tp> _Tp& at(int i0, int i1, int i2);
1931 template<typename _Tp> const _Tp& at(int i0, int i1, int i2) const;
1933 template<typename _Tp> _Tp& at(const int* idx);
1934 template<typename _Tp> const _Tp& at(const int* idx) const;
1936 template<typename _Tp, int n> _Tp& at(const Vec<int, n>& idx);
1937 template<typename _Tp, int n> const _Tp& at(const Vec<int, n>& idx) const;
1939 //! special versions for 2D arrays (especially convenient for referencing image pixels)
1940 template<typename _Tp> _Tp& at(Point pt);
1941 template<typename _Tp> const _Tp& at(Point pt) const;
1943 //! template methods for iteration over matrix elements.
1944 // the iterators take care of skipping gaps in the end of rows (if any)
1945 template<typename _Tp> MatIterator_<_Tp> begin();
1946 template<typename _Tp> MatIterator_<_Tp> end();
1947 template<typename _Tp> MatConstIterator_<_Tp> begin() const;
1948 template<typename _Tp> MatConstIterator_<_Tp> end() const;
1950 enum { MAGIC_VAL=0x42FF0000, AUTO_STEP=0, CONTINUOUS_FLAG=CV_MAT_CONT_FLAG, SUBMATRIX_FLAG=CV_SUBMAT_FLAG };
1952 /*! includes several bit-fields:
1953 - the magic signature
1956 - number of channels
1959 //! the matrix dimensionality, >= 2
1961 //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
1963 //! pointer to the data
1966 //! pointer to the reference counter;
1967 // when matrix points to user-allocated data, the pointer is NULL
1970 //! helper fields used in locateROI and adjustROI
1975 //! custom allocator
1976 MatAllocator* allocator;
1978 struct CV_EXPORTS MSize
1981 Size operator()() const;
1982 const int& operator[](int i) const;
1983 int& operator[](int i);
1984 operator const int*() const;
1985 bool operator == (const MSize& sz) const;
1986 bool operator != (const MSize& sz) const;
1991 struct CV_EXPORTS MStep
1995 const size_t& operator[](int i) const;
1996 size_t& operator[](int i);
1997 operator size_t() const;
1998 MStep& operator = (size_t s);
2003 MStep& operator = (const MStep&);
2015 Random Number Generator
2017 The class implements RNG using Multiply-with-Carry algorithm
2019 class CV_EXPORTS RNG
2022 enum { UNIFORM=0, NORMAL=1 };
2026 //! updates the state and returns the next 32-bit unsigned integer random number
2033 operator unsigned();
2034 //! returns a random integer sampled uniformly from [0, N).
2035 unsigned operator ()(unsigned N);
2036 unsigned operator ()();
2040 //! returns uniformly distributed integer random number from [a,b) range
2041 int uniform(int a, int b);
2042 //! returns uniformly distributed floating-point random number from [a,b) range
2043 float uniform(float a, float b);
2044 //! returns uniformly distributed double-precision floating-point random number from [a,b) range
2045 double uniform(double a, double b);
2046 void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange=false );
2047 //! returns Gaussian random variate with mean zero.
2048 double gaussian(double sigma);
2054 Random Number Generator - MT
2056 The class implements RNG using the Mersenne Twister algorithm
2058 class CV_EXPORTS RNG_MT19937
2062 RNG_MT19937(unsigned s);
2063 void seed(unsigned s);
2068 operator unsigned();
2072 unsigned operator ()(unsigned N);
2073 unsigned operator ()();
2075 //! returns uniformly distributed integer random number from [a,b) range
2076 int uniform(int a, int b);
2077 //! returns uniformly distributed floating-point random number from [a,b) range
2078 float uniform(float a, float b);
2079 //! returns uniformly distributed double-precision floating-point random number from [a,b) range
2080 double uniform(double a, double b);
2083 enum PeriodParameters {N = 624, M = 397};
2089 Termination criteria in iterative algorithms
2091 class CV_EXPORTS TermCriteria
2096 COUNT=1, //!< the maximum number of iterations or elements to compute
2097 MAX_ITER=COUNT, //!< ditto
2098 EPS=2 //!< the desired accuracy or change in parameters at which the iterative algorithm stops
2101 //! default constructor
2103 //! full constructor
2104 TermCriteria(int type, int maxCount, double epsilon);
2105 //! conversion from CvTermCriteria
2106 TermCriteria(const CvTermCriteria& criteria);
2107 //! conversion to CvTermCriteria
2108 operator CvTermCriteria() const;
2110 int type; //!< the type of termination criteria: COUNT, EPS or COUNT + EPS
2111 int maxCount; // the maximum number of iterations/elements
2112 double epsilon; // the desired accuracy
2116 typedef void (*BinaryFunc)(const uchar* src1, size_t step1,
2117 const uchar* src2, size_t step2,
2118 uchar* dst, size_t step, Size sz,
2121 CV_EXPORTS BinaryFunc getConvertFunc(int sdepth, int ddepth);
2122 CV_EXPORTS BinaryFunc getConvertScaleFunc(int sdepth, int ddepth);
2123 CV_EXPORTS BinaryFunc getCopyMaskFunc(size_t esz);
2125 //! swaps two matrices
2126 CV_EXPORTS void swap(Mat& a, Mat& b);
2128 //! converts array (CvMat or IplImage) to cv::Mat
2129 CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false,
2130 bool allowND=true, int coiMode=0);
2131 //! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it.
2132 CV_EXPORTS void extractImageCOI(const CvArr* arr, OutputArray coiimg, int coi=-1);
2133 //! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage
2134 CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1);
2136 //! adds one matrix to another (dst = src1 + src2)
2137 CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst,
2138 InputArray mask=noArray(), int dtype=-1);
2139 //! subtracts one matrix from another (dst = src1 - src2)
2140 CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst,
2141 InputArray mask=noArray(), int dtype=-1);
2143 //! computes element-wise weighted product of the two arrays (dst = scale*src1*src2)
2144 CV_EXPORTS_W void multiply(InputArray src1, InputArray src2,
2145 OutputArray dst, double scale=1, int dtype=-1);
2147 //! computes element-wise weighted quotient of the two arrays (dst = scale*src1/src2)
2148 CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst,
2149 double scale=1, int dtype=-1);
2151 //! computes element-wise weighted reciprocal of an array (dst = scale/src2)
2152 CV_EXPORTS_W void divide(double scale, InputArray src2,
2153 OutputArray dst, int dtype=-1);
2155 //! adds scaled array to another one (dst = alpha*src1 + src2)
2156 CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst);
2158 //! computes weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma)
2159 CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2,
2160 double beta, double gamma, OutputArray dst, int dtype=-1);
2162 //! 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)
2163 CV_EXPORTS_W void convertScaleAbs(InputArray src, OutputArray dst,
2164 double alpha=1, double beta=0);
2165 //! transforms array of numbers using a lookup table: dst(i)=lut(src(i))
2166 CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst,
2167 int interpolation=0);
2169 //! computes sum of array elements
2170 CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src);
2171 //! computes the number of nonzero array elements
2172 CV_EXPORTS_W int countNonZero( InputArray src );
2173 //! returns the list of locations of non-zero pixels
2174 CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx );
2176 //! computes mean value of selected array elements
2177 CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask=noArray());
2178 //! computes mean value and standard deviation of all or selected array elements
2179 CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev,
2180 InputArray mask=noArray());
2181 //! computes norm of the selected array part
2182 CV_EXPORTS_W double norm(InputArray src1, int normType=NORM_L2, InputArray mask=noArray());
2183 //! computes norm of selected part of the difference between two arrays
2184 CV_EXPORTS_W double norm(InputArray src1, InputArray src2,
2185 int normType=NORM_L2, InputArray mask=noArray());
2187 //! naive nearest neighbor finder
2188 CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2,
2189 OutputArray dist, int dtype, OutputArray nidx,
2190 int normType=NORM_L2, int K=0,
2191 InputArray mask=noArray(), int update=0,
2192 bool crosscheck=false);
2194 //! 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
2195 CV_EXPORTS_W void normalize( InputArray src, OutputArray dst, double alpha=1, double beta=0,
2196 int norm_type=NORM_L2, int dtype=-1, InputArray mask=noArray());
2198 //! finds global minimum and maximum array elements and returns their values and their locations
2199 CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal,
2200 CV_OUT double* maxVal=0, CV_OUT Point* minLoc=0,
2201 CV_OUT Point* maxLoc=0, InputArray mask=noArray());
2202 CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal,
2203 int* minIdx=0, int* maxIdx=0, InputArray mask=noArray());
2205 //! transforms 2D matrix to 1D row or column vector by taking sum, minimum, maximum or mean value over all the rows
2206 CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype=-1);
2208 //! makes multi-channel array out of several single-channel arrays
2209 CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst);
2210 CV_EXPORTS void merge(const vector<Mat>& mv, OutputArray dst );
2212 //! makes multi-channel array out of several single-channel arrays
2213 CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst);
2215 //! copies each plane of a multi-channel array to a dedicated array
2216 CV_EXPORTS void split(const Mat& src, Mat* mvbegin);
2217 CV_EXPORTS void split(const Mat& m, vector<Mat>& mv );
2219 //! copies each plane of a multi-channel array to a dedicated array
2220 CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv);
2222 //! copies selected channels from the input arrays to the selected channels of the output arrays
2223 CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts,
2224 const int* fromTo, size_t npairs);
2225 CV_EXPORTS void mixChannels(const vector<Mat>& src, vector<Mat>& dst,
2226 const int* fromTo, size_t npairs);
2227 CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputArrayOfArrays dst,
2228 const vector<int>& fromTo);
2230 //! extracts a single channel from src (coi is 0-based index)
2231 CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi);
2233 //! inserts a single channel to dst (coi is 0-based index)
2234 CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi);
2236 //! reverses the order of the rows, columns or both in a matrix
2237 CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode);
2239 //! replicates the input matrix the specified number of times in the horizontal and/or vertical direction
2240 CV_EXPORTS_W void repeat(InputArray src, int ny, int nx, OutputArray dst);
2241 CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx);
2243 CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, OutputArray dst);
2244 CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst);
2245 CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst);
2247 CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst);
2248 CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst);
2249 CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst);
2251 //! computes bitwise conjunction of the two arrays (dst = src1 & src2)
2252 CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2,
2253 OutputArray dst, InputArray mask=noArray());
2254 //! computes bitwise disjunction of the two arrays (dst = src1 | src2)
2255 CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2,
2256 OutputArray dst, InputArray mask=noArray());
2257 //! computes bitwise exclusive-or of the two arrays (dst = src1 ^ src2)
2258 CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2,
2259 OutputArray dst, InputArray mask=noArray());
2260 //! inverts each bit of array (dst = ~src)
2261 CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst,
2262 InputArray mask=noArray());
2263 //! computes element-wise absolute difference of two arrays (dst = abs(src1 - src2))
2264 CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst);
2265 //! set mask elements for those array elements which are within the element-specific bounding box (dst = lowerb <= src && src < upperb)
2266 CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb,
2267 InputArray upperb, OutputArray dst);
2268 //! compares elements of two arrays (dst = src1 <cmpop> src2)
2269 CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop);
2270 //! computes per-element minimum of two arrays (dst = min(src1, src2))
2271 CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst);
2272 //! computes per-element maximum of two arrays (dst = max(src1, src2))
2273 CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst);
2275 //! computes per-element minimum of two arrays (dst = min(src1, src2))
2276 CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst);
2277 //! computes per-element minimum of array and scalar (dst = min(src1, src2))
2278 CV_EXPORTS void min(const Mat& src1, double src2, Mat& dst);
2279 //! computes per-element maximum of two arrays (dst = max(src1, src2))
2280 CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst);
2281 //! computes per-element maximum of array and scalar (dst = max(src1, src2))
2282 CV_EXPORTS void max(const Mat& src1, double src2, Mat& dst);
2284 //! computes square root of each matrix element (dst = src**0.5)
2285 CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst);
2286 //! raises the input matrix elements to the specified power (b = a**power)
2287 CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst);
2288 //! computes exponent of each matrix element (dst = e**src)
2289 CV_EXPORTS_W void exp(InputArray src, OutputArray dst);
2290 //! computes natural logarithm of absolute value of each matrix element: dst = log(abs(src))
2291 CV_EXPORTS_W void log(InputArray src, OutputArray dst);
2292 //! computes cube root of the argument
2293 CV_EXPORTS_W float cubeRoot(float val);
2294 //! computes the angle in degrees (0..360) of the vector (x,y)
2295 CV_EXPORTS_W float fastAtan2(float y, float x);
2297 CV_EXPORTS void exp(const float* src, float* dst, int n);
2298 CV_EXPORTS void log(const float* src, float* dst, int n);
2299 CV_EXPORTS void fastAtan2(const float* y, const float* x, float* dst, int n, bool angleInDegrees);
2300 CV_EXPORTS void magnitude(const float* x, const float* y, float* dst, int n);
2302 //! converts polar coordinates to Cartesian
2303 CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle,
2304 OutputArray x, OutputArray y, bool angleInDegrees=false);
2305 //! converts Cartesian coordinates to polar
2306 CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y,
2307 OutputArray magnitude, OutputArray angle,
2308 bool angleInDegrees=false);
2309 //! computes angle (angle(i)) of each (x(i), y(i)) vector
2310 CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle,
2311 bool angleInDegrees=false);
2312 //! computes magnitude (magnitude(i)) of each (x(i), y(i)) vector
2313 CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude);
2314 //! checks that each matrix element is within the specified range.
2315 CV_EXPORTS_W bool checkRange(InputArray a, bool quiet=true, CV_OUT Point* pos=0,
2316 double minVal=-DBL_MAX, double maxVal=DBL_MAX);
2317 //! converts NaN's to the given number
2318 CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val=0);
2320 //! implements generalized matrix product algorithm GEMM from BLAS
2321 CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha,
2322 InputArray src3, double gamma, OutputArray dst, int flags=0);
2323 //! multiplies matrix by its transposition from the left or from the right
2324 CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa,
2325 InputArray delta=noArray(),
2326 double scale=1, int dtype=-1 );
2327 //! transposes the matrix
2328 CV_EXPORTS_W void transpose(InputArray src, OutputArray dst);
2329 //! performs affine transformation of each element of multi-channel input matrix
2330 CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m );
2331 //! performs perspective transformation of each element of multi-channel input matrix
2332 CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m );
2334 //! extends the symmetrical matrix from the lower half or from the upper half
2335 CV_EXPORTS_W void completeSymm(InputOutputArray mtx, bool lowerToUpper=false);
2336 //! initializes scaled identity matrix
2337 CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s=Scalar(1));
2338 //! computes determinant of a square matrix
2339 CV_EXPORTS_W double determinant(InputArray mtx);
2340 //! computes trace of a matrix
2341 CV_EXPORTS_W Scalar trace(InputArray mtx);
2342 //! computes inverse or pseudo-inverse matrix
2343 CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags=DECOMP_LU);
2344 //! solves linear system or a least-square problem
2345 CV_EXPORTS_W bool solve(InputArray src1, InputArray src2,
2346 OutputArray dst, int flags=DECOMP_LU);
2351 SORT_EVERY_COLUMN=1,
2356 //! sorts independently each matrix row or each matrix column
2357 CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags);
2358 //! sorts independently each matrix row or each matrix column
2359 CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags);
2360 //! finds real roots of a cubic polynomial
2361 CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots);
2362 //! finds real and complex roots of a polynomial
2363 CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters=300);
2364 //! finds eigenvalues of a symmetric matrix
2365 CV_EXPORTS bool eigen(InputArray src, OutputArray eigenvalues, int lowindex=-1,
2367 //! finds eigenvalues and eigenvectors of a symmetric matrix
2368 CV_EXPORTS bool eigen(InputArray src, OutputArray eigenvalues,
2369 OutputArray eigenvectors,
2370 int lowindex=-1, int highindex=-1);
2371 CV_EXPORTS_W bool eigen(InputArray src, bool computeEigenvectors,
2372 OutputArray eigenvalues, OutputArray eigenvectors);
2384 //! computes covariation matrix of a set of samples
2385 CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean,
2386 int flags, int ctype=CV_64F);
2387 //! computes covariation matrix of a set of samples
2388 CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar,
2389 OutputArray mean, int flags, int ctype=CV_64F);
2392 Principal Component Analysis
2394 The class PCA is used to compute the special basis for a set of vectors.
2395 The basis will consist of eigenvectors of the covariance matrix computed
2396 from the input set of vectors. After PCA is performed, vectors can be transformed from
2397 the original high-dimensional space to the subspace formed by a few most
2398 prominent eigenvectors (called the principal components),
2399 corresponding to the largest eigenvalues of the covariation matrix.
2400 Thus the dimensionality of the vector and the correlation between the coordinates is reduced.
2402 The following sample is the function that takes two matrices. The first one stores the set
2403 of vectors (a row per vector) that is used to compute PCA, the second one stores another
2404 "test" set of vectors (a row per vector) that are first compressed with PCA,
2405 then reconstructed back and then the reconstruction error norm is computed and printed for each vector.
2410 PCA compressPCA(const Mat& pcaset, int maxComponents,
2411 const Mat& testset, Mat& compressed)
2413 PCA pca(pcaset, // pass the data
2414 Mat(), // we do not have a pre-computed mean vector,
2415 // so let the PCA engine to compute it
2416 CV_PCA_DATA_AS_ROW, // indicate that the vectors
2417 // are stored as matrix rows
2418 // (use CV_PCA_DATA_AS_COL if the vectors are
2419 // the matrix columns)
2420 maxComponents // specify, how many principal components to retain
2422 // if there is no test data, just return the computed basis, ready-to-use
2425 CV_Assert( testset.cols == pcaset.cols );
2427 compressed.create(testset.rows, maxComponents, testset.type());
2430 for( int i = 0; i < testset.rows; i++ )
2432 Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed;
2433 // compress the vector, the result will be stored
2434 // in the i-th row of the output matrix
2435 pca.project(vec, coeffs);
2436 // and then reconstruct it
2437 pca.backProject(coeffs, reconstructed);
2438 // and measure the error
2439 printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2));
2445 class CV_EXPORTS PCA
2448 //! default constructor
2450 //! the constructor that performs PCA
2451 PCA(InputArray data, InputArray mean, int flags, int maxComponents=0);
2452 PCA(InputArray data, InputArray mean, int flags, double retainedVariance);
2453 //! operator that performs PCA. The previously stored data, if any, is released
2454 PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents=0);
2455 PCA& computeVar(InputArray data, InputArray mean, int flags, double retainedVariance);
2456 //! projects vector from the original space to the principal components subspace
2457 Mat project(InputArray vec) const;
2458 //! projects vector from the original space to the principal components subspace
2459 void project(InputArray vec, OutputArray result) const;
2460 //! reconstructs the original vector from the projection
2461 Mat backProject(InputArray vec) const;
2462 //! reconstructs the original vector from the projection
2463 void backProject(InputArray vec, OutputArray result) const;
2465 Mat eigenvectors; //!< eigenvectors of the covariation matrix
2466 Mat eigenvalues; //!< eigenvalues of the covariation matrix
2467 Mat mean; //!< mean value subtracted before the projection and added after the back projection
2470 CV_EXPORTS_W void PCACompute(InputArray data, CV_OUT InputOutputArray mean,
2471 OutputArray eigenvectors, int maxComponents=0);
2473 CV_EXPORTS_W void PCAComputeVar(InputArray data, CV_OUT InputOutputArray mean,
2474 OutputArray eigenvectors, double retainedVariance);
2476 CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean,
2477 InputArray eigenvectors, OutputArray result);
2479 CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean,
2480 InputArray eigenvectors, OutputArray result);
2484 Singular Value Decomposition class
2486 The class is used to compute Singular Value Decomposition of a floating-point matrix and then
2487 use it to solve least-square problems, under-determined linear systems, invert matrices,
2488 compute condition numbers etc.
2490 For a bit faster operation you can pass flags=SVD::MODIFY_A|... to modify the decomposed matrix
2491 when it is not necessarily to preserve it. If you want to compute condition number of a matrix
2492 or absolute value of its determinant - you do not need SVD::u or SVD::vt,
2493 so you can pass flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that the full-size SVD::u and SVD::vt
2494 must be computed, which is not necessary most of the time.
2496 class CV_EXPORTS SVD
2499 enum { MODIFY_A=1, NO_UV=2, FULL_UV=4 };
2500 //! the default constructor
2502 //! the constructor that performs SVD
2503 SVD( InputArray src, int flags=0 );
2504 //! the operator that performs SVD. The previously allocated SVD::u, SVD::w are SVD::vt are released.
2505 SVD& operator ()( InputArray src, int flags=0 );
2507 //! decomposes matrix and stores the results to user-provided matrices
2508 static void compute( InputArray src, OutputArray w,
2509 OutputArray u, OutputArray vt, int flags=0 );
2510 //! computes singular values of a matrix
2511 static void compute( InputArray src, OutputArray w, int flags=0 );
2512 //! performs back substitution
2513 static void backSubst( InputArray w, InputArray u,
2514 InputArray vt, InputArray rhs,
2517 template<typename _Tp, int m, int n, int nm> static void compute( const Matx<_Tp, m, n>& a,
2518 Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt );
2519 template<typename _Tp, int m, int n, int nm> static void compute( const Matx<_Tp, m, n>& a,
2520 Matx<_Tp, nm, 1>& w );
2521 template<typename _Tp, int m, int n, int nm, int nb> static void backSubst( const Matx<_Tp, nm, 1>& w,
2522 const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst );
2524 //! finds dst = arg min_{|dst|=1} |m*dst|
2525 static void solveZ( InputArray src, OutputArray dst );
2526 //! performs back substitution, so that dst is the solution or pseudo-solution of m*dst = rhs, where m is the decomposed matrix
2527 void backSubst( InputArray rhs, OutputArray dst ) const;
2532 //! computes SVD of src
2533 CV_EXPORTS_W void SVDecomp( InputArray src, CV_OUT OutputArray w,
2534 CV_OUT OutputArray u, CV_OUT OutputArray vt, int flags=0 );
2536 //! performs back substitution for the previously computed SVD
2537 CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt,
2538 InputArray rhs, CV_OUT OutputArray dst );
2540 //! computes Mahalanobis distance between two vectors: sqrt((v1-v2)'*icovar*(v1-v2)), where icovar is the inverse covariation matrix
2541 CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar);
2542 //! a synonym for Mahalanobis
2543 CV_EXPORTS double Mahalonobis(InputArray v1, InputArray v2, InputArray icovar);
2545 //! performs forward or inverse 1D or 2D Discrete Fourier Transformation
2546 CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags=0, int nonzeroRows=0);
2547 //! performs inverse 1D or 2D Discrete Fourier Transformation
2548 CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags=0, int nonzeroRows=0);
2549 //! performs forward or inverse 1D or 2D Discrete Cosine Transformation
2550 CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags=0);
2551 //! performs inverse 1D or 2D Discrete Cosine Transformation
2552 CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags=0);
2553 //! computes element-wise product of the two Fourier spectrums. The second spectrum can optionally be conjugated before the multiplication
2554 CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c,
2555 int flags, bool conjB=false);
2556 //! computes the minimal vector size vecsize1 >= vecsize so that the dft() of the vector of length vecsize1 can be computed efficiently
2557 CV_EXPORTS_W int getOptimalDFTSize(int vecsize);
2560 Various k-Means flags
2564 KMEANS_RANDOM_CENTERS=0, // Chooses random centers for k-Means initialization
2565 KMEANS_PP_CENTERS=2, // Uses k-Means++ algorithm for initialization
2566 KMEANS_USE_INITIAL_LABELS=1 // Uses the user-provided labels for K-Means initialization
2568 //! clusters the input data using k-Means algorithm
2569 CV_EXPORTS_W double kmeans( InputArray data, int K, CV_OUT InputOutputArray bestLabels,
2570 TermCriteria criteria, int attempts,
2571 int flags, OutputArray centers=noArray() );
2573 //! returns the thread-local Random number generator
2574 CV_EXPORTS RNG& theRNG();
2576 //! returns the next unifomly-distributed random number of the specified type
2577 template<typename _Tp> static inline _Tp randu() { return (_Tp)theRNG(); }
2579 //! fills array with uniformly-distributed random numbers from the range [low, high)
2580 CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high);
2582 //! fills array with normally-distributed random numbers with the specified mean and the standard deviation
2583 CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev);
2585 //! shuffles the input array elements
2586 CV_EXPORTS void randShuffle(InputOutputArray dst, double iterFactor=1., RNG* rng=0);
2587 CV_EXPORTS_AS(randShuffle) void randShuffle_(InputOutputArray dst, double iterFactor=1.);
2589 //! draws the line segment (pt1, pt2) in the image
2590 CV_EXPORTS_W void line(CV_IN_OUT Mat& img, Point pt1, Point pt2, const Scalar& color,
2591 int thickness=1, int lineType=8, int shift=0);
2593 //! draws the rectangle outline or a solid rectangle with the opposite corners pt1 and pt2 in the image
2594 CV_EXPORTS_W void rectangle(CV_IN_OUT Mat& img, Point pt1, Point pt2,
2595 const Scalar& color, int thickness=1,
2596 int lineType=8, int shift=0);
2598 //! draws the rectangle outline or a solid rectangle covering rec in the image
2599 CV_EXPORTS void rectangle(CV_IN_OUT Mat& img, Rect rec,
2600 const Scalar& color, int thickness=1,
2601 int lineType=8, int shift=0);
2603 //! draws the circle outline or a solid circle in the image
2604 CV_EXPORTS_W void circle(CV_IN_OUT Mat& img, Point center, int radius,
2605 const Scalar& color, int thickness=1,
2606 int lineType=8, int shift=0);
2608 //! draws an elliptic arc, ellipse sector or a rotated ellipse in the image
2609 CV_EXPORTS_W void ellipse(CV_IN_OUT Mat& img, Point center, Size axes,
2610 double angle, double startAngle, double endAngle,
2611 const Scalar& color, int thickness=1,
2612 int lineType=8, int shift=0);
2614 //! draws a rotated ellipse in the image
2615 CV_EXPORTS_W void ellipse(CV_IN_OUT Mat& img, const RotatedRect& box, const Scalar& color,
2616 int thickness=1, int lineType=8);
2618 //! draws a filled convex polygon in the image
2619 CV_EXPORTS void fillConvexPoly(Mat& img, const Point* pts, int npts,
2620 const Scalar& color, int lineType=8,
2622 CV_EXPORTS_W void fillConvexPoly(InputOutputArray img, InputArray points,
2623 const Scalar& color, int lineType=8,
2626 //! fills an area bounded by one or more polygons
2627 CV_EXPORTS void fillPoly(Mat& img, const Point** pts,
2628 const int* npts, int ncontours,
2629 const Scalar& color, int lineType=8, int shift=0,
2630 Point offset=Point() );
2632 CV_EXPORTS_W void fillPoly(InputOutputArray img, InputArrayOfArrays pts,
2633 const Scalar& color, int lineType=8, int shift=0,
2634 Point offset=Point() );
2636 //! draws one or more polygonal curves
2637 CV_EXPORTS void polylines(Mat& img, const Point** pts, const int* npts,
2638 int ncontours, bool isClosed, const Scalar& color,
2639 int thickness=1, int lineType=8, int shift=0 );
2641 CV_EXPORTS_W void polylines(InputOutputArray img, InputArrayOfArrays pts,
2642 bool isClosed, const Scalar& color,
2643 int thickness=1, int lineType=8, int shift=0 );
2645 //! clips the line segment by the rectangle Rect(0, 0, imgSize.width, imgSize.height)
2646 CV_EXPORTS bool clipLine(Size imgSize, CV_IN_OUT Point& pt1, CV_IN_OUT Point& pt2);
2648 //! clips the line segment by the rectangle imgRect
2649 CV_EXPORTS_W bool clipLine(Rect imgRect, CV_OUT CV_IN_OUT Point& pt1, CV_OUT CV_IN_OUT Point& pt2);
2654 The class is used to iterate over all the pixels on the raster line
2655 segment connecting two specified points.
2657 class CV_EXPORTS LineIterator
2660 //! intializes the iterator
2661 LineIterator( const Mat& img, Point pt1, Point pt2,
2662 int connectivity=8, bool leftToRight=false );
2663 //! returns pointer to the current pixel
2664 uchar* operator *();
2665 //! prefix increment operator (++it). shifts iterator to the next pixel
2666 LineIterator& operator ++();
2667 //! postfix increment operator (it++). shifts iterator to the next pixel
2668 LineIterator operator ++(int);
2669 //! returns coordinates of the current pixel
2676 int minusDelta, plusDelta;
2677 int minusStep, plusStep;
2680 //! converts elliptic arc to a polygonal curve
2681 CV_EXPORTS_W void ellipse2Poly( Point center, Size axes, int angle,
2682 int arcStart, int arcEnd, int delta,
2683 CV_OUT vector<Point>& pts );
2687 FONT_HERSHEY_SIMPLEX = 0,
2688 FONT_HERSHEY_PLAIN = 1,
2689 FONT_HERSHEY_DUPLEX = 2,
2690 FONT_HERSHEY_COMPLEX = 3,
2691 FONT_HERSHEY_TRIPLEX = 4,
2692 FONT_HERSHEY_COMPLEX_SMALL = 5,
2693 FONT_HERSHEY_SCRIPT_SIMPLEX = 6,
2694 FONT_HERSHEY_SCRIPT_COMPLEX = 7,
2698 //! renders text string in the image
2699 CV_EXPORTS_W void putText( Mat& img, const string& text, Point org,
2700 int fontFace, double fontScale, Scalar color,
2701 int thickness=1, int lineType=8,
2702 bool bottomLeftOrigin=false );
2704 //! returns bounding box of the text string
2705 CV_EXPORTS_W Size getTextSize(const string& text, int fontFace,
2706 double fontScale, int thickness,
2707 CV_OUT int* baseLine);
2709 ///////////////////////////////// Mat_<_Tp> ////////////////////////////////////
2712 Template matrix class derived from Mat
2714 The class Mat_ is a "thin" template wrapper on top of cv::Mat. It does not have any extra data fields,
2715 nor it or cv::Mat have any virtual methods and thus references or pointers to these two classes
2716 can be safely converted one to another. But do it with care, for example:
2719 // create 100x100 8-bit matrix
2720 Mat M(100,100,CV_8U);
2721 // this will compile fine. no any data conversion will be done.
2722 Mat_<float>& M1 = (Mat_<float>&)M;
2723 // the program will likely crash at the statement below
2727 While cv::Mat is sufficient in most cases, cv::Mat_ can be more convenient if you use a lot of element
2728 access operations and if you know matrix type at compile time.
2729 Note that cv::Mat::at<_Tp>(int y, int x) and cv::Mat_<_Tp>::operator ()(int y, int x) do absolutely the
2730 same thing and run at the same speed, but the latter is certainly shorter:
2733 Mat_<double> M(20,20);
2734 for(int i = 0; i < M.rows; i++)
2735 for(int j = 0; j < M.cols; j++)
2736 M(i,j) = 1./(i+j+1);
2739 cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
2742 It is easy to use Mat_ for multi-channel images/matrices - just pass cv::Vec as cv::Mat_ template parameter:
2745 // allocate 320x240 color image and fill it with green (in RGB space)
2746 Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
2747 // now draw a diagonal white line
2748 for(int i = 0; i < 100; i++)
2749 img(i,i)=Vec3b(255,255,255);
2750 // and now modify the 2nd (red) channel of each pixel
2751 for(int i = 0; i < img.rows; i++)
2752 for(int j = 0; j < img.cols; j++)
2753 img(i,j)[2] ^= (uchar)(i ^ j); // img(y,x)[c] accesses c-th channel of the pixel (x,y)
2756 template<typename _Tp> class Mat_ : public Mat
2759 typedef _Tp value_type;
2760 typedef typename DataType<_Tp>::channel_type channel_type;
2761 typedef MatIterator_<_Tp> iterator;
2762 typedef MatConstIterator_<_Tp> const_iterator;
2764 //! default constructor
2766 //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type)
2767 Mat_(int _rows, int _cols);
2768 //! constructor that sets each matrix element to specified value
2769 Mat_(int _rows, int _cols, const _Tp& value);
2770 //! equivalent to Mat(_size, DataType<_Tp>::type)
2771 explicit Mat_(Size _size);
2772 //! constructor that sets each matrix element to specified value
2773 Mat_(Size _size, const _Tp& value);
2774 //! n-dim array constructor
2775 Mat_(int _ndims, const int* _sizes);
2776 //! n-dim array constructor that sets each matrix element to specified value
2777 Mat_(int _ndims, const int* _sizes, const _Tp& value);
2778 //! copy/conversion contructor. If m is of different type, it's converted
2780 //! copy constructor
2781 Mat_(const Mat_& m);
2782 //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type
2783 Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP);
2784 //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type
2785 Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0);
2786 //! selects a submatrix
2787 Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all());
2788 //! selects a submatrix
2789 Mat_(const Mat_& m, const Rect& roi);
2790 //! selects a submatrix, n-dim version
2791 Mat_(const Mat_& m, const Range* ranges);
2792 //! from a matrix expression
2793 explicit Mat_(const MatExpr& e);
2794 //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column
2795 explicit Mat_(const vector<_Tp>& vec, bool copyData=false);
2796 template<int n> explicit Mat_(const Vec<typename DataType<_Tp>::channel_type, n>& vec, bool copyData=true);
2797 template<int m, int n> explicit Mat_(const Matx<typename DataType<_Tp>::channel_type, m, n>& mtx, bool copyData=true);
2798 explicit Mat_(const Point_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
2799 explicit Mat_(const Point3_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
2800 explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer);
2802 Mat_& operator = (const Mat& m);
2803 Mat_& operator = (const Mat_& m);
2804 //! set all the elements to s.
2805 Mat_& operator = (const _Tp& s);
2806 //! assign a matrix expression
2807 Mat_& operator = (const MatExpr& e);
2809 //! iterators; they are smart enough to skip gaps in the end of rows
2812 const_iterator begin() const;
2813 const_iterator end() const;
2815 //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type)
2816 void create(int _rows, int _cols);
2817 //! equivalent to Mat::create(_size, DataType<_Tp>::type)
2818 void create(Size _size);
2819 //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type)
2820 void create(int _ndims, const int* _sizes);
2822 Mat_ cross(const Mat_& m) const;
2823 //! data type conversion
2824 template<typename T2> operator Mat_<T2>() const;
2825 //! overridden forms of Mat::row() etc.
2826 Mat_ row(int y) const;
2827 Mat_ col(int x) const;
2828 Mat_ diag(int d=0) const;
2831 //! overridden forms of Mat::elemSize() etc.
2832 size_t elemSize() const;
2833 size_t elemSize1() const;
2836 int channels() const;
2837 size_t step1(int i=0) const;
2838 //! returns step()/sizeof(_Tp)
2839 size_t stepT(int i=0) const;
2841 //! overridden forms of Mat::zeros() etc. Data type is omitted, of course
2842 static MatExpr zeros(int rows, int cols);
2843 static MatExpr zeros(Size size);
2844 static MatExpr zeros(int _ndims, const int* _sizes);
2845 static MatExpr ones(int rows, int cols);
2846 static MatExpr ones(Size size);
2847 static MatExpr ones(int _ndims, const int* _sizes);
2848 static MatExpr eye(int rows, int cols);
2849 static MatExpr eye(Size size);
2851 //! some more overriden methods
2852 Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright );
2853 Mat_ operator()( const Range& rowRange, const Range& colRange ) const;
2854 Mat_ operator()( const Rect& roi ) const;
2855 Mat_ operator()( const Range* ranges ) const;
2857 //! more convenient forms of row and element access operators
2858 _Tp* operator [](int y);
2859 const _Tp* operator [](int y) const;
2861 //! returns reference to the specified element
2862 _Tp& operator ()(const int* idx);
2863 //! returns read-only reference to the specified element
2864 const _Tp& operator ()(const int* idx) const;
2866 //! returns reference to the specified element
2867 template<int n> _Tp& operator ()(const Vec<int, n>& idx);
2868 //! returns read-only reference to the specified element
2869 template<int n> const _Tp& operator ()(const Vec<int, n>& idx) const;
2871 //! returns reference to the specified element (1D case)
2872 _Tp& operator ()(int idx0);
2873 //! returns read-only reference to the specified element (1D case)
2874 const _Tp& operator ()(int idx0) const;
2875 //! returns reference to the specified element (2D case)
2876 _Tp& operator ()(int idx0, int idx1);
2877 //! returns read-only reference to the specified element (2D case)
2878 const _Tp& operator ()(int idx0, int idx1) const;
2879 //! returns reference to the specified element (3D case)
2880 _Tp& operator ()(int idx0, int idx1, int idx2);
2881 //! returns read-only reference to the specified element (3D case)
2882 const _Tp& operator ()(int idx0, int idx1, int idx2) const;
2884 _Tp& operator ()(Point pt);
2885 const _Tp& operator ()(Point pt) const;
2887 //! conversion to vector.
2888 operator vector<_Tp>() const;
2889 //! conversion to Vec
2890 template<int n> operator Vec<typename DataType<_Tp>::channel_type, n>() const;
2891 //! conversion to Matx
2892 template<int m, int n> operator Matx<typename DataType<_Tp>::channel_type, m, n>() const;
2895 typedef Mat_<uchar> Mat1b;
2896 typedef Mat_<Vec2b> Mat2b;
2897 typedef Mat_<Vec3b> Mat3b;
2898 typedef Mat_<Vec4b> Mat4b;
2900 typedef Mat_<short> Mat1s;
2901 typedef Mat_<Vec2s> Mat2s;
2902 typedef Mat_<Vec3s> Mat3s;
2903 typedef Mat_<Vec4s> Mat4s;
2905 typedef Mat_<ushort> Mat1w;
2906 typedef Mat_<Vec2w> Mat2w;
2907 typedef Mat_<Vec3w> Mat3w;
2908 typedef Mat_<Vec4w> Mat4w;
2910 typedef Mat_<int> Mat1i;
2911 typedef Mat_<Vec2i> Mat2i;
2912 typedef Mat_<Vec3i> Mat3i;
2913 typedef Mat_<Vec4i> Mat4i;
2915 typedef Mat_<float> Mat1f;
2916 typedef Mat_<Vec2f> Mat2f;
2917 typedef Mat_<Vec3f> Mat3f;
2918 typedef Mat_<Vec4f> Mat4f;
2920 typedef Mat_<double> Mat1d;
2921 typedef Mat_<Vec2d> Mat2d;
2922 typedef Mat_<Vec3d> Mat3d;
2923 typedef Mat_<Vec4d> Mat4d;
2925 //////////// Iterators & Comma initializers //////////////////
2927 class CV_EXPORTS MatConstIterator
2930 typedef uchar* value_type;
2931 typedef ptrdiff_t difference_type;
2932 typedef const uchar** pointer;
2933 typedef uchar* reference;
2934 typedef std::random_access_iterator_tag iterator_category;
2936 //! default constructor
2938 //! constructor that sets the iterator to the beginning of the matrix
2939 MatConstIterator(const Mat* _m);
2940 //! constructor that sets the iterator to the specified element of the matrix
2941 MatConstIterator(const Mat* _m, int _row, int _col=0);
2942 //! constructor that sets the iterator to the specified element of the matrix
2943 MatConstIterator(const Mat* _m, Point _pt);
2944 //! constructor that sets the iterator to the specified element of the matrix
2945 MatConstIterator(const Mat* _m, const int* _idx);
2946 //! copy constructor
2947 MatConstIterator(const MatConstIterator& it);
2950 MatConstIterator& operator = (const MatConstIterator& it);
2951 //! returns the current matrix element
2952 uchar* operator *() const;
2953 //! returns the i-th matrix element, relative to the current
2954 uchar* operator [](ptrdiff_t i) const;
2956 //! shifts the iterator forward by the specified number of elements
2957 MatConstIterator& operator += (ptrdiff_t ofs);
2958 //! shifts the iterator backward by the specified number of elements
2959 MatConstIterator& operator -= (ptrdiff_t ofs);
2960 //! decrements the iterator
2961 MatConstIterator& operator --();
2962 //! decrements the iterator
2963 MatConstIterator operator --(int);
2964 //! increments the iterator
2965 MatConstIterator& operator ++();
2966 //! increments the iterator
2967 MatConstIterator operator ++(int);
2968 //! returns the current iterator position
2970 //! returns the current iterator position
2971 void pos(int* _idx) const;
2972 ptrdiff_t lpos() const;
2973 void seek(ptrdiff_t ofs, bool relative=false);
2974 void seek(const int* _idx, bool relative=false);
2984 Matrix read-only iterator
2987 template<typename _Tp>
2988 class MatConstIterator_ : public MatConstIterator
2991 typedef _Tp value_type;
2992 typedef ptrdiff_t difference_type;
2993 typedef const _Tp* pointer;
2994 typedef const _Tp& reference;
2995 typedef std::random_access_iterator_tag iterator_category;
2997 //! default constructor
2998 MatConstIterator_();
2999 //! constructor that sets the iterator to the beginning of the matrix
3000 MatConstIterator_(const Mat_<_Tp>* _m);
3001 //! constructor that sets the iterator to the specified element of the matrix
3002 MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0);
3003 //! constructor that sets the iterator to the specified element of the matrix
3004 MatConstIterator_(const Mat_<_Tp>* _m, Point _pt);
3005 //! constructor that sets the iterator to the specified element of the matrix
3006 MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx);
3007 //! copy constructor
3008 MatConstIterator_(const MatConstIterator_& it);
3011 MatConstIterator_& operator = (const MatConstIterator_& it);
3012 //! returns the current matrix element
3013 _Tp operator *() const;
3014 //! returns the i-th matrix element, relative to the current
3015 _Tp operator [](ptrdiff_t i) const;
3017 //! shifts the iterator forward by the specified number of elements
3018 MatConstIterator_& operator += (ptrdiff_t ofs);
3019 //! shifts the iterator backward by the specified number of elements
3020 MatConstIterator_& operator -= (ptrdiff_t ofs);
3021 //! decrements the iterator
3022 MatConstIterator_& operator --();
3023 //! decrements the iterator
3024 MatConstIterator_ operator --(int);
3025 //! increments the iterator
3026 MatConstIterator_& operator ++();
3027 //! increments the iterator
3028 MatConstIterator_ operator ++(int);
3029 //! returns the current iterator position
3035 Matrix read-write iterator
3038 template<typename _Tp>
3039 class MatIterator_ : public MatConstIterator_<_Tp>
3042 typedef _Tp* pointer;
3043 typedef _Tp& reference;
3044 typedef std::random_access_iterator_tag iterator_category;
3046 //! the default constructor
3048 //! constructor that sets the iterator to the beginning of the matrix
3049 MatIterator_(Mat_<_Tp>* _m);
3050 //! constructor that sets the iterator to the specified element of the matrix
3051 MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0);
3052 //! constructor that sets the iterator to the specified element of the matrix
3053 MatIterator_(const Mat_<_Tp>* _m, Point _pt);
3054 //! constructor that sets the iterator to the specified element of the matrix
3055 MatIterator_(const Mat_<_Tp>* _m, const int* _idx);
3056 //! copy constructor
3057 MatIterator_(const MatIterator_& it);
3059 MatIterator_& operator = (const MatIterator_<_Tp>& it );
3061 //! returns the current matrix element
3062 _Tp& operator *() const;
3063 //! returns the i-th matrix element, relative to the current
3064 _Tp& operator [](ptrdiff_t i) const;
3066 //! shifts the iterator forward by the specified number of elements
3067 MatIterator_& operator += (ptrdiff_t ofs);
3068 //! shifts the iterator backward by the specified number of elements
3069 MatIterator_& operator -= (ptrdiff_t ofs);
3070 //! decrements the iterator
3071 MatIterator_& operator --();
3072 //! decrements the iterator
3073 MatIterator_ operator --(int);
3074 //! increments the iterator
3075 MatIterator_& operator ++();
3076 //! increments the iterator
3077 MatIterator_ operator ++(int);
3080 template<typename _Tp> class MatOp_Iter_;
3083 Comma-separated Matrix Initializer
3085 The class instances are usually not created explicitly.
3086 Instead, they are created on "matrix << firstValue" operator.
3088 The sample below initializes 2x2 rotation matrix:
3091 double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180);
3092 Mat R = (Mat_<double>(2,2) << a, -b, b, a);
3095 template<typename _Tp> class MatCommaInitializer_
3098 //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat
3099 MatCommaInitializer_(Mat_<_Tp>* _m);
3100 //! the operator that takes the next value and put it to the matrix
3101 template<typename T2> MatCommaInitializer_<_Tp>& operator , (T2 v);
3102 //! another form of conversion operator
3103 Mat_<_Tp> operator *() const;
3104 operator Mat_<_Tp>() const;
3106 MatIterator_<_Tp> it;
3110 template<typename _Tp, int m, int n> class MatxCommaInitializer
3113 MatxCommaInitializer(Matx<_Tp, m, n>* _mtx);
3114 template<typename T2> MatxCommaInitializer<_Tp, m, n>& operator , (T2 val);
3115 Matx<_Tp, m, n> operator *() const;
3117 Matx<_Tp, m, n>* dst;
3121 template<typename _Tp, int m> class VecCommaInitializer : public MatxCommaInitializer<_Tp, m, 1>
3124 VecCommaInitializer(Vec<_Tp, m>* _vec);
3125 template<typename T2> VecCommaInitializer<_Tp, m>& operator , (T2 val);
3126 Vec<_Tp, m> operator *() const;
3130 Automatically Allocated Buffer Class
3132 The class is used for temporary buffers in functions and methods.
3133 If a temporary buffer is usually small (a few K's of memory),
3134 but its size depends on the parameters, it makes sense to create a small
3135 fixed-size array on stack and use it if it's large enough. If the required buffer size
3136 is larger than the fixed size, another buffer of sufficient size is allocated dynamically
3137 and released after the processing. Therefore, in typical cases, when the buffer size is small,
3138 there is no overhead associated with malloc()/free().
3139 At the same time, there is no limit on the size of processed data.
3141 This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and
3142 the number of stack-allocated elements. Here is how the class is used:
3145 void my_func(const cv::Mat& m)
3147 cv::AutoBuffer<float, 1000> buf; // create automatic buffer containing 1000 floats
3149 buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used,
3150 // otherwise the buffer of "m.rows" floats will be allocated
3151 // dynamically and deallocated in cv::AutoBuffer destructor
3156 template<typename _Tp, size_t fixed_size=4096/sizeof(_Tp)+8> class AutoBuffer
3159 typedef _Tp value_type;
3160 enum { buffer_padding = (int)((16 + sizeof(_Tp) - 1)/sizeof(_Tp)) };
3162 //! the default contructor
3164 //! constructor taking the real buffer size
3165 AutoBuffer(size_t _size);
3166 //! destructor. calls deallocate()
3169 //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used
3170 void allocate(size_t _size);
3171 //! deallocates the buffer if it was dynamically allocated
3173 //! returns pointer to the real buffer, stack-allocated or head-allocated
3175 //! returns read-only pointer to the real buffer, stack-allocated or head-allocated
3176 operator const _Tp* () const;
3179 //! pointer to the real buffer, can point to buf if the buffer is small enough
3181 //! size of the real buffer
3183 //! pre-allocated buffer
3184 _Tp buf[fixed_size+buffer_padding];
3187 /////////////////////////// multi-dimensional dense matrix //////////////////////////
3190 n-Dimensional Dense Matrix Iterator Class.
3192 The class cv::NAryMatIterator is used for iterating over one or more n-dimensional dense arrays (cv::Mat's).
3194 The iterator is completely different from cv::Mat_ and cv::SparseMat_ iterators.
3195 It iterates through the slices (or planes), not the elements, where "slice" is a continuous part of the arrays.
3197 Here is the example on how the iterator can be used to normalize 3D histogram:
3200 void normalizeColorHist(Mat& hist)
3203 // intialize iterator (the style is different from STL).
3204 // after initialization the iterator will contain
3205 // the number of slices or planes
3206 // the iterator will go through
3207 Mat* arrays[] = { &hist, 0 };
3209 NAryMatIterator it(arrays, planes);
3211 // iterate through the matrix. on each iteration
3212 // it.planes[i] (of type Mat) will be set to the current plane of
3213 // i-th n-dim matrix passed to the iterator constructor.
3214 for(int p = 0; p < it.nplanes; p++, ++it)
3215 s += sum(it.planes[0])[0];
3216 it = NAryMatIterator(hist);
3218 for(int p = 0; p < it.nplanes; p++, ++it)
3221 // this is a shorter implementation of the above
3222 // using built-in operations on Mat
3223 double s = sum(hist)[0];
3224 hist.convertTo(hist, hist.type(), 1./s, 0);
3226 // and this is even shorter one
3227 // (assuming that the histogram elements are non-negative)
3228 normalize(hist, hist, 1, 0, NORM_L1);
3233 You can iterate through several matrices simultaneously as long as they have the same geometry
3234 (dimensionality and all the dimension sizes are the same), which is useful for binary
3235 and n-ary operations on such matrices. Just pass those matrices to cv::MatNDIterator.
3236 Then, during the iteration it.planes[0], it.planes[1], ... will
3237 be the slices of the corresponding matrices
3239 class CV_EXPORTS NAryMatIterator
3242 //! the default constructor
3244 //! the full constructor taking arbitrary number of n-dim matrices
3245 NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1);
3246 //! the full constructor taking arbitrary number of n-dim matrices
3247 NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1);
3248 //! the separate iterator initialization method
3249 void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1);
3251 //! proceeds to the next plane of every iterated matrix
3252 NAryMatIterator& operator ++();
3253 //! proceeds to the next plane of every iterated matrix (postfix increment operator)
3254 NAryMatIterator operator ++(int);
3256 //! the iterated arrays
3258 //! the current planes
3262 //! the number of arrays
3264 //! the number of hyper-planes that the iterator steps through
3266 //! the size of each segment (in elements)
3273 //typedef NAryMatIterator NAryMatNDIterator;
3275 typedef void (*ConvertData)(const void* from, void* to, int cn);
3276 typedef void (*ConvertScaleData)(const void* from, void* to, int cn, double alpha, double beta);
3278 //! returns the function for converting pixels from one data type to another
3279 CV_EXPORTS ConvertData getConvertElem(int fromType, int toType);
3280 //! returns the function for converting pixels from one data type to another with the optional scaling
3281 CV_EXPORTS ConvertScaleData getConvertScaleElem(int fromType, int toType);
3284 /////////////////////////// multi-dimensional sparse matrix //////////////////////////
3286 class SparseMatIterator;
3287 class SparseMatConstIterator;
3288 template<typename _Tp> class SparseMatIterator_;
3289 template<typename _Tp> class SparseMatConstIterator_;
3292 Sparse matrix class.
3294 The class represents multi-dimensional sparse numerical arrays. Such a sparse array can store elements
3295 of any type that cv::Mat is able to store. "Sparse" means that only non-zero elements
3296 are stored (though, as a result of some operations on a sparse matrix, some of its stored elements
3297 can actually become 0. It's user responsibility to detect such elements and delete them using cv::SparseMat::erase().
3298 The non-zero elements are stored in a hash table that grows when it's filled enough,
3299 so that the search time remains O(1) in average. Elements can be accessed using the following methods:
3302 <li>Query operations: cv::SparseMat::ptr() and the higher-level cv::SparseMat::ref(),
3303 cv::SparseMat::value() and cv::SparseMat::find, for example:
3306 int size[] = {10, 10, 10, 10, 10};
3307 SparseMat sparse_mat(dims, size, CV_32F);
3308 for(int i = 0; i < 1000; i++)
3311 for(int k = 0; k < dims; k++)
3312 idx[k] = rand()%sparse_mat.size(k);
3313 sparse_mat.ref<float>(idx) += 1.f;
3317 <li>Sparse matrix iterators. Like cv::Mat iterators and unlike cv::Mat iterators, the sparse matrix iterators are STL-style,
3318 that is, the iteration is done as following:
3320 // prints elements of a sparse floating-point matrix and the sum of elements.
3321 SparseMatConstIterator_<float>
3322 it = sparse_mat.begin<float>(),
3323 it_end = sparse_mat.end<float>();
3325 int dims = sparse_mat.dims();
3326 for(; it != it_end; ++it)
3328 // print element indices and the element value
3329 const Node* n = it.node();
3331 for(int i = 0; i < dims; i++)
3332 printf("%3d%c", n->idx[i], i < dims-1 ? ',' : ')');
3333 printf(": %f\n", *it);
3336 printf("Element sum is %g\n", s);
3338 If you run this loop, you will notice that elements are enumerated
3339 in no any logical order (lexicographical etc.),
3340 they come in the same order as they stored in the hash table, i.e. semi-randomly.
3342 You may collect pointers to the nodes and sort them to get the proper ordering.
3343 Note, however, that pointers to the nodes may become invalid when you add more
3344 elements to the matrix; this is because of possible buffer reallocation.
3346 <li>A combination of the above 2 methods when you need to process 2 or more sparse
3347 matrices simultaneously, e.g. this is how you can compute unnormalized
3348 cross-correlation of the 2 floating-point sparse matrices:
3350 double crossCorr(const SparseMat& a, const SparseMat& b)
3352 const SparseMat *_a = &a, *_b = &b;
3353 // if b contains less elements than a,
3354 // it's faster to iterate through b
3355 if(_a->nzcount() > _b->nzcount())
3357 SparseMatConstIterator_<float> it = _a->begin<float>(),
3358 it_end = _a->end<float>();
3360 for(; it != it_end; ++it)
3362 // take the next element from the first matrix
3364 const Node* anode = it.node();
3365 // and try to find element with the same index in the second matrix.
3366 // since the hash value depends only on the element index,
3367 // we reuse hashvalue stored in the node
3368 float bvalue = _b->value<float>(anode->idx,&anode->hashval);
3369 ccorr += avalue*bvalue;
3376 class CV_EXPORTS SparseMat
3379 typedef SparseMatIterator iterator;
3380 typedef SparseMatConstIterator const_iterator;
3382 //! the sparse matrix header
3383 struct CV_EXPORTS Hdr
3385 Hdr(int _dims, const int* _sizes, int _type);
3394 vector<size_t> hashtab;
3395 int size[CV_MAX_DIM];
3398 //! sparse matrix node - element of a hash table
3399 struct CV_EXPORTS Node
3403 //! index of the next node in the same hash table entry
3405 //! index of the matrix element
3406 int idx[CV_MAX_DIM];
3409 //! default constructor
3411 //! creates matrix of the specified size and type
3412 SparseMat(int dims, const int* _sizes, int _type);
3413 //! copy constructor
3414 SparseMat(const SparseMat& m);
3415 //! converts dense 2d matrix to the sparse form
3417 \param m the input matrix
3419 explicit SparseMat(const Mat& m);
3420 //! converts old-style sparse matrix to the new-style. All the data is copied
3421 SparseMat(const CvSparseMat* m);
3425 //! assignment operator. This is O(1) operation, i.e. no data is copied
3426 SparseMat& operator = (const SparseMat& m);
3427 //! equivalent to the corresponding constructor
3428 SparseMat& operator = (const Mat& m);
3430 //! creates full copy of the matrix
3431 SparseMat clone() const;
3433 //! copies all the data to the destination matrix. All the previous content of m is erased
3434 void copyTo( SparseMat& m ) const;
3435 //! converts sparse matrix to dense matrix.
3436 void copyTo( Mat& m ) const;
3437 //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type
3438 void convertTo( SparseMat& m, int rtype, double alpha=1 ) const;
3439 //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling.
3441 \param rtype The output matrix data type. When it is =-1, the output array will have the same data type as (*this)
3442 \param alpha The scale factor
3443 \param beta The optional delta added to the scaled values before the conversion
3445 void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
3448 void assignTo( SparseMat& m, int type=-1 ) const;
3450 //! reallocates sparse matrix.
3452 If the matrix already had the proper size and type,
3453 it is simply cleared with clear(), otherwise,
3454 the old matrix is released (using release()) and the new one is allocated.
3456 void create(int dims, const int* _sizes, int _type);
3457 //! sets all the sparse matrix elements to 0, which means clearing the hash table.
3459 //! manually increments the reference counter to the header.
3461 // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated.
3464 //! converts sparse matrix to the old-style representation; all the elements are copied.
3465 operator CvSparseMat*() const;
3466 //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements)
3467 size_t elemSize() const;
3468 //! returns elemSize()/channels()
3469 size_t elemSize1() const;
3471 //! returns type of sparse matrix elements
3473 //! returns the depth of sparse matrix elements
3475 //! returns the number of channels
3476 int channels() const;
3478 //! returns the array of sizes, or NULL if the matrix is not allocated
3479 const int* size() const;
3480 //! returns the size of i-th matrix dimension (or 0)
3481 int size(int i) const;
3482 //! returns the matrix dimensionality
3484 //! returns the number of non-zero elements (=the number of hash table nodes)
3485 size_t nzcount() const;
3487 //! computes the element hash value (1D case)
3488 size_t hash(int i0) const;
3489 //! computes the element hash value (2D case)
3490 size_t hash(int i0, int i1) const;
3491 //! computes the element hash value (3D case)
3492 size_t hash(int i0, int i1, int i2) const;
3493 //! computes the element hash value (nD case)
3494 size_t hash(const int* idx) const;
3498 specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case.
3500 return pointer to the matrix element.
3502 <li>if the element is there (it's non-zero), the pointer to it is returned
3503 <li>if it's not there and createMissing=false, NULL pointer is returned
3504 <li>if it's not there and createMissing=true, then the new element
3505 is created and initialized with 0. Pointer to it is returned
3506 <li>if the optional hashval pointer is not NULL, the element hash value is
3507 not computed, but *hashval is taken instead.
3510 //! returns pointer to the specified element (1D case)
3511 uchar* ptr(int i0, bool createMissing, size_t* hashval=0);
3512 //! returns pointer to the specified element (2D case)
3513 uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0);
3514 //! returns pointer to the specified element (3D case)
3515 uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0);
3516 //! returns pointer to the specified element (nD case)
3517 uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0);
3522 return read-write reference to the specified sparse matrix element.
3524 ref<_Tp>(i0,...[,hashval]) is equivalent to *(_Tp*)ptr(i0,...,true[,hashval]).
3525 The methods always return a valid reference.
3526 If the element did not exist, it is created and initialiazed with 0.
3528 //! returns reference to the specified element (1D case)
3529 template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0);
3530 //! returns reference to the specified element (2D case)
3531 template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0);
3532 //! returns reference to the specified element (3D case)
3533 template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
3534 //! returns reference to the specified element (nD case)
3535 template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0);
3540 return value of the specified sparse matrix element.
3542 value<_Tp>(i0,...[,hashval]) is equivalent
3545 { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); }
3548 That is, if the element did not exist, the methods return 0.
3550 //! returns value of the specified element (1D case)
3551 template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const;
3552 //! returns value of the specified element (2D case)
3553 template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const;
3554 //! returns value of the specified element (3D case)
3555 template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0) const;
3556 //! returns value of the specified element (nD case)
3557 template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const;
3562 Return pointer to the specified sparse matrix element if it exists
3564 find<_Tp>(i0,...[,hashval]) is equivalent to (_const Tp*)ptr(i0,...false[,hashval]).
3566 If the specified element does not exist, the methods return NULL.
3568 //! returns pointer to the specified element (1D case)
3569 template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const;
3570 //! returns pointer to the specified element (2D case)
3571 template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0) const;
3572 //! returns pointer to the specified element (3D case)
3573 template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const;
3574 //! returns pointer to the specified element (nD case)
3575 template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0) const;
3577 //! erases the specified element (2D case)
3578 void erase(int i0, int i1, size_t* hashval=0);
3579 //! erases the specified element (3D case)
3580 void erase(int i0, int i1, int i2, size_t* hashval=0);
3581 //! erases the specified element (nD case)
3582 void erase(const int* idx, size_t* hashval=0);
3586 return the sparse matrix iterator pointing to the first sparse matrix element
3588 //! returns the sparse matrix iterator at the matrix beginning
3589 SparseMatIterator begin();
3590 //! returns the sparse matrix iterator at the matrix beginning
3591 template<typename _Tp> SparseMatIterator_<_Tp> begin();
3592 //! returns the read-only sparse matrix iterator at the matrix beginning
3593 SparseMatConstIterator begin() const;
3594 //! returns the read-only sparse matrix iterator at the matrix beginning
3595 template<typename _Tp> SparseMatConstIterator_<_Tp> begin() const;
3598 return the sparse matrix iterator pointing to the element following the last sparse matrix element
3600 //! returns the sparse matrix iterator at the matrix end
3601 SparseMatIterator end();
3602 //! returns the read-only sparse matrix iterator at the matrix end
3603 SparseMatConstIterator end() const;
3604 //! returns the typed sparse matrix iterator at the matrix end
3605 template<typename _Tp> SparseMatIterator_<_Tp> end();
3606 //! returns the typed read-only sparse matrix iterator at the matrix end
3607 template<typename _Tp> SparseMatConstIterator_<_Tp> end() const;
3609 //! returns the value stored in the sparse martix node
3610 template<typename _Tp> _Tp& value(Node* n);
3611 //! returns the value stored in the sparse martix node
3612 template<typename _Tp> const _Tp& value(const Node* n) const;
3614 ////////////// some internal-use methods ///////////////
3615 Node* node(size_t nidx);
3616 const Node* node(size_t nidx) const;
3618 uchar* newNode(const int* idx, size_t hashval);
3619 void removeNode(size_t hidx, size_t nidx, size_t previdx);
3620 void resizeHashTab(size_t newsize);
3622 enum { MAGIC_VAL=0x42FD0000, MAX_DIM=CV_MAX_DIM, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 };
3628 //! finds global minimum and maximum sparse array elements and returns their values and their locations
3629 CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal,
3630 double* maxVal, int* minIdx=0, int* maxIdx=0);
3631 //! computes norm of a sparse matrix
3632 CV_EXPORTS double norm( const SparseMat& src, int normType );
3633 //! 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
3634 CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType );
3637 Read-Only Sparse Matrix Iterator.
3638 Here is how to use the iterator to compute the sum of floating-point sparse matrix elements:
3641 SparseMatConstIterator it = m.begin(), it_end = m.end();
3643 CV_Assert( m.type() == CV_32F );
3644 for( ; it != it_end; ++it )
3645 s += it.value<float>();
3648 class CV_EXPORTS SparseMatConstIterator
3651 //! the default constructor
3652 SparseMatConstIterator();
3653 //! the full constructor setting the iterator to the first sparse matrix element
3654 SparseMatConstIterator(const SparseMat* _m);
3655 //! the copy constructor
3656 SparseMatConstIterator(const SparseMatConstIterator& it);
3658 //! the assignment operator
3659 SparseMatConstIterator& operator = (const SparseMatConstIterator& it);
3661 //! template method returning the current matrix element
3662 template<typename _Tp> const _Tp& value() const;
3663 //! returns the current node of the sparse matrix. it.node->idx is the current element index
3664 const SparseMat::Node* node() const;
3666 //! moves iterator to the previous element
3667 SparseMatConstIterator& operator --();
3668 //! moves iterator to the previous element
3669 SparseMatConstIterator operator --(int);
3670 //! moves iterator to the next element
3671 SparseMatConstIterator& operator ++();
3672 //! moves iterator to the next element
3673 SparseMatConstIterator operator ++(int);
3675 //! moves iterator to the element after the last element
3684 Read-write Sparse Matrix Iterator
3686 The class is similar to cv::SparseMatConstIterator,
3687 but can be used for in-place modification of the matrix elements.
3689 class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator
3692 //! the default constructor
3693 SparseMatIterator();
3694 //! the full constructor setting the iterator to the first sparse matrix element
3695 SparseMatIterator(SparseMat* _m);
3696 //! the full constructor setting the iterator to the specified sparse matrix element
3697 SparseMatIterator(SparseMat* _m, const int* idx);
3698 //! the copy constructor
3699 SparseMatIterator(const SparseMatIterator& it);
3701 //! the assignment operator
3702 SparseMatIterator& operator = (const SparseMatIterator& it);
3703 //! returns read-write reference to the current sparse matrix element
3704 template<typename _Tp> _Tp& value() const;
3705 //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!)
3706 SparseMat::Node* node() const;
3708 //! moves iterator to the next element
3709 SparseMatIterator& operator ++();
3710 //! moves iterator to the next element
3711 SparseMatIterator operator ++(int);
3715 The Template Sparse Matrix class derived from cv::SparseMat
3717 The class provides slightly more convenient operations for accessing elements.
3722 SparseMat_<int> m_ = (SparseMat_<int>&)m;
3723 m_.ref(1)++; // equivalent to m.ref<int>(1)++;
3724 m_.ref(2) += m_(3); // equivalent to m.ref<int>(2) += m.value<int>(3);
3727 template<typename _Tp> class SparseMat_ : public SparseMat
3730 typedef SparseMatIterator_<_Tp> iterator;
3731 typedef SparseMatConstIterator_<_Tp> const_iterator;
3733 //! the default constructor
3735 //! the full constructor equivelent to SparseMat(dims, _sizes, DataType<_Tp>::type)
3736 SparseMat_(int dims, const int* _sizes);
3737 //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted
3738 SparseMat_(const SparseMat& m);
3739 //! the copy constructor. This is O(1) operation - no data is copied
3740 SparseMat_(const SparseMat_& m);
3741 //! converts dense matrix to the sparse form
3742 SparseMat_(const Mat& m);
3743 //! converts the old-style sparse matrix to the C++ class. All the elements are copied
3744 SparseMat_(const CvSparseMat* m);
3745 //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted
3746 SparseMat_& operator = (const SparseMat& m);
3747 //! the assignment operator. This is O(1) operation - no data is copied
3748 SparseMat_& operator = (const SparseMat_& m);
3749 //! converts dense matrix to the sparse form
3750 SparseMat_& operator = (const Mat& m);
3752 //! makes full copy of the matrix. All the elements are duplicated
3753 SparseMat_ clone() const;
3754 //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type)
3755 void create(int dims, const int* _sizes);
3756 //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied
3757 operator CvSparseMat*() const;
3759 //! returns type of the matrix elements
3761 //! returns depth of the matrix elements
3763 //! returns the number of channels in each matrix element
3764 int channels() const;
3766 //! equivalent to SparseMat::ref<_Tp>(i0, hashval)
3767 _Tp& ref(int i0, size_t* hashval=0);
3768 //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval)
3769 _Tp& ref(int i0, int i1, size_t* hashval=0);
3770 //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval)
3771 _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
3772 //! equivalent to SparseMat::ref<_Tp>(idx, hashval)
3773 _Tp& ref(const int* idx, size_t* hashval=0);
3775 //! equivalent to SparseMat::value<_Tp>(i0, hashval)
3776 _Tp operator()(int i0, size_t* hashval=0) const;
3777 //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval)
3778 _Tp operator()(int i0, int i1, size_t* hashval=0) const;
3779 //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval)
3780 _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const;
3781 //! equivalent to SparseMat::value<_Tp>(idx, hashval)
3782 _Tp operator()(const int* idx, size_t* hashval=0) const;
3784 //! returns sparse matrix iterator pointing to the first sparse matrix element
3785 SparseMatIterator_<_Tp> begin();
3786 //! returns read-only sparse matrix iterator pointing to the first sparse matrix element
3787 SparseMatConstIterator_<_Tp> begin() const;
3788 //! returns sparse matrix iterator pointing to the element following the last sparse matrix element
3789 SparseMatIterator_<_Tp> end();
3790 //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element
3791 SparseMatConstIterator_<_Tp> end() const;
3796 Template Read-Only Sparse Matrix Iterator Class.
3798 This is the derived from SparseMatConstIterator class that
3799 introduces more convenient operator *() for accessing the current element.
3801 template<typename _Tp> class SparseMatConstIterator_ : public SparseMatConstIterator
3804 typedef std::forward_iterator_tag iterator_category;
3806 //! the default constructor
3807 SparseMatConstIterator_();
3808 //! the full constructor setting the iterator to the first sparse matrix element
3809 SparseMatConstIterator_(const SparseMat_<_Tp>* _m);
3810 SparseMatConstIterator_(const SparseMat* _m);
3811 //! the copy constructor
3812 SparseMatConstIterator_(const SparseMatConstIterator_& it);
3814 //! the assignment operator
3815 SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it);
3816 //! the element access operator
3817 const _Tp& operator *() const;
3819 //! moves iterator to the next element
3820 SparseMatConstIterator_& operator ++();
3821 //! moves iterator to the next element
3822 SparseMatConstIterator_ operator ++(int);
3826 Template Read-Write Sparse Matrix Iterator Class.
3828 This is the derived from cv::SparseMatConstIterator_ class that
3829 introduces more convenient operator *() for accessing the current element.
3831 template<typename _Tp> class SparseMatIterator_ : public SparseMatConstIterator_<_Tp>
3834 typedef std::forward_iterator_tag iterator_category;
3836 //! the default constructor
3837 SparseMatIterator_();
3838 //! the full constructor setting the iterator to the first sparse matrix element
3839 SparseMatIterator_(SparseMat_<_Tp>* _m);
3840 SparseMatIterator_(SparseMat* _m);
3841 //! the copy constructor
3842 SparseMatIterator_(const SparseMatIterator_& it);
3844 //! the assignment operator
3845 SparseMatIterator_& operator = (const SparseMatIterator_& it);
3846 //! returns the reference to the current element
3847 _Tp& operator *() const;
3849 //! moves the iterator to the next element
3850 SparseMatIterator_& operator ++();
3851 //! moves the iterator to the next element
3852 SparseMatIterator_ operator ++(int);
3855 //////////////////// Fast Nearest-Neighbor Search Structure ////////////////////
3858 Fast Nearest Neighbor Search Class.
3860 The class implements D. Lowe BBF (Best-Bin-First) algorithm for the last
3861 approximate (or accurate) nearest neighbor search in multi-dimensional spaces.
3863 First, a set of vectors is passed to KDTree::KDTree() constructor
3864 or KDTree::build() method, where it is reordered.
3866 Then arbitrary vectors can be passed to KDTree::findNearest() methods, which
3867 find the K nearest neighbors among the vectors from the initial set.
3868 The user can balance between the speed and accuracy of the search by varying Emax
3869 parameter, which is the number of leaves that the algorithm checks.
3870 The larger parameter values yield more accurate results at the expense of lower processing speed.
3873 KDTree T(points, false);
3874 const int K = 3, Emax = INT_MAX;
3877 T.findNearest(query_vec, K, Emax, idx, 0, dist);
3878 CV_Assert(dist[0] <= dist[1] && dist[1] <= dist[2]);
3881 class CV_EXPORTS_W KDTree
3885 The node of the search tree.
3889 Node() : idx(-1), left(-1), right(-1), boundary(0.f) {}
3890 Node(int _idx, int _left, int _right, float _boundary)
3891 : idx(_idx), left(_left), right(_right), boundary(_boundary) {}
3892 //! split dimension; >=0 for nodes (dim), < 0 for leaves (index of the point)
3894 //! node indices of the left and the right branches
3896 //! go to the left if query_vec[node.idx]<=node.boundary, otherwise go to the right
3900 //! the default constructor
3902 //! the full constructor that builds the search tree
3903 CV_WRAP KDTree(InputArray points, bool copyAndReorderPoints=false);
3904 //! the full constructor that builds the search tree
3905 CV_WRAP KDTree(InputArray points, InputArray _labels,
3906 bool copyAndReorderPoints=false);
3907 //! builds the search tree
3908 CV_WRAP void build(InputArray points, bool copyAndReorderPoints=false);
3909 //! builds the search tree
3910 CV_WRAP void build(InputArray points, InputArray labels,
3911 bool copyAndReorderPoints=false);
3912 //! finds the K nearest neighbors of "vec" while looking at Emax (at most) leaves
3913 CV_WRAP int findNearest(InputArray vec, int K, int Emax,
3914 OutputArray neighborsIdx,
3915 OutputArray neighbors=noArray(),
3916 OutputArray dist=noArray(),
3917 OutputArray labels=noArray()) const;
3918 //! finds all the points from the initial set that belong to the specified box
3919 CV_WRAP void findOrthoRange(InputArray minBounds,
3920 InputArray maxBounds,
3921 OutputArray neighborsIdx,
3922 OutputArray neighbors=noArray(),
3923 OutputArray labels=noArray()) const;
3924 //! returns vectors with the specified indices
3925 CV_WRAP void getPoints(InputArray idx, OutputArray pts,
3926 OutputArray labels=noArray()) const;
3927 //! return a vector with the specified index
3928 const float* getPoint(int ptidx, int* label=0) const;
3929 //! returns the search space dimensionality
3930 CV_WRAP int dims() const;
3932 vector<Node> nodes; //!< all the tree nodes
3933 CV_PROP Mat points; //!< all the points. It can be a reordered copy of the input vector set or the original vector set.
3934 CV_PROP vector<int> labels; //!< the parallel array of labels.
3935 CV_PROP int maxDepth; //!< maximum depth of the search tree. Do not modify it
3936 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
3939 //////////////////////////////////////// XML & YAML I/O ////////////////////////////////////
3941 class CV_EXPORTS FileNode;
3944 XML/YAML File Storage Class.
3946 The class describes an object associated with XML or YAML file.
3947 It can be used to store data to such a file or read and decode the data.
3949 The storage is organized as a tree of nested sequences (or lists) and mappings.
3950 Sequence is a heterogenious array, which elements are accessed by indices or sequentially using an iterator.
3951 Mapping is analogue of std::map or C structure, which elements are accessed by names.
3952 The most top level structure is a mapping.
3953 Leaves of the file storage tree are integers, floating-point numbers and text strings.
3955 For example, the following code:
3958 // open file storage for writing. Type of the file is determined from the extension
3959 FileStorage fs("test.yml", FileStorage::WRITE);
3960 fs << "test_int" << 5 << "test_real" << 3.1 << "test_string" << "ABCDEFGH";
3961 fs << "test_mat" << Mat::eye(3,3,CV_32F);
3963 fs << "test_list" << "[" << 0.0000000000001 << 2 << CV_PI << -3435345 << "2-502 2-029 3egegeg" <<
3964 "{:" << "month" << 12 << "day" << 31 << "year" << 1969 << "}" << "]";
3965 fs << "test_map" << "{" << "x" << 1 << "y" << 2 << "width" << 100 << "height" << 200 << "lbp" << "[:";
3967 const uchar arr[] = {0, 1, 1, 0, 1, 1, 0, 1};
3968 fs.writeRaw("u", arr, (int)(sizeof(arr)/sizeof(arr[0])));
3973 will produce the following file:
3978 test_real: 3.1000000000000001e+00
3979 test_string: ABCDEFGH
3980 test_mat: !!opencv-matrix
3984 data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1. ]
3986 - 1.0000000000000000e-13
3988 - 3.1415926535897931e+00
3990 - "2-502 2-029 3egegeg"
3991 - { month:12, day:31, year:1969 }
3997 lbp: [ 0, 1, 1, 0, 1, 1, 0, 1 ]
4000 and to read the file above, the following code can be used:
4003 // open file storage for reading.
4004 // Type of the file is determined from the content, not the extension
4005 FileStorage fs("test.yml", FileStorage::READ);
4006 int test_int = (int)fs["test_int"];
4007 double test_real = (double)fs["test_real"];
4008 string test_string = (string)fs["test_string"];
4011 fs["test_mat"] >> M;
4013 FileNode tl = fs["test_list"];
4014 CV_Assert(tl.type() == FileNode::SEQ && tl.size() == 6);
4015 double tl0 = (double)tl[0];
4016 int tl1 = (int)tl[1];
4017 double tl2 = (double)tl[2];
4018 int tl3 = (int)tl[3];
4019 string tl4 = (string)tl[4];
4020 CV_Assert(tl[5].type() == FileNode::MAP && tl[5].size() == 3);
4022 int month = (int)tl[5]["month"];
4023 int day = (int)tl[5]["day"];
4024 int year = (int)tl[5]["year"];
4026 FileNode tm = fs["test_map"];
4028 int x = (int)tm["x"];
4029 int y = (int)tm["y"];
4030 int width = (int)tm["width"];
4031 int height = (int)tm["height"];
4034 FileNodeIterator it = tm["lbp"].begin();
4036 for(int k = 0; k < 8; k++, ++it)
4037 lbp_val |= ((int)*it) << k;
4040 class CV_EXPORTS_W FileStorage
4043 //! file storage mode
4046 READ=0, //! read mode
4047 WRITE=1, //! write mode
4048 APPEND=2, //! append mode
4062 //! the default constructor
4063 CV_WRAP FileStorage();
4064 //! the full constructor that opens file storage for reading or writing
4065 CV_WRAP FileStorage(const string& source, int flags, const string& encoding=string());
4066 //! the constructor that takes pointer to the C FileStorage structure
4067 FileStorage(CvFileStorage* fs);
4068 //! the destructor. calls release()
4069 virtual ~FileStorage();
4071 //! opens file storage for reading or writing. The previous storage is closed with release()
4072 CV_WRAP virtual bool open(const string& filename, int flags, const string& encoding=string());
4073 //! returns true if the object is associated with currently opened file.
4074 CV_WRAP virtual bool isOpened() const;
4075 //! closes the file and releases all the memory buffers
4076 CV_WRAP virtual void release();
4077 //! closes the file, releases all the memory buffers and returns the text string
4078 CV_WRAP string releaseAndGetString();
4080 //! returns the first element of the top-level mapping
4081 CV_WRAP FileNode getFirstTopLevelNode() const;
4082 //! returns the top-level mapping. YAML supports multiple streams
4083 CV_WRAP FileNode root(int streamidx=0) const;
4084 //! returns the specified element of the top-level mapping
4085 FileNode operator[](const string& nodename) const;
4086 //! returns the specified element of the top-level mapping
4087 CV_WRAP FileNode operator[](const char* nodename) const;
4089 //! returns pointer to the underlying C FileStorage structure
4090 CvFileStorage* operator *() { return fs; }
4091 //! returns pointer to the underlying C FileStorage structure
4092 const CvFileStorage* operator *() const { return fs; }
4093 //! writes one or more numbers of the specified format to the currently written structure
4094 void writeRaw( const string& fmt, const uchar* vec, size_t len );
4095 //! writes the registered C structure (CvMat, CvMatND, CvSeq). See cvWrite()
4096 void writeObj( const string& name, const void* obj );
4098 //! returns the normalized object name for the specified file name
4099 static string getDefaultObjectName(const string& filename);
4101 Ptr<CvFileStorage> fs; //!< the underlying C FileStorage structure
4102 string elname; //!< the currently written element
4103 vector<char> structs; //!< the stack of written structures
4104 int state; //!< the writer state
4107 class CV_EXPORTS FileNodeIterator;
4110 File Storage Node class
4112 The node is used to store each and every element of the file storage opened for reading -
4113 from the primitive objects, such as numbers and text strings, to the complex nodes:
4114 sequences, mappings and the registered objects.
4116 Note that file nodes are only used for navigating file storages opened for reading.
4117 When a file storage is opened for writing, no data is stored in memory after it is written.
4119 class CV_EXPORTS_W_SIMPLE FileNode
4122 //! type of the file storage node
4125 NONE=0, //!< empty node
4126 INT=1, //!< an integer
4127 REAL=2, //!< floating-point number
4128 FLOAT=REAL, //!< synonym or REAL
4129 STR=3, //!< text string in UTF-8 encoding
4130 STRING=STR, //!< synonym for STR
4131 REF=4, //!< integer of size size_t. Typically used for storing complex dynamic structures where some elements reference the others
4132 SEQ=5, //!< sequence
4135 FLOW=8, //!< compact representation of a sequence or mapping. Used only by YAML writer
4136 USER=16, //!< a registered object (e.g. a matrix)
4137 EMPTY=32, //!< empty structure (sequence or mapping)
4138 NAMED=64 //!< the node has a name (i.e. it is element of a mapping)
4140 //! the default constructor
4142 //! the full constructor wrapping CvFileNode structure.
4143 FileNode(const CvFileStorage* fs, const CvFileNode* node);
4144 //! the copy constructor
4145 FileNode(const FileNode& node);
4146 //! returns element of a mapping node
4147 FileNode operator[](const string& nodename) const;
4148 //! returns element of a mapping node
4149 CV_WRAP FileNode operator[](const char* nodename) const;
4150 //! returns element of a sequence node
4151 CV_WRAP FileNode operator[](int i) const;
4152 //! returns type of the node
4153 CV_WRAP int type() const;
4155 //! returns true if the node is empty
4156 CV_WRAP bool empty() const;
4157 //! returns true if the node is a "none" object
4158 CV_WRAP bool isNone() const;
4159 //! returns true if the node is a sequence
4160 CV_WRAP bool isSeq() const;
4161 //! returns true if the node is a mapping
4162 CV_WRAP bool isMap() const;
4163 //! returns true if the node is an integer
4164 CV_WRAP bool isInt() const;
4165 //! returns true if the node is a floating-point number
4166 CV_WRAP bool isReal() const;
4167 //! returns true if the node is a text string
4168 CV_WRAP bool isString() const;
4169 //! returns true if the node has a name
4170 CV_WRAP bool isNamed() const;
4171 //! returns the node name or an empty string if the node is nameless
4172 CV_WRAP string name() const;
4173 //! returns the number of elements in the node, if it is a sequence or mapping, or 1 otherwise.
4174 CV_WRAP size_t size() const;
4175 //! returns the node content as an integer. If the node stores floating-point number, it is rounded.
4176 operator int() const;
4177 //! returns the node content as float
4178 operator float() const;
4179 //! returns the node content as double
4180 operator double() const;
4181 //! returns the node content as text string
4182 operator string() const;
4184 //! returns pointer to the underlying file node
4185 CvFileNode* operator *();
4186 //! returns pointer to the underlying file node
4187 const CvFileNode* operator* () const;
4189 //! returns iterator pointing to the first node element
4190 FileNodeIterator begin() const;
4191 //! returns iterator pointing to the element following the last node element
4192 FileNodeIterator end() const;
4194 //! reads node elements to the buffer with the specified format
4195 void readRaw( const string& fmt, uchar* vec, size_t len ) const;
4196 //! reads the registered object and returns pointer to it
4197 void* readObj() const;
4199 // do not use wrapper pointer classes for better efficiency
4200 const CvFileStorage* fs;
4201 const CvFileNode* node;
4208 The class is used for iterating sequences (usually) and mappings.
4210 class CV_EXPORTS FileNodeIterator
4213 //! the default constructor
4215 //! the full constructor set to the ofs-th element of the node
4216 FileNodeIterator(const CvFileStorage* fs, const CvFileNode* node, size_t ofs=0);
4217 //! the copy constructor
4218 FileNodeIterator(const FileNodeIterator& it);
4219 //! returns the currently observed element
4220 FileNode operator *() const;
4221 //! accesses the currently observed element methods
4222 FileNode operator ->() const;
4224 //! moves iterator to the next node
4225 FileNodeIterator& operator ++ ();
4226 //! moves iterator to the next node
4227 FileNodeIterator operator ++ (int);
4228 //! moves iterator to the previous node
4229 FileNodeIterator& operator -- ();
4230 //! moves iterator to the previous node
4231 FileNodeIterator operator -- (int);
4232 //! moves iterator forward by the specified offset (possibly negative)
4233 FileNodeIterator& operator += (int ofs);
4234 //! moves iterator backward by the specified offset (possibly negative)
4235 FileNodeIterator& operator -= (int ofs);
4237 //! reads the next maxCount elements (or less, if the sequence/mapping last element occurs earlier) to the buffer with the specified format
4238 FileNodeIterator& readRaw( const string& fmt, uchar* vec,
4239 size_t maxCount=(size_t)INT_MAX );
4241 const CvFileStorage* fs;
4242 const CvFileNode* container;
4247 ////////////// convenient wrappers for operating old-style dynamic structures //////////////
4249 template<typename _Tp> class SeqIterator;
4251 typedef Ptr<CvMemStorage> MemStorage;
4254 Template Sequence Class derived from CvSeq
4256 The class provides more convenient access to sequence elements,
4257 STL-style operations and iterators.
4259 \note The class is targeted for simple data types,
4260 i.e. no constructors or destructors
4261 are called for the sequence elements.
4263 template<typename _Tp> class Seq
4266 typedef SeqIterator<_Tp> iterator;
4267 typedef SeqIterator<_Tp> const_iterator;
4269 //! the default constructor
4271 //! the constructor for wrapping CvSeq structure. The real element type in CvSeq should match _Tp.
4272 Seq(const CvSeq* seq);
4273 //! creates the empty sequence that resides in the specified storage
4274 Seq(MemStorage& storage, int headerSize = sizeof(CvSeq));
4275 //! returns read-write reference to the specified element
4276 _Tp& operator [](int idx);
4277 //! returns read-only reference to the specified element
4278 const _Tp& operator[](int idx) const;
4279 //! returns iterator pointing to the beginning of the sequence
4280 SeqIterator<_Tp> begin() const;
4281 //! returns iterator pointing to the element following the last sequence element
4282 SeqIterator<_Tp> end() const;
4283 //! returns the number of elements in the sequence
4284 size_t size() const;
4285 //! returns the type of sequence elements (CV_8UC1 ... CV_64FC(CV_CN_MAX) ...)
4287 //! returns the depth of sequence elements (CV_8U ... CV_64F)
4289 //! returns the number of channels in each sequence element
4290 int channels() const;
4291 //! returns the size of each sequence element
4292 size_t elemSize() const;
4293 //! returns index of the specified sequence element
4294 size_t index(const _Tp& elem) const;
4295 //! appends the specified element to the end of the sequence
4296 void push_back(const _Tp& elem);
4297 //! appends the specified element to the front of the sequence
4298 void push_front(const _Tp& elem);
4299 //! appends zero or more elements to the end of the sequence
4300 void push_back(const _Tp* elems, size_t count);
4301 //! appends zero or more elements to the front of the sequence
4302 void push_front(const _Tp* elems, size_t count);
4303 //! inserts the specified element to the specified position
4304 void insert(int idx, const _Tp& elem);
4305 //! inserts zero or more elements to the specified position
4306 void insert(int idx, const _Tp* elems, size_t count);
4307 //! removes element at the specified position
4308 void remove(int idx);
4309 //! removes the specified subsequence
4310 void remove(const Range& r);
4312 //! returns reference to the first sequence element
4314 //! returns read-only reference to the first sequence element
4315 const _Tp& front() const;
4316 //! returns reference to the last sequence element
4318 //! returns read-only reference to the last sequence element
4319 const _Tp& back() const;
4320 //! returns true iff the sequence contains no elements
4323 //! removes all the elements from the sequence
4325 //! removes the first element from the sequence
4327 //! removes the last element from the sequence
4329 //! removes zero or more elements from the beginning of the sequence
4330 void pop_front(_Tp* elems, size_t count);
4331 //! removes zero or more elements from the end of the sequence
4332 void pop_back(_Tp* elems, size_t count);
4334 //! copies the whole sequence or the sequence slice to the specified vector
4335 void copyTo(vector<_Tp>& vec, const Range& range=Range::all()) const;
4336 //! returns the vector containing all the sequence elements
4337 operator vector<_Tp>() const;
4344 STL-style Sequence Iterator inherited from the CvSeqReader structure
4346 template<typename _Tp> class SeqIterator : public CvSeqReader
4349 //! the default constructor
4351 //! the constructor setting the iterator to the beginning or to the end of the sequence
4352 SeqIterator(const Seq<_Tp>& seq, bool seekEnd=false);
4353 //! positions the iterator within the sequence
4354 void seek(size_t pos);
4355 //! reports the current iterator position
4356 size_t tell() const;
4357 //! returns reference to the current sequence element
4359 //! returns read-only reference to the current sequence element
4360 const _Tp& operator *() const;
4361 //! moves iterator to the next sequence element
4362 SeqIterator& operator ++();
4363 //! moves iterator to the next sequence element
4364 SeqIterator operator ++(int) const;
4365 //! moves iterator to the previous sequence element
4366 SeqIterator& operator --();
4367 //! moves iterator to the previous sequence element
4368 SeqIterator operator --(int) const;
4370 //! moves iterator forward by the specified offset (possibly negative)
4371 SeqIterator& operator +=(int);
4372 //! moves iterator backward by the specified offset (possibly negative)
4373 SeqIterator& operator -=(int);
4375 // this is index of the current element module seq->total*2
4376 // (to distinguish between 0 and seq->total)
4381 class CV_EXPORTS Algorithm;
4382 class CV_EXPORTS AlgorithmInfo;
4383 struct CV_EXPORTS AlgorithmInfoData;
4385 template<typename _Tp> struct ParamType {};
4388 Base class for high-level OpenCV algorithms
4390 class CV_EXPORTS_W Algorithm
4394 virtual ~Algorithm();
4395 string name() const;
4397 template<typename _Tp> typename ParamType<_Tp>::member_type get(const string& name) const;
4398 template<typename _Tp> typename ParamType<_Tp>::member_type get(const char* name) const;
4400 CV_WRAP int getInt(const string& name) const;
4401 CV_WRAP double getDouble(const string& name) const;
4402 CV_WRAP bool getBool(const string& name) const;
4403 CV_WRAP string getString(const string& name) const;
4404 CV_WRAP Mat getMat(const string& name) const;
4405 CV_WRAP vector<Mat> getMatVector(const string& name) const;
4406 CV_WRAP Ptr<Algorithm> getAlgorithm(const string& name) const;
4408 void set(const string& name, int value);
4409 void set(const string& name, double value);
4410 void set(const string& name, bool value);
4411 void set(const string& name, const string& value);
4412 void set(const string& name, const Mat& value);
4413 void set(const string& name, const vector<Mat>& value);
4414 void set(const string& name, const Ptr<Algorithm>& value);
4415 template<typename _Tp> void set(const string& name, const Ptr<_Tp>& value);
4417 CV_WRAP void setInt(const string& name, int value);
4418 CV_WRAP void setDouble(const string& name, double value);
4419 CV_WRAP void setBool(const string& name, bool value);
4420 CV_WRAP void setString(const string& name, const string& value);
4421 CV_WRAP void setMat(const string& name, const Mat& value);
4422 CV_WRAP void setMatVector(const string& name, const vector<Mat>& value);
4423 CV_WRAP void setAlgorithm(const string& name, const Ptr<Algorithm>& value);
4424 template<typename _Tp> void setAlgorithm(const string& name, const Ptr<_Tp>& value);
4426 void set(const char* name, int value);
4427 void set(const char* name, double value);
4428 void set(const char* name, bool value);
4429 void set(const char* name, const string& value);
4430 void set(const char* name, const Mat& value);
4431 void set(const char* name, const vector<Mat>& value);
4432 void set(const char* name, const Ptr<Algorithm>& value);
4433 template<typename _Tp> void set(const char* name, const Ptr<_Tp>& value);
4435 void setInt(const char* name, int value);
4436 void setDouble(const char* name, double value);
4437 void setBool(const char* name, bool value);
4438 void setString(const char* name, const string& value);
4439 void setMat(const char* name, const Mat& value);
4440 void setMatVector(const char* name, const vector<Mat>& value);
4441 void setAlgorithm(const char* name, const Ptr<Algorithm>& value);
4442 template<typename _Tp> void setAlgorithm(const char* name, const Ptr<_Tp>& value);
4444 CV_WRAP string paramHelp(const string& name) const;
4445 int paramType(const char* name) const;
4446 CV_WRAP int paramType(const string& name) const;
4447 CV_WRAP void getParams(CV_OUT vector<string>& names) const;
4450 virtual void write(FileStorage& fs) const;
4451 virtual void read(const FileNode& fn);
4453 typedef Algorithm* (*Constructor)(void);
4454 typedef int (Algorithm::*Getter)() const;
4455 typedef void (Algorithm::*Setter)(int);
4457 CV_WRAP static void getList(CV_OUT vector<string>& algorithms);
4458 CV_WRAP static Ptr<Algorithm> _create(const string& name);
4459 template<typename _Tp> static Ptr<_Tp> create(const string& name);
4461 virtual AlgorithmInfo* info() const /* TODO: make it = 0;*/ { return 0; }
4465 class CV_EXPORTS AlgorithmInfo
4468 friend class Algorithm;
4469 AlgorithmInfo(const string& name, Algorithm::Constructor create);
4471 void get(const Algorithm* algo, const char* name, int argType, void* value) const;
4472 void addParam_(Algorithm& algo, const char* name, int argType,
4473 void* value, bool readOnly,
4474 Algorithm::Getter getter, Algorithm::Setter setter,
4475 const string& help=string());
4476 string paramHelp(const char* name) const;
4477 int paramType(const char* name) const;
4478 void getParams(vector<string>& names) const;
4480 void write(const Algorithm* algo, FileStorage& fs) const;
4481 void read(Algorithm* algo, const FileNode& fn) const;
4482 string name() const;
4484 void addParam(Algorithm& algo, const char* name,
4485 int& value, bool readOnly=false,
4486 int (Algorithm::*getter)()=0,
4487 void (Algorithm::*setter)(int)=0,
4488 const string& help=string());
4489 void addParam(Algorithm& algo, const char* name,
4490 short& value, bool readOnly=false,
4491 int (Algorithm::*getter)()=0,
4492 void (Algorithm::*setter)(int)=0,
4493 const string& help=string());
4494 void addParam(Algorithm& algo, const char* name,
4495 bool& value, bool readOnly=false,
4496 int (Algorithm::*getter)()=0,
4497 void (Algorithm::*setter)(int)=0,
4498 const string& help=string());
4499 void addParam(Algorithm& algo, const char* name,
4500 double& value, bool readOnly=false,
4501 double (Algorithm::*getter)()=0,
4502 void (Algorithm::*setter)(double)=0,
4503 const string& help=string());
4504 void addParam(Algorithm& algo, const char* name,
4505 string& value, bool readOnly=false,
4506 string (Algorithm::*getter)()=0,
4507 void (Algorithm::*setter)(const string&)=0,
4508 const string& help=string());
4509 void addParam(Algorithm& algo, const char* name,
4510 Mat& value, bool readOnly=false,
4511 Mat (Algorithm::*getter)()=0,
4512 void (Algorithm::*setter)(const Mat&)=0,
4513 const string& help=string());
4514 void addParam(Algorithm& algo, const char* name,
4515 vector<Mat>& value, bool readOnly=false,
4516 vector<Mat> (Algorithm::*getter)()=0,
4517 void (Algorithm::*setter)(const vector<Mat>&)=0,
4518 const string& help=string());
4519 void addParam(Algorithm& algo, const char* name,
4520 Ptr<Algorithm>& value, bool readOnly=false,
4521 Ptr<Algorithm> (Algorithm::*getter)()=0,
4522 void (Algorithm::*setter)(const Ptr<Algorithm>&)=0,
4523 const string& help=string());
4524 void addParam(Algorithm& algo, const char* name,
4525 float& value, bool readOnly=false,
4526 float (Algorithm::*getter)()=0,
4527 void (Algorithm::*setter)(float)=0,
4528 const string& help=string());
4529 void addParam(Algorithm& algo, const char* name,
4530 unsigned int& value, bool readOnly=false,
4531 unsigned int (Algorithm::*getter)()=0,
4532 void (Algorithm::*setter)(unsigned int)=0,
4533 const string& help=string());
4534 void addParam(Algorithm& algo, const char* name,
4535 uint64& value, bool readOnly=false,
4536 uint64 (Algorithm::*getter)()=0,
4537 void (Algorithm::*setter)(uint64)=0,
4538 const string& help=string());
4539 void addParam(Algorithm& algo, const char* name,
4540 uchar& value, bool readOnly=false,
4541 uchar (Algorithm::*getter)()=0,
4542 void (Algorithm::*setter)(uchar)=0,
4543 const string& help=string());
4544 template<typename _Tp, typename _Base> void addParam(Algorithm& algo, const char* name,
4545 Ptr<_Tp>& value, bool readOnly=false,
4546 Ptr<_Tp> (Algorithm::*getter)()=0,
4547 void (Algorithm::*setter)(const Ptr<_Tp>&)=0,
4548 const string& help=string());
4549 template<typename _Tp> void addParam(Algorithm& algo, const char* name,
4550 Ptr<_Tp>& value, bool readOnly=false,
4551 Ptr<_Tp> (Algorithm::*getter)()=0,
4552 void (Algorithm::*setter)(const Ptr<_Tp>&)=0,
4553 const string& help=string());
4555 AlgorithmInfoData* data;
4556 void set(Algorithm* algo, const char* name, int argType,
4557 const void* value, bool force=false) const;
4561 struct CV_EXPORTS Param
4563 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 };
4566 Param(int _type, bool _readonly, int _offset,
4567 Algorithm::Getter _getter=0,
4568 Algorithm::Setter _setter=0,
4569 const string& _help=string());
4573 Algorithm::Getter getter;
4574 Algorithm::Setter setter;
4578 template<> struct ParamType<bool>
4580 typedef bool const_param_type;
4581 typedef bool member_type;
4583 enum { type = Param::BOOLEAN };
4586 template<> struct ParamType<int>
4588 typedef int const_param_type;
4589 typedef int member_type;
4591 enum { type = Param::INT };
4594 template<> struct ParamType<short>
4596 typedef int const_param_type;
4597 typedef int member_type;
4599 enum { type = Param::SHORT };
4602 template<> struct ParamType<double>
4604 typedef double const_param_type;
4605 typedef double member_type;
4607 enum { type = Param::REAL };
4610 template<> struct ParamType<string>
4612 typedef const string& const_param_type;
4613 typedef string member_type;
4615 enum { type = Param::STRING };
4618 template<> struct ParamType<Mat>
4620 typedef const Mat& const_param_type;
4621 typedef Mat member_type;
4623 enum { type = Param::MAT };
4626 template<> struct ParamType<vector<Mat> >
4628 typedef const vector<Mat>& const_param_type;
4629 typedef vector<Mat> member_type;
4631 enum { type = Param::MAT_VECTOR };
4634 template<> struct ParamType<Algorithm>
4636 typedef const Ptr<Algorithm>& const_param_type;
4637 typedef Ptr<Algorithm> member_type;
4639 enum { type = Param::ALGORITHM };
4642 template<> struct ParamType<float>
4644 typedef float const_param_type;
4645 typedef float member_type;
4647 enum { type = Param::FLOAT };
4650 template<> struct ParamType<unsigned>
4652 typedef unsigned const_param_type;
4653 typedef unsigned member_type;
4655 enum { type = Param::UNSIGNED_INT };
4658 template<> struct ParamType<uint64>
4660 typedef uint64 const_param_type;
4661 typedef uint64 member_type;
4663 enum { type = Param::UINT64 };
4666 template<> struct ParamType<uchar>
4668 typedef uchar const_param_type;
4669 typedef uchar member_type;
4671 enum { type = Param::UCHAR };
4675 "\nThe CommandLineParser class is designed for command line arguments parsing\n"
4677 "Before you start to work with CommandLineParser you have to create a map for keys.\n"
4678 " It will look like this\n"
4679 " const char* keys =\n"
4681 " { s| string| 123asd |string parameter}\n"
4682 " { d| digit | 100 |digit parameter }\n"
4683 " { c|noCamera|false |without camera }\n"
4684 " { 1| |some text|help }\n"
4685 " { 2| |333 |another help }\n"
4688 " \"{\" - start of parameter string.\n"
4689 " \"}\" - end of parameter string\n"
4690 " \"|\" - separator between short name, full name, default value and help\n"
4691 "Supported syntax: \n"
4692 " --key1=arg1 <If a key with '--' must has an argument\n"
4693 " you have to assign it through '=' sign.> \n"
4694 "<If the key with '--' doesn't have any argument, it means that it is a bool key>\n"
4695 " -key2=arg2 <If a key with '-' must has an argument \n"
4696 " you have to assign it through '=' sign.> \n"
4697 "If the key with '-' doesn't have any argument, it means that it is a bool key\n"
4698 " key3 <This key can't has any parameter> \n"
4700 " Imagine that the input parameters are next:\n"
4701 " -s=string_value --digit=250 --noCamera lena.jpg 10000\n"
4702 " CommandLineParser parser(argc, argv, keys) - create a parser object\n"
4703 " parser.get<string>(\"s\" or \"string\") will return you first parameter value\n"
4704 " parser.get<string>(\"s\", false or \"string\", false) will return you first parameter value\n"
4705 " without spaces in end and begin\n"
4706 " parser.get<int>(\"d\" or \"digit\") will return you second parameter value.\n"
4707 " It also works with 'unsigned int', 'double', and 'float' types>\n"
4708 " parser.get<bool>(\"c\" or \"noCamera\") will return you true .\n"
4709 " If you enter this key in commandline>\n"
4710 " It return you false otherwise.\n"
4711 " parser.get<string>(\"1\") will return you the first argument without parameter (lena.jpg) \n"
4712 " parser.get<int>(\"2\") will return you the second argument without parameter (10000)\n"
4713 " It also works with 'unsigned int', 'double', and 'float' types \n"
4715 class CV_EXPORTS CommandLineParser
4719 //! the default constructor
4720 CommandLineParser(int argc, const char* const argv[], const char* key_map);
4722 //! get parameter, you can choose: delete spaces in end and begin or not
4723 template<typename _Tp>
4724 _Tp get(const std::string& name, bool space_delete=true)
4730 std::string str = getString(name);
4731 return analyzeValue<_Tp>(str, space_delete);
4734 //! print short name, full name, current value and help for all params
4738 std::map<std::string, std::vector<std::string> > data;
4739 std::string getString(const std::string& name);
4741 bool has(const std::string& keys);
4743 template<typename _Tp>
4744 _Tp analyzeValue(const std::string& str, bool space_delete=false);
4746 template<typename _Tp>
4747 static _Tp getData(const std::string& str)
4750 std::stringstream s1(str);
4755 template<typename _Tp>
4756 _Tp fromStringNumber(const std::string& str);//the default conversion function for numbers
4760 template<> CV_EXPORTS
4761 bool CommandLineParser::get<bool>(const std::string& name, bool space_delete);
4763 template<> CV_EXPORTS
4764 std::string CommandLineParser::analyzeValue<std::string>(const std::string& str, bool space_delete);
4766 template<> CV_EXPORTS
4767 int CommandLineParser::analyzeValue<int>(const std::string& str, bool space_delete);
4769 template<> CV_EXPORTS
4770 unsigned int CommandLineParser::analyzeValue<unsigned int>(const std::string& str, bool space_delete);
4772 template<> CV_EXPORTS
4773 uint64 CommandLineParser::analyzeValue<uint64>(const std::string& str, bool space_delete);
4775 template<> CV_EXPORTS
4776 float CommandLineParser::analyzeValue<float>(const std::string& str, bool space_delete);
4778 template<> CV_EXPORTS
4779 double CommandLineParser::analyzeValue<double>(const std::string& str, bool space_delete);
4782 /////////////////////////////// Parallel Primitives //////////////////////////////////
4784 // a base body class
4785 class CV_EXPORTS ParallelLoopBody
4788 virtual ~ParallelLoopBody();
4789 virtual void operator() (const Range& range) const = 0;
4792 CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.);
4794 /////////////////////////// Synchronization Primitives ///////////////////////////////
4796 class CV_EXPORTS Mutex
4801 Mutex(const Mutex& m);
4802 Mutex& operator = (const Mutex& m);
4813 class CV_EXPORTS AutoLock
4816 AutoLock(Mutex& m) : mutex(&m) { mutex->lock(); }
4817 ~AutoLock() { mutex->unlock(); }
4821 AutoLock(const AutoLock&);
4822 AutoLock& operator = (const AutoLock&);
4825 class TLSDataContainer
4830 CV_EXPORTS TLSDataContainer();
4831 CV_EXPORTS ~TLSDataContainer(); // virtual is not required
4833 virtual void* createDataInstance() const = 0;
4834 virtual void deleteDataInstance(void* data) const = 0;
4836 CV_EXPORTS void* getData() const;
4839 template <typename T>
4840 class TLSData : protected TLSDataContainer
4844 inline ~TLSData() {}
4845 inline T* get() const { return (T*)getData(); }
4847 virtual void* createDataInstance() const { return new T; }
4848 virtual void deleteDataInstance(void* data) const { delete (T*)data; }
4853 #endif // __cplusplus
4855 #include "opencv2/core/operations.hpp"
4856 #include "opencv2/core/mat.hpp"
4858 #endif /*__OPENCV_CORE_HPP__*/