5fd92721354da2ef2a5138e7b5e8b19110e901e8
[profile/ivi/opencv.git] / modules / core / include / opencv2 / core / core.hpp
1 /*! \file core.hpp
2     \brief The Core Functionality
3  */
4 /*M///////////////////////////////////////////////////////////////////////////////////////
5 //
6 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
7 //
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.
11 //
12 //
13 //                           License Agreement
14 //                For Open Source Computer Vision Library
15 //
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.
19 //
20 // Redistribution and use in source and binary forms, with or without modification,
21 // are permitted provided that the following conditions are met:
22 //
23 //   * Redistribution's of source code must retain the above copyright notice,
24 //     this list of conditions and the following disclaimer.
25 //
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.
29 //
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.
32 //
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.
43 //
44 //M*/
45
46 #ifndef __OPENCV_CORE_HPP__
47 #define __OPENCV_CORE_HPP__
48
49 #include "opencv2/core/types_c.h"
50 #include "opencv2/core/version.hpp"
51
52 #ifdef __cplusplus
53
54 #ifndef SKIP_INCLUDES
55 #include <limits.h>
56 #include <algorithm>
57 #include <cmath>
58 #include <cstddef>
59 #include <complex>
60 #include <map>
61 #include <new>
62 #include <string>
63 #include <vector>
64 #include <sstream>
65 #endif // SKIP_INCLUDES
66
67 /*! \namespace cv
68     Namespace where all the C++ OpenCV functionality resides
69 */
70 namespace cv {
71
72 #undef abs
73 #undef min
74 #undef max
75 #undef Complex
76
77 using std::vector;
78 using std::string;
79 using std::ptrdiff_t;
80
81 template<typename _Tp> class CV_EXPORTS Size_;
82 template<typename _Tp> class CV_EXPORTS Point_;
83 template<typename _Tp> class CV_EXPORTS Rect_;
84 template<typename _Tp, int cn> class CV_EXPORTS Vec;
85 template<typename _Tp, int m, int n> class CV_EXPORTS Matx;
86
87 typedef std::string String;
88
89 class Mat;
90 class SparseMat;
91 typedef Mat MatND;
92
93 class GlBuffer;
94 class GlTexture;
95 class GlArrays;
96 class GlCamera;
97
98 namespace gpu {
99     class GpuMat;
100 }
101
102 class CV_EXPORTS MatExpr;
103 class CV_EXPORTS MatOp_Base;
104 class CV_EXPORTS MatArg;
105 class CV_EXPORTS MatConstIterator;
106
107 template<typename _Tp> class CV_EXPORTS Mat_;
108 template<typename _Tp> class CV_EXPORTS MatIterator_;
109 template<typename _Tp> class CV_EXPORTS MatConstIterator_;
110 template<typename _Tp> class CV_EXPORTS MatCommaInitializer_;
111
112 #if !defined(ANDROID) || (defined(_GLIBCXX_USE_WCHAR_T) && _GLIBCXX_USE_WCHAR_T)
113 typedef std::basic_string<wchar_t> WString;
114
115 CV_EXPORTS string fromUtf16(const WString& str);
116 CV_EXPORTS WString toUtf16(const string& str);
117 #endif
118
119 CV_EXPORTS string format( const char* fmt, ... );
120 CV_EXPORTS string tempfile( const char* suffix CV_DEFAULT(0));
121
122 // matrix decomposition types
123 enum { DECOMP_LU=0, DECOMP_SVD=1, DECOMP_EIG=2, DECOMP_CHOLESKY=3, DECOMP_QR=4, DECOMP_NORMAL=16 };
124 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 };
125 enum { CMP_EQ=0, CMP_GT=1, CMP_GE=2, CMP_LT=3, CMP_LE=4, CMP_NE=5 };
126 enum { GEMM_1_T=1, GEMM_2_T=2, GEMM_3_T=4 };
127 enum { DFT_INVERSE=1, DFT_SCALE=2, DFT_ROWS=4, DFT_COMPLEX_OUTPUT=16, DFT_REAL_OUTPUT=32,
128     DCT_INVERSE = DFT_INVERSE, DCT_ROWS=DFT_ROWS };
129
130
131 /*!
132  The standard OpenCV exception class.
133  Instances of the class are thrown by various functions and methods in the case of critical errors.
134  */
135 class CV_EXPORTS Exception : public std::exception
136 {
137 public:
138     /*!
139      Default constructor
140      */
141     Exception();
142     /*!
143      Full constructor. Normally the constuctor is not called explicitly.
144      Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used.
145     */
146     Exception(int _code, const string& _err, const string& _func, const string& _file, int _line);
147     virtual ~Exception() throw();
148
149     /*!
150      \return the error description and the context as a text string.
151     */
152     virtual const char *what() const throw();
153     void formatMessage();
154
155     string msg; ///< the formatted error message
156
157     int code; ///< error code @see CVStatus
158     string err; ///< error description
159     string func; ///< function name. Available only when the compiler supports __func__ macro
160     string file; ///< source file name where the error has occured
161     int line; ///< line number in the source file where the error has occured
162 };
163
164
165 //! Signals an error and raises the exception.
166
167 /*!
168   By default the function prints information about the error to stderr,
169   then it either stops if setBreakOnError() had been called before or raises the exception.
170   It is possible to alternate error processing by using redirectError().
171
172   \param exc the exception raisen.
173  */
174 CV_EXPORTS void error( const Exception& exc );
175
176 //! Sets/resets the break-on-error mode.
177
178 /*!
179   When the break-on-error mode is set, the default error handler
180   issues a hardware exception, which can make debugging more convenient.
181
182   \return the previous state
183  */
184 CV_EXPORTS bool setBreakOnError(bool flag);
185
186 typedef int (CV_CDECL *ErrorCallback)( int status, const char* func_name,
187                                        const char* err_msg, const char* file_name,
188                                        int line, void* userdata );
189
190 //! Sets the new error handler and the optional user data.
191
192 /*!
193   The function sets the new error handler, called from cv::error().
194
195   \param errCallback the new error handler. If NULL, the default error handler is used.
196   \param userdata the optional user data pointer, passed to the callback.
197   \param prevUserdata the optional output parameter where the previous user data pointer is stored
198
199   \return the previous error handler
200 */
201 CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback,
202                                         void* userdata=0, void** prevUserdata=0);
203
204 #ifdef __GNUC__
205 #define CV_Error( code, msg ) cv::error( cv::Exception(code, msg, __func__, __FILE__, __LINE__) )
206 #define CV_Error_( code, args ) cv::error( cv::Exception(code, cv::format args, __func__, __FILE__, __LINE__) )
207 #define CV_Assert( expr ) if((expr)) ; else cv::error( cv::Exception(CV_StsAssert, #expr, __func__, __FILE__, __LINE__) )
208 #else
209 #define CV_Error( code, msg ) cv::error( cv::Exception(code, msg, "", __FILE__, __LINE__) )
210 #define CV_Error_( code, args ) cv::error( cv::Exception(code, cv::format args, "", __FILE__, __LINE__) )
211 #define CV_Assert( expr ) if((expr)) ; else cv::error( cv::Exception(CV_StsAssert, #expr, "", __FILE__, __LINE__) )
212 #endif
213
214 #ifdef _DEBUG
215 #define CV_DbgAssert(expr) CV_Assert(expr)
216 #else
217 #define CV_DbgAssert(expr)
218 #endif
219
220 CV_EXPORTS void setNumThreads(int nthreads);
221 CV_EXPORTS int getNumThreads();
222 CV_EXPORTS int getThreadNum();
223
224 CV_EXPORTS_W const std::string& getBuildInformation();
225
226 //! Returns the number of ticks.
227
228 /*!
229   The function returns the number of ticks since the certain event (e.g. when the machine was turned on).
230   It can be used to initialize cv::RNG or to measure a function execution time by reading the tick count
231   before and after the function call. The granularity of ticks depends on the hardware and OS used. Use
232   cv::getTickFrequency() to convert ticks to seconds.
233 */
234 CV_EXPORTS_W int64 getTickCount();
235
236 /*!
237   Returns the number of ticks per seconds.
238
239   The function returns the number of ticks (as returned by cv::getTickCount()) per second.
240   The following code computes the execution time in milliseconds:
241
242   \code
243   double exec_time = (double)getTickCount();
244   // do something ...
245   exec_time = ((double)getTickCount() - exec_time)*1000./getTickFrequency();
246   \endcode
247 */
248 CV_EXPORTS_W double getTickFrequency();
249
250 /*!
251   Returns the number of CPU ticks.
252
253   On platforms where the feature is available, the function returns the number of CPU ticks
254   since the certain event (normally, the system power-on moment). Using this function
255   one can accurately measure the execution time of very small code fragments,
256   for which cv::getTickCount() granularity is not enough.
257 */
258 CV_EXPORTS_W int64 getCPUTickCount();
259
260 /*!
261   Returns SSE etc. support status
262
263   The function returns true if certain hardware features are available.
264   Currently, the following features are recognized:
265   - CV_CPU_MMX - MMX
266   - CV_CPU_SSE - SSE
267   - CV_CPU_SSE2 - SSE 2
268   - CV_CPU_SSE3 - SSE 3
269   - CV_CPU_SSSE3 - SSSE 3
270   - CV_CPU_SSE4_1 - SSE 4.1
271   - CV_CPU_SSE4_2 - SSE 4.2
272   - CV_CPU_POPCNT - POPCOUNT
273   - CV_CPU_AVX - AVX
274
275   \note {Note that the function output is not static. Once you called cv::useOptimized(false),
276   most of the hardware acceleration is disabled and thus the function will returns false,
277   until you call cv::useOptimized(true)}
278 */
279 CV_EXPORTS_W bool checkHardwareSupport(int feature);
280
281 //! returns the number of CPUs (including hyper-threading)
282 CV_EXPORTS_W int getNumberOfCPUs();
283
284 /*!
285   Allocates memory buffer
286
287   This is specialized OpenCV memory allocation function that returns properly aligned memory buffers.
288   The usage is identical to malloc(). The allocated buffers must be freed with cv::fastFree().
289   If there is not enough memory, the function calls cv::error(), which raises an exception.
290
291   \param bufSize buffer size in bytes
292   \return the allocated memory buffer.
293 */
294 CV_EXPORTS void* fastMalloc(size_t bufSize);
295
296 /*!
297   Frees the memory allocated with cv::fastMalloc
298
299   This is the corresponding deallocation function for cv::fastMalloc().
300   When ptr==NULL, the function has no effect.
301 */
302 CV_EXPORTS void fastFree(void* ptr);
303
304 template<typename _Tp> static inline _Tp* allocate(size_t n)
305 {
306     return new _Tp[n];
307 }
308
309 template<typename _Tp> static inline void deallocate(_Tp* ptr, size_t)
310 {
311     delete[] ptr;
312 }
313
314 /*!
315   Aligns pointer by the certain number of bytes
316
317   This small inline function aligns the pointer by the certian number of bytes by shifting
318   it forward by 0 or a positive offset.
319 */
320 template<typename _Tp> static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp))
321 {
322     return (_Tp*)(((size_t)ptr + n-1) & -n);
323 }
324
325 /*!
326   Aligns buffer size by the certain number of bytes
327
328   This small inline function aligns a buffer size by the certian number of bytes by enlarging it.
329 */
330 static inline size_t alignSize(size_t sz, int n)
331 {
332     return (sz + n-1) & -n;
333 }
334
335 /*!
336   Turns on/off available optimization
337
338   The function turns on or off the optimized code in OpenCV. Some optimization can not be enabled
339   or disabled, but, for example, most of SSE code in OpenCV can be temporarily turned on or off this way.
340
341   \note{Since optimization may imply using special data structures, it may be unsafe
342   to call this function anywhere in the code. Instead, call it somewhere at the top level.}
343 */
344 CV_EXPORTS_W void setUseOptimized(bool onoff);
345
346 /*!
347   Returns the current optimization status
348
349   The function returns the current optimization status, which is controlled by cv::setUseOptimized().
350 */
351 CV_EXPORTS_W bool useOptimized();
352
353 /*!
354   The STL-compilant memory Allocator based on cv::fastMalloc() and cv::fastFree()
355 */
356 template<typename _Tp> class CV_EXPORTS Allocator
357 {
358 public:
359     typedef _Tp value_type;
360     typedef value_type* pointer;
361     typedef const value_type* const_pointer;
362     typedef value_type& reference;
363     typedef const value_type& const_reference;
364     typedef size_t size_type;
365     typedef ptrdiff_t difference_type;
366     template<typename U> class rebind { typedef Allocator<U> other; };
367
368     explicit Allocator() {}
369     ~Allocator() {}
370     explicit Allocator(Allocator const&) {}
371     template<typename U>
372     explicit Allocator(Allocator<U> const&) {}
373
374     // address
375     pointer address(reference r) { return &r; }
376     const_pointer address(const_reference r) { return &r; }
377
378     pointer allocate(size_type count, const void* =0)
379     { return reinterpret_cast<pointer>(fastMalloc(count * sizeof (_Tp))); }
380
381     void deallocate(pointer p, size_type) {fastFree(p); }
382
383     size_type max_size() const
384     { return max(static_cast<_Tp>(-1)/sizeof(_Tp), 1); }
385
386     void construct(pointer p, const _Tp& v) { new(static_cast<void*>(p)) _Tp(v); }
387     void destroy(pointer p) { p->~_Tp(); }
388 };
389
390 /////////////////////// Vec (used as element of multi-channel images /////////////////////
391
392 /*!
393   A helper class for cv::DataType
394
395   The class is specialized for each fundamental numerical data type supported by OpenCV.
396   It provides DataDepth<T>::value constant.
397 */
398 template<typename _Tp> class CV_EXPORTS DataDepth {};
399
400 template<> class DataDepth<bool> { public: enum { value = CV_8U, fmt=(int)'u' }; };
401 template<> class DataDepth<uchar> { public: enum { value = CV_8U, fmt=(int)'u' }; };
402 template<> class DataDepth<schar> { public: enum { value = CV_8S, fmt=(int)'c' }; };
403 template<> class DataDepth<char> { public: enum { value = CV_8S, fmt=(int)'c' }; };
404 template<> class DataDepth<ushort> { public: enum { value = CV_16U, fmt=(int)'w' }; };
405 template<> class DataDepth<short> { public: enum { value = CV_16S, fmt=(int)'s' }; };
406 template<> class DataDepth<int> { public: enum { value = CV_32S, fmt=(int)'i' }; };
407 // this is temporary solution to support 32-bit unsigned integers
408 template<> class DataDepth<unsigned> { public: enum { value = CV_32S, fmt=(int)'i' }; };
409 template<> class DataDepth<float> { public: enum { value = CV_32F, fmt=(int)'f' }; };
410 template<> class DataDepth<double> { public: enum { value = CV_64F, fmt=(int)'d' }; };
411 template<typename _Tp> class DataDepth<_Tp*> { public: enum { value = CV_USRTYPE1, fmt=(int)'r' }; };
412
413
414 ////////////////////////////// Small Matrix ///////////////////////////
415
416 /*!
417  A short numerical vector.
418
419  This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements)
420  on which you can perform basic arithmetical operations, access individual elements using [] operator etc.
421  The vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc.,
422  which elements are dynamically allocated in the heap.
423
424  The template takes 2 parameters:
425  -# _Tp element type
426  -# cn the number of elements
427
428  In addition to the universal notation like Vec<float, 3>, you can use shorter aliases
429  for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec<float, 3>.
430  */
431
432 struct CV_EXPORTS Matx_AddOp {};
433 struct CV_EXPORTS Matx_SubOp {};
434 struct CV_EXPORTS Matx_ScaleOp {};
435 struct CV_EXPORTS Matx_MulOp {};
436 struct CV_EXPORTS Matx_MatMulOp {};
437 struct CV_EXPORTS Matx_TOp {};
438
439 template<typename _Tp, int m, int n> class CV_EXPORTS Matx
440 {
441 public:
442     typedef _Tp value_type;
443     typedef Matx<_Tp, (m < n ? m : n), 1> diag_type;
444     typedef Matx<_Tp, m, n> mat_type;
445     enum { depth = DataDepth<_Tp>::value, rows = m, cols = n, channels = rows*cols,
446            type = CV_MAKETYPE(depth, channels) };
447
448     //! default constructor
449     Matx();
450
451     Matx(_Tp v0); //!< 1x1 matrix
452     Matx(_Tp v0, _Tp v1); //!< 1x2 or 2x1 matrix
453     Matx(_Tp v0, _Tp v1, _Tp v2); //!< 1x3 or 3x1 matrix
454     Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 1x4, 2x2 or 4x1 matrix
455     Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 1x5 or 5x1 matrix
456     Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 1x6, 2x3, 3x2 or 6x1 matrix
457     Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 1x7 or 7x1 matrix
458     Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 1x8, 2x4, 4x2 or 8x1 matrix
459     Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 1x9, 3x3 or 9x1 matrix
460     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
461     Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3,
462          _Tp v4, _Tp v5, _Tp v6, _Tp v7,
463          _Tp v8, _Tp v9, _Tp v10, _Tp v11); //!< 1x12, 2x6, 3x4, 4x3, 6x2 or 12x1 matrix
464     Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3,
465          _Tp v4, _Tp v5, _Tp v6, _Tp v7,
466          _Tp v8, _Tp v9, _Tp v10, _Tp v11,
467          _Tp v12, _Tp v13, _Tp v14, _Tp v15); //!< 1x16, 4x4 or 16x1 matrix
468     explicit Matx(const _Tp* vals); //!< initialize from a plain array
469
470     static Matx all(_Tp alpha);
471     static Matx zeros();
472     static Matx ones();
473     static Matx eye();
474     static Matx diag(const diag_type& d);
475     static Matx randu(_Tp a, _Tp b);
476     static Matx randn(_Tp a, _Tp b);
477
478     //! dot product computed with the default precision
479     _Tp dot(const Matx<_Tp, m, n>& v) const;
480
481     //! dot product computed in double-precision arithmetics
482     double ddot(const Matx<_Tp, m, n>& v) const;
483
484     //! convertion to another data type
485     template<typename T2> operator Matx<T2, m, n>() const;
486
487     //! change the matrix shape
488     template<int m1, int n1> Matx<_Tp, m1, n1> reshape() const;
489
490     //! extract part of the matrix
491     template<int m1, int n1> Matx<_Tp, m1, n1> get_minor(int i, int j) const;
492
493     //! extract the matrix row
494     Matx<_Tp, 1, n> row(int i) const;
495
496     //! extract the matrix column
497     Matx<_Tp, m, 1> col(int i) const;
498
499     //! extract the matrix diagonal
500     diag_type diag() const;
501
502     //! transpose the matrix
503     Matx<_Tp, n, m> t() const;
504
505     //! invert matrix the matrix
506     Matx<_Tp, n, m> inv(int method=DECOMP_LU) const;
507
508     //! solve linear system
509     template<int l> Matx<_Tp, n, l> solve(const Matx<_Tp, m, l>& rhs, int flags=DECOMP_LU) const;
510     Vec<_Tp, n> solve(const Vec<_Tp, m>& rhs, int method) const;
511
512     //! multiply two matrices element-wise
513     Matx<_Tp, m, n> mul(const Matx<_Tp, m, n>& a) const;
514
515     //! element access
516     const _Tp& operator ()(int i, int j) const;
517     _Tp& operator ()(int i, int j);
518
519     //! 1D element access
520     const _Tp& operator ()(int i) const;
521     _Tp& operator ()(int i);
522
523     Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp);
524     Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp);
525     template<typename _T2> Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp);
526     Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp);
527     template<int l> Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp);
528     Matx(const Matx<_Tp, n, m>& a, Matx_TOp);
529
530     _Tp val[m*n]; //< matrix elements
531 };
532
533
534 typedef Matx<float, 1, 2> Matx12f;
535 typedef Matx<double, 1, 2> Matx12d;
536 typedef Matx<float, 1, 3> Matx13f;
537 typedef Matx<double, 1, 3> Matx13d;
538 typedef Matx<float, 1, 4> Matx14f;
539 typedef Matx<double, 1, 4> Matx14d;
540 typedef Matx<float, 1, 6> Matx16f;
541 typedef Matx<double, 1, 6> Matx16d;
542
543 typedef Matx<float, 2, 1> Matx21f;
544 typedef Matx<double, 2, 1> Matx21d;
545 typedef Matx<float, 3, 1> Matx31f;
546 typedef Matx<double, 3, 1> Matx31d;
547 typedef Matx<float, 4, 1> Matx41f;
548 typedef Matx<double, 4, 1> Matx41d;
549 typedef Matx<float, 6, 1> Matx61f;
550 typedef Matx<double, 6, 1> Matx61d;
551
552 typedef Matx<float, 2, 2> Matx22f;
553 typedef Matx<double, 2, 2> Matx22d;
554 typedef Matx<float, 2, 3> Matx23f;
555 typedef Matx<double, 2, 3> Matx23d;
556 typedef Matx<float, 3, 2> Matx32f;
557 typedef Matx<double, 3, 2> Matx32d;
558
559 typedef Matx<float, 3, 3> Matx33f;
560 typedef Matx<double, 3, 3> Matx33d;
561
562 typedef Matx<float, 3, 4> Matx34f;
563 typedef Matx<double, 3, 4> Matx34d;
564 typedef Matx<float, 4, 3> Matx43f;
565 typedef Matx<double, 4, 3> Matx43d;
566
567 typedef Matx<float, 4, 4> Matx44f;
568 typedef Matx<double, 4, 4> Matx44d;
569 typedef Matx<float, 6, 6> Matx66f;
570 typedef Matx<double, 6, 6> Matx66d;
571
572
573 /*!
574   A short numerical vector.
575
576   This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements)
577   on which you can perform basic arithmetical operations, access individual elements using [] operator etc.
578   The vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc.,
579   which elements are dynamically allocated in the heap.
580
581   The template takes 2 parameters:
582   -# _Tp element type
583   -# cn the number of elements
584
585   In addition to the universal notation like Vec<float, 3>, you can use shorter aliases
586   for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec<float, 3>.
587 */
588 template<typename _Tp, int cn> class CV_EXPORTS Vec : public Matx<_Tp, cn, 1>
589 {
590 public:
591     typedef _Tp value_type;
592     enum { depth = DataDepth<_Tp>::value, channels = cn, type = CV_MAKETYPE(depth, channels) };
593
594     //! default constructor
595     Vec();
596
597     Vec(_Tp v0); //!< 1-element vector constructor
598     Vec(_Tp v0, _Tp v1); //!< 2-element vector constructor
599     Vec(_Tp v0, _Tp v1, _Tp v2); //!< 3-element vector constructor
600     Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 4-element vector constructor
601     Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 5-element vector constructor
602     Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 6-element vector constructor
603     Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 7-element vector constructor
604     Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 8-element vector constructor
605     Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 9-element vector constructor
606     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
607     explicit Vec(const _Tp* values);
608
609     Vec(const Vec<_Tp, cn>& v);
610
611     static Vec all(_Tp alpha);
612
613     //! per-element multiplication
614     Vec mul(const Vec<_Tp, cn>& v) const;
615
616     //! conjugation (makes sense for complex numbers and quaternions)
617     Vec conj() const;
618
619     /*!
620       cross product of the two 3D vectors.
621
622       For other dimensionalities the exception is raised
623     */
624     Vec cross(const Vec& v) const;
625     //! convertion to another data type
626     template<typename T2> operator Vec<T2, cn>() const;
627     //! conversion to 4-element CvScalar.
628     operator CvScalar() const;
629
630     /*! element access */
631     const _Tp& operator [](int i) const;
632     _Tp& operator[](int i);
633     const _Tp& operator ()(int i) const;
634     _Tp& operator ()(int i);
635
636     Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp);
637     Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp);
638     template<typename _T2> Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp);
639 };
640
641
642 /* \typedef
643
644    Shorter aliases for the most popular specializations of Vec<T,n>
645 */
646 typedef Vec<uchar, 2> Vec2b;
647 typedef Vec<uchar, 3> Vec3b;
648 typedef Vec<uchar, 4> Vec4b;
649
650 typedef Vec<short, 2> Vec2s;
651 typedef Vec<short, 3> Vec3s;
652 typedef Vec<short, 4> Vec4s;
653
654 typedef Vec<ushort, 2> Vec2w;
655 typedef Vec<ushort, 3> Vec3w;
656 typedef Vec<ushort, 4> Vec4w;
657
658 typedef Vec<int, 2> Vec2i;
659 typedef Vec<int, 3> Vec3i;
660 typedef Vec<int, 4> Vec4i;
661 typedef Vec<int, 6> Vec6i;
662 typedef Vec<int, 8> Vec8i;
663
664 typedef Vec<float, 2> Vec2f;
665 typedef Vec<float, 3> Vec3f;
666 typedef Vec<float, 4> Vec4f;
667 typedef Vec<float, 6> Vec6f;
668
669 typedef Vec<double, 2> Vec2d;
670 typedef Vec<double, 3> Vec3d;
671 typedef Vec<double, 4> Vec4d;
672 typedef Vec<double, 6> Vec6d;
673
674
675 //////////////////////////////// Complex //////////////////////////////
676
677 /*!
678   A complex number class.
679
680   The template class is similar and compatible with std::complex, however it provides slightly
681   more convenient access to the real and imaginary parts using through the simple field access, as opposite
682   to std::complex::real() and std::complex::imag().
683 */
684 template<typename _Tp> class CV_EXPORTS Complex
685 {
686 public:
687
688     //! constructors
689     Complex();
690     Complex( _Tp _re, _Tp _im=0 );
691     Complex( const std::complex<_Tp>& c );
692
693     //! conversion to another data type
694     template<typename T2> operator Complex<T2>() const;
695     //! conjugation
696     Complex conj() const;
697     //! conversion to std::complex
698     operator std::complex<_Tp>() const;
699
700     _Tp re, im; //< the real and the imaginary parts
701 };
702
703
704 /*!
705   \typedef
706 */
707 typedef Complex<float> Complexf;
708 typedef Complex<double> Complexd;
709
710
711 //////////////////////////////// Point_ ////////////////////////////////
712
713 /*!
714   template 2D point class.
715
716   The class defines a point in 2D space. Data type of the point coordinates is specified
717   as a template parameter. There are a few shorter aliases available for user convenience.
718   See cv::Point, cv::Point2i, cv::Point2f and cv::Point2d.
719 */
720 template<typename _Tp> class CV_EXPORTS Point_
721 {
722 public:
723     typedef _Tp value_type;
724
725     // various constructors
726     Point_();
727     Point_(_Tp _x, _Tp _y);
728     Point_(const Point_& pt);
729     Point_(const CvPoint& pt);
730     Point_(const CvPoint2D32f& pt);
731     Point_(const Size_<_Tp>& sz);
732     Point_(const Vec<_Tp, 2>& v);
733
734     Point_& operator = (const Point_& pt);
735     //! conversion to another data type
736     template<typename _Tp2> operator Point_<_Tp2>() const;
737
738     //! conversion to the old-style C structures
739     operator CvPoint() const;
740     operator CvPoint2D32f() const;
741     operator Vec<_Tp, 2>() const;
742
743     //! dot product
744     _Tp dot(const Point_& pt) const;
745     //! dot product computed in double-precision arithmetics
746     double ddot(const Point_& pt) const;
747     //! cross-product
748     double cross(const Point_& pt) const;
749     //! checks whether the point is inside the specified rectangle
750     bool inside(const Rect_<_Tp>& r) const;
751
752     _Tp x, y; //< the point coordinates
753 };
754
755 /*!
756   template 3D point class.
757
758   The class defines a point in 3D space. Data type of the point coordinates is specified
759   as a template parameter.
760
761   \see cv::Point3i, cv::Point3f and cv::Point3d
762 */
763 template<typename _Tp> class CV_EXPORTS Point3_
764 {
765 public:
766     typedef _Tp value_type;
767
768     // various constructors
769     Point3_();
770     Point3_(_Tp _x, _Tp _y, _Tp _z);
771     Point3_(const Point3_& pt);
772     explicit Point3_(const Point_<_Tp>& pt);
773     Point3_(const CvPoint3D32f& pt);
774     Point3_(const Vec<_Tp, 3>& v);
775
776     Point3_& operator = (const Point3_& pt);
777     //! conversion to another data type
778     template<typename _Tp2> operator Point3_<_Tp2>() const;
779     //! conversion to the old-style CvPoint...
780     operator CvPoint3D32f() const;
781     //! conversion to cv::Vec<>
782     operator Vec<_Tp, 3>() const;
783
784     //! dot product
785     _Tp dot(const Point3_& pt) const;
786     //! dot product computed in double-precision arithmetics
787     double ddot(const Point3_& pt) const;
788     //! cross product of the 2 3D points
789     Point3_ cross(const Point3_& pt) const;
790
791     _Tp x, y, z; //< the point coordinates
792 };
793
794 //////////////////////////////// Size_ ////////////////////////////////
795
796 /*!
797   The 2D size class
798
799   The class represents the size of a 2D rectangle, image size, matrix size etc.
800   Normally, cv::Size ~ cv::Size_<int> is used.
801 */
802 template<typename _Tp> class CV_EXPORTS Size_
803 {
804 public:
805     typedef _Tp value_type;
806
807     //! various constructors
808     Size_();
809     Size_(_Tp _width, _Tp _height);
810     Size_(const Size_& sz);
811     Size_(const CvSize& sz);
812     Size_(const CvSize2D32f& sz);
813     Size_(const Point_<_Tp>& pt);
814
815     Size_& operator = (const Size_& sz);
816     //! the area (width*height)
817     _Tp area() const;
818
819     //! conversion of another data type.
820     template<typename _Tp2> operator Size_<_Tp2>() const;
821
822     //! conversion to the old-style OpenCV types
823     operator CvSize() const;
824     operator CvSize2D32f() const;
825
826     _Tp width, height; // the width and the height
827 };
828
829 //////////////////////////////// Rect_ ////////////////////////////////
830
831 /*!
832   The 2D up-right rectangle class
833
834   The class represents a 2D rectangle with coordinates of the specified data type.
835   Normally, cv::Rect ~ cv::Rect_<int> is used.
836 */
837 template<typename _Tp> class CV_EXPORTS Rect_
838 {
839 public:
840     typedef _Tp value_type;
841
842     //! various constructors
843     Rect_();
844     Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height);
845     Rect_(const Rect_& r);
846     Rect_(const CvRect& r);
847     Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz);
848     Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2);
849
850     Rect_& operator = ( const Rect_& r );
851     //! the top-left corner
852     Point_<_Tp> tl() const;
853     //! the bottom-right corner
854     Point_<_Tp> br() const;
855
856     //! size (width, height) of the rectangle
857     Size_<_Tp> size() const;
858     //! area (width*height) of the rectangle
859     _Tp area() const;
860
861     //! conversion to another data type
862     template<typename _Tp2> operator Rect_<_Tp2>() const;
863     //! conversion to the old-style CvRect
864     operator CvRect() const;
865
866     //! checks whether the rectangle contains the point
867     bool contains(const Point_<_Tp>& pt) const;
868
869     _Tp x, y, width, height; //< the top-left corner, as well as width and height of the rectangle
870 };
871
872
873 /*!
874   \typedef
875
876   shorter aliases for the most popular cv::Point_<>, cv::Size_<> and cv::Rect_<> specializations
877 */
878 typedef Point_<int> Point2i;
879 typedef Point2i Point;
880 typedef Size_<int> Size2i;
881 typedef Size2i Size;
882 typedef Rect_<int> Rect;
883 typedef Point_<float> Point2f;
884 typedef Point_<double> Point2d;
885 typedef Size_<float> Size2f;
886 typedef Point3_<int> Point3i;
887 typedef Point3_<float> Point3f;
888 typedef Point3_<double> Point3d;
889
890
891 /*!
892   The rotated 2D rectangle.
893
894   The class represents rotated (i.e. not up-right) rectangles on a plane.
895   Each rectangle is described by the center point (mass center), length of each side
896   (represented by cv::Size2f structure) and the rotation angle in degrees.
897 */
898 class CV_EXPORTS RotatedRect
899 {
900 public:
901     //! various constructors
902     RotatedRect();
903     RotatedRect(const Point2f& center, const Size2f& size, float angle);
904     RotatedRect(const CvBox2D& box);
905
906     //! returns 4 vertices of the rectangle
907     void points(Point2f pts[]) const;
908     //! returns the minimal up-right rectangle containing the rotated rectangle
909     Rect boundingRect() const;
910     //! conversion to the old-style CvBox2D structure
911     operator CvBox2D() const;
912
913     Point2f center; //< the rectangle mass center
914     Size2f size;    //< width and height of the rectangle
915     float angle;    //< the rotation angle. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle.
916 };
917
918 //////////////////////////////// Scalar_ ///////////////////////////////
919
920 /*!
921    The template scalar class.
922
923    This is partially specialized cv::Vec class with the number of elements = 4, i.e. a short vector of four elements.
924    Normally, cv::Scalar ~ cv::Scalar_<double> is used.
925 */
926 template<typename _Tp> class CV_EXPORTS Scalar_ : public Vec<_Tp, 4>
927 {
928 public:
929     //! various constructors
930     Scalar_();
931     Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0);
932     Scalar_(const CvScalar& s);
933     Scalar_(_Tp v0);
934
935     //! returns a scalar with all elements set to v0
936     static Scalar_<_Tp> all(_Tp v0);
937     //! conversion to the old-style CvScalar
938     operator CvScalar() const;
939
940     //! conversion to another data type
941     template<typename T2> operator Scalar_<T2>() const;
942
943     //! per-element product
944     Scalar_<_Tp> mul(const Scalar_<_Tp>& t, double scale=1 ) const;
945
946     // returns (v0, -v1, -v2, -v3)
947     Scalar_<_Tp> conj() const;
948
949     // returns true iff v1 == v2 == v3 == 0
950     bool isReal() const;
951 };
952
953 typedef Scalar_<double> Scalar;
954
955 CV_EXPORTS void scalarToRawData(const Scalar& s, void* buf, int type, int unroll_to=0);
956
957 //////////////////////////////// Range /////////////////////////////////
958
959 /*!
960    The 2D range class
961
962    This is the class used to specify a continuous subsequence, i.e. part of a contour, or a column span in a matrix.
963 */
964 class CV_EXPORTS Range
965 {
966 public:
967     Range();
968     Range(int _start, int _end);
969     Range(const CvSlice& slice);
970     int size() const;
971     bool empty() const;
972     static Range all();
973     operator CvSlice() const;
974
975     int start, end;
976 };
977
978 /////////////////////////////// DataType ////////////////////////////////
979
980 /*!
981    Informative template class for OpenCV "scalars".
982
983    The class is specialized for each primitive numerical type supported by OpenCV (such as unsigned char or float),
984    as well as for more complex types, like cv::Complex<>, std::complex<>, cv::Vec<> etc.
985    The common property of all such types (called "scalars", do not confuse it with cv::Scalar_)
986    is that each of them is basically a tuple of numbers of the same type. Each "scalar" can be represented
987    by the depth id (CV_8U ... CV_64F) and the number of channels.
988    OpenCV matrices, 2D or nD, dense or sparse, can store "scalars",
989    as long as the number of channels does not exceed CV_CN_MAX.
990 */
991 template<typename _Tp> class DataType
992 {
993 public:
994     typedef _Tp value_type;
995     typedef value_type work_type;
996     typedef value_type channel_type;
997     typedef value_type vec_type;
998     enum { generic_type = 1, depth = -1, channels = 1, fmt=0,
999         type = CV_MAKETYPE(depth, channels) };
1000 };
1001
1002 template<> class DataType<bool>
1003 {
1004 public:
1005     typedef bool value_type;
1006     typedef int work_type;
1007     typedef value_type channel_type;
1008     typedef value_type vec_type;
1009     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1010            fmt=DataDepth<channel_type>::fmt,
1011            type = CV_MAKETYPE(depth, channels) };
1012 };
1013
1014 template<> class DataType<uchar>
1015 {
1016 public:
1017     typedef uchar value_type;
1018     typedef int work_type;
1019     typedef value_type channel_type;
1020     typedef value_type vec_type;
1021     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1022            fmt=DataDepth<channel_type>::fmt,
1023            type = CV_MAKETYPE(depth, channels) };
1024 };
1025
1026 template<> class DataType<schar>
1027 {
1028 public:
1029     typedef schar value_type;
1030     typedef int work_type;
1031     typedef value_type channel_type;
1032     typedef value_type vec_type;
1033     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1034            fmt=DataDepth<channel_type>::fmt,
1035            type = CV_MAKETYPE(depth, channels) };
1036 };
1037
1038 template<> class DataType<char>
1039 {
1040 public:
1041     typedef schar value_type;
1042     typedef int work_type;
1043     typedef value_type channel_type;
1044     typedef value_type vec_type;
1045     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1046            fmt=DataDepth<channel_type>::fmt,
1047            type = CV_MAKETYPE(depth, channels) };
1048 };
1049
1050 template<> class DataType<ushort>
1051 {
1052 public:
1053     typedef ushort value_type;
1054     typedef int work_type;
1055     typedef value_type channel_type;
1056     typedef value_type vec_type;
1057     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1058            fmt=DataDepth<channel_type>::fmt,
1059            type = CV_MAKETYPE(depth, channels) };
1060 };
1061
1062 template<> class DataType<short>
1063 {
1064 public:
1065     typedef short value_type;
1066     typedef int work_type;
1067     typedef value_type channel_type;
1068     typedef value_type vec_type;
1069     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1070            fmt=DataDepth<channel_type>::fmt,
1071            type = CV_MAKETYPE(depth, channels) };
1072 };
1073
1074 template<> class DataType<int>
1075 {
1076 public:
1077     typedef int value_type;
1078     typedef value_type work_type;
1079     typedef value_type channel_type;
1080     typedef value_type vec_type;
1081     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1082            fmt=DataDepth<channel_type>::fmt,
1083            type = CV_MAKETYPE(depth, channels) };
1084 };
1085
1086 template<> class DataType<float>
1087 {
1088 public:
1089     typedef float value_type;
1090     typedef value_type work_type;
1091     typedef value_type channel_type;
1092     typedef value_type vec_type;
1093     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1094            fmt=DataDepth<channel_type>::fmt,
1095            type = CV_MAKETYPE(depth, channels) };
1096 };
1097
1098 template<> class DataType<double>
1099 {
1100 public:
1101     typedef double value_type;
1102     typedef value_type work_type;
1103     typedef value_type channel_type;
1104     typedef value_type vec_type;
1105     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 1,
1106            fmt=DataDepth<channel_type>::fmt,
1107            type = CV_MAKETYPE(depth, channels) };
1108 };
1109
1110 template<typename _Tp, int cn> class DataType<Vec<_Tp, cn> >
1111 {
1112 public:
1113     typedef Vec<_Tp, cn> value_type;
1114     typedef Vec<typename DataType<_Tp>::work_type, cn> work_type;
1115     typedef _Tp channel_type;
1116     typedef value_type vec_type;
1117     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = cn,
1118            fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1119            type = CV_MAKETYPE(depth, channels) };
1120 };
1121
1122 template<typename _Tp> class DataType<std::complex<_Tp> >
1123 {
1124 public:
1125     typedef std::complex<_Tp> value_type;
1126     typedef value_type work_type;
1127     typedef _Tp channel_type;
1128     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1129            fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1130            type = CV_MAKETYPE(depth, channels) };
1131     typedef Vec<channel_type, channels> vec_type;
1132 };
1133
1134 template<typename _Tp> class DataType<Complex<_Tp> >
1135 {
1136 public:
1137     typedef Complex<_Tp> value_type;
1138     typedef value_type work_type;
1139     typedef _Tp channel_type;
1140     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1141            fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1142            type = CV_MAKETYPE(depth, channels) };
1143     typedef Vec<channel_type, channels> vec_type;
1144 };
1145
1146 template<typename _Tp> class DataType<Point_<_Tp> >
1147 {
1148 public:
1149     typedef Point_<_Tp> value_type;
1150     typedef Point_<typename DataType<_Tp>::work_type> work_type;
1151     typedef _Tp channel_type;
1152     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1153            fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1154            type = CV_MAKETYPE(depth, channels) };
1155     typedef Vec<channel_type, channels> vec_type;
1156 };
1157
1158 template<typename _Tp> class DataType<Point3_<_Tp> >
1159 {
1160 public:
1161     typedef Point3_<_Tp> value_type;
1162     typedef Point3_<typename DataType<_Tp>::work_type> work_type;
1163     typedef _Tp channel_type;
1164     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 3,
1165            fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1166            type = CV_MAKETYPE(depth, channels) };
1167     typedef Vec<channel_type, channels> vec_type;
1168 };
1169
1170 template<typename _Tp> class DataType<Size_<_Tp> >
1171 {
1172 public:
1173     typedef Size_<_Tp> value_type;
1174     typedef Size_<typename DataType<_Tp>::work_type> work_type;
1175     typedef _Tp channel_type;
1176     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1177            fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1178            type = CV_MAKETYPE(depth, channels) };
1179     typedef Vec<channel_type, channels> vec_type;
1180 };
1181
1182 template<typename _Tp> class DataType<Rect_<_Tp> >
1183 {
1184 public:
1185     typedef Rect_<_Tp> value_type;
1186     typedef Rect_<typename DataType<_Tp>::work_type> work_type;
1187     typedef _Tp channel_type;
1188     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 4,
1189            fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1190            type = CV_MAKETYPE(depth, channels) };
1191     typedef Vec<channel_type, channels> vec_type;
1192 };
1193
1194 template<typename _Tp> class DataType<Scalar_<_Tp> >
1195 {
1196 public:
1197     typedef Scalar_<_Tp> value_type;
1198     typedef Scalar_<typename DataType<_Tp>::work_type> work_type;
1199     typedef _Tp channel_type;
1200     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 4,
1201            fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1202            type = CV_MAKETYPE(depth, channels) };
1203     typedef Vec<channel_type, channels> vec_type;
1204 };
1205
1206 template<> class DataType<Range>
1207 {
1208 public:
1209     typedef Range value_type;
1210     typedef value_type work_type;
1211     typedef int channel_type;
1212     enum { generic_type = 0, depth = DataDepth<channel_type>::value, channels = 2,
1213            fmt = ((channels-1)<<8) + DataDepth<channel_type>::fmt,
1214            type = CV_MAKETYPE(depth, channels) };
1215     typedef Vec<channel_type, channels> vec_type;
1216 };
1217
1218 //////////////////// generic_type ref-counting pointer class for C/C++ objects ////////////////////////
1219
1220 /*!
1221   Smart pointer to dynamically allocated objects.
1222
1223   This is template pointer-wrapping class that stores the associated reference counter along with the
1224   object pointer. The class is similar to std::smart_ptr<> from the recent addons to the C++ standard,
1225   but is shorter to write :) and self-contained (i.e. does add any dependency on the compiler or an external library).
1226
1227   Basically, you can use "Ptr<MyObjectType> ptr" (or faster "const Ptr<MyObjectType>& ptr" for read-only access)
1228   everywhere instead of "MyObjectType* ptr", where MyObjectType is some C structure or a C++ class.
1229   To make it all work, you need to specialize Ptr<>::delete_obj(), like:
1230
1231   \code
1232   template<> void Ptr<MyObjectType>::delete_obj() { call_destructor_func(obj); }
1233   \endcode
1234
1235   \note{if MyObjectType is a C++ class with a destructor, you do not need to specialize delete_obj(),
1236   since the default implementation calls "delete obj;"}
1237
1238   \note{Another good property of the class is that the operations on the reference counter are atomic,
1239   i.e. it is safe to use the class in multi-threaded applications}
1240 */
1241 template<typename _Tp> class CV_EXPORTS Ptr
1242 {
1243 public:
1244     //! empty constructor
1245     Ptr();
1246     //! take ownership of the pointer. The associated reference counter is allocated and set to 1
1247     Ptr(_Tp* _obj);
1248     //! calls release()
1249     ~Ptr();
1250     //! copy constructor. Copies the members and calls addref()
1251     Ptr(const Ptr& ptr);
1252     template<typename _Tp2> Ptr(const Ptr<_Tp2>& ptr);
1253     //! copy operator. Calls ptr.addref() and release() before copying the members
1254     Ptr& operator = (const Ptr& ptr);
1255     //! increments the reference counter
1256     void addref();
1257     //! decrements the reference counter. If it reaches 0, delete_obj() is called
1258     void release();
1259     //! deletes the object. Override if needed
1260     void delete_obj();
1261     //! returns true iff obj==NULL
1262     bool empty() const;
1263
1264     //! cast pointer to another type
1265     template<typename _Tp2> Ptr<_Tp2> ptr();
1266     template<typename _Tp2> const Ptr<_Tp2> ptr() const;
1267
1268     //! helper operators making "Ptr<T> ptr" use very similar to "T* ptr".
1269     _Tp* operator -> ();
1270     const _Tp* operator -> () const;
1271
1272     operator _Tp* ();
1273     operator const _Tp*() const;
1274
1275     _Tp* obj; //< the object pointer.
1276     int* refcount; //< the associated reference counter
1277 };
1278
1279
1280 //////////////////////// Input/Output Array Arguments /////////////////////////////////
1281
1282 /*!
1283  Proxy datatype for passing Mat's and vector<>'s as input parameters
1284  */
1285 class CV_EXPORTS _InputArray
1286 {
1287 public:
1288     enum {
1289         KIND_SHIFT = 16,
1290         FIXED_TYPE = 0x8000 << KIND_SHIFT,
1291         FIXED_SIZE = 0x4000 << KIND_SHIFT,
1292         KIND_MASK = ~(FIXED_TYPE|FIXED_SIZE) - (1 << KIND_SHIFT) + 1,
1293
1294         NONE              = 0 << KIND_SHIFT,
1295         MAT               = 1 << KIND_SHIFT,
1296         MATX              = 2 << KIND_SHIFT,
1297         STD_VECTOR        = 3 << KIND_SHIFT,
1298         STD_VECTOR_VECTOR = 4 << KIND_SHIFT,
1299         STD_VECTOR_MAT    = 5 << KIND_SHIFT,
1300         EXPR              = 6 << KIND_SHIFT,
1301         OPENGL_BUFFER     = 7 << KIND_SHIFT,
1302         OPENGL_TEXTURE    = 8 << KIND_SHIFT,
1303         GPU_MAT           = 9 << KIND_SHIFT
1304     };
1305     _InputArray();
1306
1307     _InputArray(const Mat& m);
1308     _InputArray(const MatExpr& expr);
1309     template<typename _Tp> _InputArray(const _Tp* vec, int n);
1310     template<typename _Tp> _InputArray(const vector<_Tp>& vec);
1311     template<typename _Tp> _InputArray(const vector<vector<_Tp> >& vec);
1312     _InputArray(const vector<Mat>& vec);
1313     template<typename _Tp> _InputArray(const vector<Mat_<_Tp> >& vec);
1314     template<typename _Tp> _InputArray(const Mat_<_Tp>& m);
1315     template<typename _Tp, int m, int n> _InputArray(const Matx<_Tp, m, n>& matx);
1316     _InputArray(const Scalar& s);
1317     _InputArray(const double& val);
1318     _InputArray(const GlBuffer& buf);
1319     _InputArray(const GlTexture& tex);
1320     _InputArray(const gpu::GpuMat& d_mat);
1321
1322     virtual Mat getMat(int i=-1) const;
1323     virtual void getMatVector(vector<Mat>& mv) const;
1324     virtual GlBuffer getGlBuffer() const;
1325     virtual GlTexture getGlTexture() const;
1326     virtual gpu::GpuMat getGpuMat() const;
1327
1328     virtual int kind() const;
1329     virtual Size size(int i=-1) const;
1330     virtual size_t total(int i=-1) const;
1331     virtual int type(int i=-1) const;
1332     virtual int depth(int i=-1) const;
1333     virtual int channels(int i=-1) const;
1334     virtual bool empty() const;
1335
1336     virtual ~_InputArray();
1337
1338     int flags;
1339     void* obj;
1340     Size sz;
1341 };
1342
1343
1344 enum
1345 {
1346     DEPTH_MASK_8U = 1 << CV_8U,
1347     DEPTH_MASK_8S = 1 << CV_8S,
1348     DEPTH_MASK_16U = 1 << CV_16U,
1349     DEPTH_MASK_16S = 1 << CV_16S,
1350     DEPTH_MASK_32S = 1 << CV_32S,
1351     DEPTH_MASK_32F = 1 << CV_32F,
1352     DEPTH_MASK_64F = 1 << CV_64F,
1353     DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1,
1354     DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S,
1355     DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F
1356 };
1357
1358
1359 /*!
1360  Proxy datatype for passing Mat's and vector<>'s as input parameters
1361  */
1362 class CV_EXPORTS _OutputArray : public _InputArray
1363 {
1364 public:
1365     _OutputArray();
1366
1367     _OutputArray(Mat& m);
1368     template<typename _Tp> _OutputArray(vector<_Tp>& vec);
1369     template<typename _Tp> _OutputArray(vector<vector<_Tp> >& vec);
1370     _OutputArray(vector<Mat>& vec);
1371     template<typename _Tp> _OutputArray(vector<Mat_<_Tp> >& vec);
1372     template<typename _Tp> _OutputArray(Mat_<_Tp>& m);
1373     template<typename _Tp, int m, int n> _OutputArray(Matx<_Tp, m, n>& matx);
1374     template<typename _Tp> _OutputArray(_Tp* vec, int n);
1375
1376     _OutputArray(const Mat& m);
1377     template<typename _Tp> _OutputArray(const vector<_Tp>& vec);
1378     template<typename _Tp> _OutputArray(const vector<vector<_Tp> >& vec);
1379     _OutputArray(const vector<Mat>& vec);
1380     template<typename _Tp> _OutputArray(const vector<Mat_<_Tp> >& vec);
1381     template<typename _Tp> _OutputArray(const Mat_<_Tp>& m);
1382     template<typename _Tp, int m, int n> _OutputArray(const Matx<_Tp, m, n>& matx);
1383     template<typename _Tp> _OutputArray(const _Tp* vec, int n);
1384
1385     virtual bool fixedSize() const;
1386     virtual bool fixedType() const;
1387     virtual bool needed() const;
1388     virtual Mat& getMatRef(int i=-1) const;
1389     virtual void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
1390     virtual void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
1391     virtual void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
1392     virtual void release() const;
1393     virtual void clear() const;
1394
1395     virtual ~_OutputArray();
1396 };
1397
1398 typedef const _InputArray& InputArray;
1399 typedef InputArray InputArrayOfArrays;
1400 typedef const _OutputArray& OutputArray;
1401 typedef OutputArray OutputArrayOfArrays;
1402 typedef OutputArray InputOutputArray;
1403 typedef OutputArray InputOutputArrayOfArrays;
1404
1405 CV_EXPORTS OutputArray noArray();
1406
1407 /////////////////////////////////////// Mat ///////////////////////////////////////////
1408
1409 enum { MAGIC_MASK=0xFFFF0000, TYPE_MASK=0x00000FFF, DEPTH_MASK=7 };
1410
1411 static inline size_t getElemSize(int type) { return CV_ELEM_SIZE(type); }
1412
1413 /*!
1414    Custom array allocator
1415
1416 */
1417 class CV_EXPORTS MatAllocator
1418 {
1419 public:
1420     MatAllocator() {}
1421     virtual ~MatAllocator() {}
1422     virtual void allocate(int dims, const int* sizes, int type, int*& refcount,
1423                           uchar*& datastart, uchar*& data, size_t* step) = 0;
1424     virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0;
1425 };
1426
1427 /*!
1428    The n-dimensional matrix class.
1429
1430    The class represents an n-dimensional dense numerical array that can act as
1431    a matrix, image, optical flow map, 3-focal tensor etc.
1432    It is very similar to CvMat and CvMatND types from earlier versions of OpenCV,
1433    and similarly to those types, the matrix can be multi-channel. It also fully supports ROI mechanism.
1434
1435    There are many different ways to create cv::Mat object. Here are the some popular ones:
1436    <ul>
1437    <li> using cv::Mat::create(nrows, ncols, type) method or
1438      the similar constructor cv::Mat::Mat(nrows, ncols, type[, fill_value]) constructor.
1439      A new matrix of the specified size and specifed type will be allocated.
1440      "type" has the same meaning as in cvCreateMat function,
1441      e.g. CV_8UC1 means 8-bit single-channel matrix, CV_32FC2 means 2-channel (i.e. complex)
1442      floating-point matrix etc:
1443
1444      \code
1445      // make 7x7 complex matrix filled with 1+3j.
1446      cv::Mat M(7,7,CV_32FC2,Scalar(1,3));
1447      // and now turn M to 100x60 15-channel 8-bit matrix.
1448      // The old content will be deallocated
1449      M.create(100,60,CV_8UC(15));
1450      \endcode
1451
1452      As noted in the introduction of this chapter, Mat::create()
1453      will only allocate a new matrix when the current matrix dimensionality
1454      or type are different from the specified.
1455
1456    <li> by using a copy constructor or assignment operator, where on the right side it can
1457      be a matrix or expression, see below. Again, as noted in the introduction,
1458      matrix assignment is O(1) operation because it only copies the header
1459      and increases the reference counter. cv::Mat::clone() method can be used to get a full
1460      (a.k.a. deep) copy of the matrix when you need it.
1461
1462    <li> by constructing a header for a part of another matrix. It can be a single row, single column,
1463      several rows, several columns, rectangular region in the matrix (called a minor in algebra) or
1464      a diagonal. Such operations are also O(1), because the new header will reference the same data.
1465      You can actually modify a part of the matrix using this feature, e.g.
1466
1467      \code
1468      // add 5-th row, multiplied by 3 to the 3rd row
1469      M.row(3) = M.row(3) + M.row(5)*3;
1470
1471      // now copy 7-th column to the 1-st column
1472      // M.col(1) = M.col(7); // this will not work
1473      Mat M1 = M.col(1);
1474      M.col(7).copyTo(M1);
1475
1476      // create new 320x240 image
1477      cv::Mat img(Size(320,240),CV_8UC3);
1478      // select a roi
1479      cv::Mat roi(img, Rect(10,10,100,100));
1480      // fill the ROI with (0,255,0) (which is green in RGB space);
1481      // the original 320x240 image will be modified
1482      roi = Scalar(0,255,0);
1483      \endcode
1484
1485      Thanks to the additional cv::Mat::datastart and cv::Mat::dataend members, it is possible to
1486      compute the relative sub-matrix position in the main "container" matrix using cv::Mat::locateROI():
1487
1488      \code
1489      Mat A = Mat::eye(10, 10, CV_32S);
1490      // extracts A columns, 1 (inclusive) to 3 (exclusive).
1491      Mat B = A(Range::all(), Range(1, 3));
1492      // extracts B rows, 5 (inclusive) to 9 (exclusive).
1493      // that is, C ~ A(Range(5, 9), Range(1, 3))
1494      Mat C = B(Range(5, 9), Range::all());
1495      Size size; Point ofs;
1496      C.locateROI(size, ofs);
1497      // size will be (width=10,height=10) and the ofs will be (x=1, y=5)
1498      \endcode
1499
1500      As in the case of whole matrices, if you need a deep copy, use cv::Mat::clone() method
1501      of the extracted sub-matrices.
1502
1503    <li> by making a header for user-allocated-data. It can be useful for
1504       <ol>
1505       <li> processing "foreign" data using OpenCV (e.g. when you implement
1506          a DirectShow filter or a processing module for gstreamer etc.), e.g.
1507
1508          \code
1509          void process_video_frame(const unsigned char* pixels,
1510                                   int width, int height, int step)
1511          {
1512             cv::Mat img(height, width, CV_8UC3, pixels, step);
1513             cv::GaussianBlur(img, img, cv::Size(7,7), 1.5, 1.5);
1514          }
1515          \endcode
1516
1517       <li> for quick initialization of small matrices and/or super-fast element access
1518
1519          \code
1520          double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
1521          cv::Mat M = cv::Mat(3, 3, CV_64F, m).inv();
1522          \endcode
1523       </ol>
1524
1525        partial yet very common cases of this "user-allocated data" case are conversions
1526        from CvMat and IplImage to cv::Mat. For this purpose there are special constructors
1527        taking pointers to CvMat or IplImage and the optional
1528        flag indicating whether to copy the data or not.
1529
1530        Backward conversion from cv::Mat to CvMat or IplImage is provided via cast operators
1531        cv::Mat::operator CvMat() an cv::Mat::operator IplImage().
1532        The operators do not copy the data.
1533
1534
1535        \code
1536        IplImage* img = cvLoadImage("greatwave.jpg", 1);
1537        Mat mtx(img); // convert IplImage* -> cv::Mat
1538        CvMat oldmat = mtx; // convert cv::Mat -> CvMat
1539        CV_Assert(oldmat.cols == img->width && oldmat.rows == img->height &&
1540            oldmat.data.ptr == (uchar*)img->imageData && oldmat.step == img->widthStep);
1541        \endcode
1542
1543    <li> by using MATLAB-style matrix initializers, cv::Mat::zeros(), cv::Mat::ones(), cv::Mat::eye(), e.g.:
1544
1545    \code
1546    // create a double-precision identity martix and add it to M.
1547    M += Mat::eye(M.rows, M.cols, CV_64F);
1548    \endcode
1549
1550    <li> by using comma-separated initializer:
1551
1552    \code
1553    // create 3x3 double-precision identity matrix
1554    Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
1555    \endcode
1556
1557    here we first call constructor of cv::Mat_ class (that we describe further) with the proper matrix,
1558    and then we just put "<<" operator followed by comma-separated values that can be constants,
1559    variables, expressions etc. Also, note the extra parentheses that are needed to avoid compiler errors.
1560
1561    </ul>
1562
1563    Once matrix is created, it will be automatically managed by using reference-counting mechanism
1564    (unless the matrix header is built on top of user-allocated data,
1565    in which case you should handle the data by yourself).
1566    The matrix data will be deallocated when no one points to it;
1567    if you want to release the data pointed by a matrix header before the matrix destructor is called,
1568    use cv::Mat::release().
1569
1570    The next important thing to learn about the matrix class is element access. Here is how the matrix is stored.
1571    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,
1572    cv::Mat::rows contains the number of matrix rows and cv::Mat::cols - the number of matrix columns. There is yet another member,
1573    cv::Mat::step that is used to actually compute address of a matrix element. cv::Mat::step is needed because the matrix can be
1574    a part of another matrix or because there can some padding space in the end of each row for a proper alignment.
1575
1576    \image html roi.png
1577
1578    Given these parameters, address of the matrix element M_{ij} is computed as following:
1579
1580    addr(M_{ij})=M.data + M.step*i + j*M.elemSize()
1581
1582    if you know the matrix element type, e.g. it is float, then you can use cv::Mat::at() method:
1583
1584    addr(M_{ij})=&M.at<float>(i,j)
1585
1586    (where & is used to convert the reference returned by cv::Mat::at() to a pointer).
1587    if you need to process a whole row of matrix, the most efficient way is to get
1588    the pointer to the row first, and then just use plain C operator []:
1589
1590    \code
1591    // compute sum of positive matrix elements
1592    // (assuming that M is double-precision matrix)
1593    double sum=0;
1594    for(int i = 0; i < M.rows; i++)
1595    {
1596        const double* Mi = M.ptr<double>(i);
1597        for(int j = 0; j < M.cols; j++)
1598            sum += std::max(Mi[j], 0.);
1599    }
1600    \endcode
1601
1602    Some operations, like the above one, do not actually depend on the matrix shape,
1603    they just process elements of a matrix one by one (or elements from multiple matrices
1604    that are sitting in the same place, e.g. matrix addition). Such operations are called
1605    element-wise and it makes sense to check whether all the input/output matrices are continuous,
1606    i.e. have no gaps in the end of each row, and if yes, process them as a single long row:
1607
1608    \code
1609    // compute sum of positive matrix elements, optimized variant
1610    double sum=0;
1611    int cols = M.cols, rows = M.rows;
1612    if(M.isContinuous())
1613    {
1614        cols *= rows;
1615        rows = 1;
1616    }
1617    for(int i = 0; i < rows; i++)
1618    {
1619        const double* Mi = M.ptr<double>(i);
1620        for(int j = 0; j < cols; j++)
1621            sum += std::max(Mi[j], 0.);
1622    }
1623    \endcode
1624    in the case of continuous matrix the outer loop body will be executed just once,
1625    so the overhead will be smaller, which will be especially noticeable in the case of small matrices.
1626
1627    Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:
1628    \code
1629    // compute sum of positive matrix elements, iterator-based variant
1630    double sum=0;
1631    MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
1632    for(; it != it_end; ++it)
1633        sum += std::max(*it, 0.);
1634    \endcode
1635
1636    The matrix iterators are random-access iterators, so they can be passed
1637    to any STL algorithm, including std::sort().
1638 */
1639 class CV_EXPORTS Mat
1640 {
1641 public:
1642     //! default constructor
1643     Mat();
1644     //! constructs 2D matrix of the specified size and type
1645     // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
1646     Mat(int rows, int cols, int type);
1647     Mat(Size size, int type);
1648     //! constucts 2D matrix and fills it with the specified value _s.
1649     Mat(int rows, int cols, int type, const Scalar& s);
1650     Mat(Size size, int type, const Scalar& s);
1651
1652     //! constructs n-dimensional matrix
1653     Mat(int ndims, const int* sizes, int type);
1654     Mat(int ndims, const int* sizes, int type, const Scalar& s);
1655
1656     //! copy constructor
1657     Mat(const Mat& m);
1658     //! constructor for matrix headers pointing to user-allocated data
1659     Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP);
1660     Mat(Size size, int type, void* data, size_t step=AUTO_STEP);
1661     Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0);
1662
1663     //! creates a matrix header for a part of the bigger matrix
1664     Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all());
1665     Mat(const Mat& m, const Rect& roi);
1666     Mat(const Mat& m, const Range* ranges);
1667     //! converts old-style CvMat to the new matrix; the data is not copied by default
1668     Mat(const CvMat* m, bool copyData=false);
1669     //! converts old-style CvMatND to the new matrix; the data is not copied by default
1670     Mat(const CvMatND* m, bool copyData=false);
1671     //! converts old-style IplImage to the new matrix; the data is not copied by default
1672     Mat(const IplImage* img, bool copyData=false);
1673     //! builds matrix from std::vector with or without copying the data
1674     template<typename _Tp> explicit Mat(const vector<_Tp>& vec, bool copyData=false);
1675     //! builds matrix from cv::Vec; the data is copied by default
1676     template<typename _Tp, int n> explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true);
1677     //! builds matrix from cv::Matx; the data is copied by default
1678     template<typename _Tp, int m, int n> explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
1679     //! builds matrix from a 2D point
1680     template<typename _Tp> explicit Mat(const Point_<_Tp>& pt, bool copyData=true);
1681     //! builds matrix from a 3D point
1682     template<typename _Tp> explicit Mat(const Point3_<_Tp>& pt, bool copyData=true);
1683     //! builds matrix from comma initializer
1684     template<typename _Tp> explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer);
1685
1686     //! download data from GpuMat
1687     explicit Mat(const gpu::GpuMat& m);
1688
1689     //! destructor - calls release()
1690     ~Mat();
1691     //! assignment operators
1692     Mat& operator = (const Mat& m);
1693     Mat& operator = (const MatExpr& expr);
1694
1695     //! returns a new matrix header for the specified row
1696     Mat row(int y) const;
1697     //! returns a new matrix header for the specified column
1698     Mat col(int x) const;
1699     //! ... for the specified row span
1700     Mat rowRange(int startrow, int endrow) const;
1701     Mat rowRange(const Range& r) const;
1702     //! ... for the specified column span
1703     Mat colRange(int startcol, int endcol) const;
1704     Mat colRange(const Range& r) const;
1705     //! ... for the specified diagonal
1706     // (d=0 - the main diagonal,
1707     //  >0 - a diagonal from the lower half,
1708     //  <0 - a diagonal from the upper half)
1709     Mat diag(int d=0) const;
1710     //! constructs a square diagonal matrix which main diagonal is vector "d"
1711     static Mat diag(const Mat& d);
1712
1713     //! returns deep copy of the matrix, i.e. the data is copied
1714     Mat clone() const;
1715     //! copies the matrix content to "m".
1716     // It calls m.create(this->size(), this->type()).
1717     void copyTo( OutputArray m ) const;
1718     //! copies those matrix elements to "m" that are marked with non-zero mask elements.
1719     void copyTo( OutputArray m, InputArray mask ) const;
1720     //! converts matrix to another datatype with optional scalng. See cvConvertScale.
1721     void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
1722
1723     void assignTo( Mat& m, int type=-1 ) const;
1724
1725     //! sets every matrix element to s
1726     Mat& operator = (const Scalar& s);
1727     //! sets some of the matrix elements to s, according to the mask
1728     Mat& setTo(InputArray value, InputArray mask=noArray());
1729     //! creates alternative matrix header for the same data, with different
1730     // number of channels and/or different number of rows. see cvReshape.
1731     Mat reshape(int cn, int rows=0) const;
1732     Mat reshape(int cn, int newndims, const int* newsz) const;
1733
1734     //! matrix transposition by means of matrix expressions
1735     MatExpr t() const;
1736     //! matrix inversion by means of matrix expressions
1737     MatExpr inv(int method=DECOMP_LU) const;
1738     //! per-element matrix multiplication by means of matrix expressions
1739     MatExpr mul(InputArray m, double scale=1) const;
1740
1741     //! computes cross-product of 2 3D vectors
1742     Mat cross(InputArray m) const;
1743     //! computes dot-product
1744     double dot(InputArray m) const;
1745
1746     //! Matlab-style matrix initialization
1747     static MatExpr zeros(int rows, int cols, int type);
1748     static MatExpr zeros(Size size, int type);
1749     static MatExpr zeros(int ndims, const int* sz, int type);
1750     static MatExpr ones(int rows, int cols, int type);
1751     static MatExpr ones(Size size, int type);
1752     static MatExpr ones(int ndims, const int* sz, int type);
1753     static MatExpr eye(int rows, int cols, int type);
1754     static MatExpr eye(Size size, int type);
1755
1756     //! allocates new matrix data unless the matrix already has specified size and type.
1757     // previous data is unreferenced if needed.
1758     void create(int rows, int cols, int type);
1759     void create(Size size, int type);
1760     void create(int ndims, const int* sizes, int type);
1761
1762     //! increases the reference counter; use with care to avoid memleaks
1763     void addref();
1764     //! decreases reference counter;
1765     // deallocates the data when reference counter reaches 0.
1766     void release();
1767
1768     //! deallocates the matrix data
1769     void deallocate();
1770     //! internal use function; properly re-allocates _size, _step arrays
1771     void copySize(const Mat& m);
1772
1773     //! reserves enough space to fit sz hyper-planes
1774     void reserve(size_t sz);
1775     //! resizes matrix to the specified number of hyper-planes
1776     void resize(size_t sz);
1777     //! resizes matrix to the specified number of hyper-planes; initializes the newly added elements
1778     void resize(size_t sz, const Scalar& s);
1779     //! internal function
1780     void push_back_(const void* elem);
1781     //! adds element to the end of 1d matrix (or possibly multiple elements when _Tp=Mat)
1782     template<typename _Tp> void push_back(const _Tp& elem);
1783     template<typename _Tp> void push_back(const Mat_<_Tp>& elem);
1784     void push_back(const Mat& m);
1785     //! removes several hyper-planes from bottom of the matrix
1786     void pop_back(size_t nelems=1);
1787
1788     //! locates matrix header within a parent matrix. See below
1789     void locateROI( Size& wholeSize, Point& ofs ) const;
1790     //! moves/resizes the current matrix ROI inside the parent matrix.
1791     Mat& adjustROI( int dtop, int dbottom, int dleft, int dright );
1792     //! extracts a rectangular sub-matrix
1793     // (this is a generalized form of row, rowRange etc.)
1794     Mat operator()( Range rowRange, Range colRange ) const;
1795     Mat operator()( const Rect& roi ) const;
1796     Mat operator()( const Range* ranges ) const;
1797
1798     //! converts header to CvMat; no data is copied
1799     operator CvMat() const;
1800     //! converts header to CvMatND; no data is copied
1801     operator CvMatND() const;
1802     //! converts header to IplImage; no data is copied
1803     operator IplImage() const;
1804
1805     template<typename _Tp> operator vector<_Tp>() const;
1806     template<typename _Tp, int n> operator Vec<_Tp, n>() const;
1807     template<typename _Tp, int m, int n> operator Matx<_Tp, m, n>() const;
1808
1809     //! returns true iff the matrix data is continuous
1810     // (i.e. when there are no gaps between successive rows).
1811     // similar to CV_IS_MAT_CONT(cvmat->type)
1812     bool isContinuous() const;
1813
1814     //! returns true if the matrix is a submatrix of another matrix
1815     bool isSubmatrix() const;
1816
1817     //! returns element size in bytes,
1818     // similar to CV_ELEM_SIZE(cvmat->type)
1819     size_t elemSize() const;
1820     //! returns the size of element channel in bytes.
1821     size_t elemSize1() const;
1822     //! returns element type, similar to CV_MAT_TYPE(cvmat->type)
1823     int type() const;
1824     //! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
1825     int depth() const;
1826     //! returns element type, similar to CV_MAT_CN(cvmat->type)
1827     int channels() const;
1828     //! returns step/elemSize1()
1829     size_t step1(int i=0) const;
1830     //! returns true if matrix data is NULL
1831     bool empty() const;
1832     //! returns the total number of matrix elements
1833     size_t total() const;
1834
1835     //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
1836     int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
1837
1838     //! returns pointer to i0-th submatrix along the dimension #0
1839     uchar* ptr(int i0=0);
1840     const uchar* ptr(int i0=0) const;
1841
1842     //! returns pointer to (i0,i1) submatrix along the dimensions #0 and #1
1843     uchar* ptr(int i0, int i1);
1844     const uchar* ptr(int i0, int i1) const;
1845
1846     //! returns pointer to (i0,i1,i3) submatrix along the dimensions #0, #1, #2
1847     uchar* ptr(int i0, int i1, int i2);
1848     const uchar* ptr(int i0, int i1, int i2) const;
1849
1850     //! returns pointer to the matrix element
1851     uchar* ptr(const int* idx);
1852     //! returns read-only pointer to the matrix element
1853     const uchar* ptr(const int* idx) const;
1854
1855     template<int n> uchar* ptr(const Vec<int, n>& idx);
1856     template<int n> const uchar* ptr(const Vec<int, n>& idx) const;
1857
1858     //! template version of the above method
1859     template<typename _Tp> _Tp* ptr(int i0=0);
1860     template<typename _Tp> const _Tp* ptr(int i0=0) const;
1861
1862     template<typename _Tp> _Tp* ptr(int i0, int i1);
1863     template<typename _Tp> const _Tp* ptr(int i0, int i1) const;
1864
1865     template<typename _Tp> _Tp* ptr(int i0, int i1, int i2);
1866     template<typename _Tp> const _Tp* ptr(int i0, int i1, int i2) const;
1867
1868     template<typename _Tp> _Tp* ptr(const int* idx);
1869     template<typename _Tp> const _Tp* ptr(const int* idx) const;
1870
1871     template<typename _Tp, int n> _Tp* ptr(const Vec<int, n>& idx);
1872     template<typename _Tp, int n> const _Tp* ptr(const Vec<int, n>& idx) const;
1873
1874     //! the same as above, with the pointer dereferencing
1875     template<typename _Tp> _Tp& at(int i0=0);
1876     template<typename _Tp> const _Tp& at(int i0=0) const;
1877
1878     template<typename _Tp> _Tp& at(int i0, int i1);
1879     template<typename _Tp> const _Tp& at(int i0, int i1) const;
1880
1881     template<typename _Tp> _Tp& at(int i0, int i1, int i2);
1882     template<typename _Tp> const _Tp& at(int i0, int i1, int i2) const;
1883
1884     template<typename _Tp> _Tp& at(const int* idx);
1885     template<typename _Tp> const _Tp& at(const int* idx) const;
1886
1887     template<typename _Tp, int n> _Tp& at(const Vec<int, n>& idx);
1888     template<typename _Tp, int n> const _Tp& at(const Vec<int, n>& idx) const;
1889
1890     //! special versions for 2D arrays (especially convenient for referencing image pixels)
1891     template<typename _Tp> _Tp& at(Point pt);
1892     template<typename _Tp> const _Tp& at(Point pt) const;
1893
1894     //! template methods for iteration over matrix elements.
1895     // the iterators take care of skipping gaps in the end of rows (if any)
1896     template<typename _Tp> MatIterator_<_Tp> begin();
1897     template<typename _Tp> MatIterator_<_Tp> end();
1898     template<typename _Tp> MatConstIterator_<_Tp> begin() const;
1899     template<typename _Tp> MatConstIterator_<_Tp> end() const;
1900
1901     enum { MAGIC_VAL=0x42FF0000, AUTO_STEP=0, CONTINUOUS_FLAG=CV_MAT_CONT_FLAG, SUBMATRIX_FLAG=CV_SUBMAT_FLAG };
1902
1903     /*! includes several bit-fields:
1904          - the magic signature
1905          - continuity flag
1906          - depth
1907          - number of channels
1908      */
1909     int flags;
1910     //! the matrix dimensionality, >= 2
1911     int dims;
1912     //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
1913     int rows, cols;
1914     //! pointer to the data
1915     uchar* data;
1916
1917     //! pointer to the reference counter;
1918     // when matrix points to user-allocated data, the pointer is NULL
1919     int* refcount;
1920
1921     //! helper fields used in locateROI and adjustROI
1922     uchar* datastart;
1923     uchar* dataend;
1924     uchar* datalimit;
1925
1926     //! custom allocator
1927     MatAllocator* allocator;
1928
1929     struct CV_EXPORTS MSize
1930     {
1931         MSize(int* _p);
1932         Size operator()() const;
1933         const int& operator[](int i) const;
1934         int& operator[](int i);
1935         operator const int*() const;
1936         bool operator == (const MSize& sz) const;
1937         bool operator != (const MSize& sz) const;
1938
1939         int* p;
1940     };
1941
1942     struct CV_EXPORTS MStep
1943     {
1944         MStep();
1945         MStep(size_t s);
1946         const size_t& operator[](int i) const;
1947         size_t& operator[](int i);
1948         operator size_t() const;
1949         MStep& operator = (size_t s);
1950
1951         size_t* p;
1952         size_t buf[2];
1953     protected:
1954         MStep& operator = (const MStep&);
1955     };
1956
1957     MSize size;
1958     MStep step;
1959
1960 protected:
1961     void initEmpty();
1962 };
1963
1964
1965 /*!
1966    Random Number Generator
1967
1968    The class implements RNG using Multiply-with-Carry algorithm
1969 */
1970 class CV_EXPORTS RNG
1971 {
1972 public:
1973     enum { UNIFORM=0, NORMAL=1 };
1974
1975     RNG();
1976     RNG(uint64 state);
1977     //! updates the state and returns the next 32-bit unsigned integer random number
1978     unsigned next();
1979
1980     operator uchar();
1981     operator schar();
1982     operator ushort();
1983     operator short();
1984     operator unsigned();
1985     //! returns a random integer sampled uniformly from [0, N).
1986     unsigned operator ()(unsigned N);
1987     unsigned operator ()();
1988     operator int();
1989     operator float();
1990     operator double();
1991     //! returns uniformly distributed integer random number from [a,b) range
1992     int uniform(int a, int b);
1993     //! returns uniformly distributed floating-point random number from [a,b) range
1994     float uniform(float a, float b);
1995     //! returns uniformly distributed double-precision floating-point random number from [a,b) range
1996     double uniform(double a, double b);
1997     void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange=false );
1998     //! returns Gaussian random variate with mean zero.
1999     double gaussian(double sigma);
2000
2001     uint64 state;
2002 };
2003
2004
2005 /*!
2006  Termination criteria in iterative algorithms
2007  */
2008 class CV_EXPORTS TermCriteria
2009 {
2010 public:
2011     enum
2012     {
2013         COUNT=1, //!< the maximum number of iterations or elements to compute
2014         MAX_ITER=COUNT, //!< ditto
2015         EPS=2 //!< the desired accuracy or change in parameters at which the iterative algorithm stops
2016     };
2017
2018     //! default constructor
2019     TermCriteria();
2020     //! full constructor
2021     TermCriteria(int _type, int _maxCount, double _epsilon);
2022     //! conversion from CvTermCriteria
2023     TermCriteria(const CvTermCriteria& criteria);
2024     //! conversion from CvTermCriteria
2025     operator CvTermCriteria() const;
2026
2027     int type; //!< the type of termination criteria: COUNT, EPS or COUNT + EPS
2028     int maxCount; // the maximum number of iterations/elements
2029     double epsilon; // the desired accuracy
2030 };
2031
2032
2033 typedef void (*BinaryFunc)(const uchar* src1, size_t step1,
2034                            const uchar* src2, size_t step2,
2035                            uchar* dst, size_t step, Size sz,
2036                            void*);
2037
2038 CV_EXPORTS BinaryFunc getConvertFunc(int sdepth, int ddepth);
2039 CV_EXPORTS BinaryFunc getConvertScaleFunc(int sdepth, int ddepth);
2040 CV_EXPORTS BinaryFunc getCopyMaskFunc(size_t esz);
2041
2042 //! swaps two matrices
2043 CV_EXPORTS void swap(Mat& a, Mat& b);
2044
2045 //! converts array (CvMat or IplImage) to cv::Mat
2046 CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false,
2047                           bool allowND=true, int coiMode=0);
2048 //! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it.
2049 CV_EXPORTS void extractImageCOI(const CvArr* arr, OutputArray coiimg, int coi=-1);
2050 //! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage
2051 CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1);
2052
2053 //! adds one matrix to another (dst = src1 + src2)
2054 CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst,
2055                       InputArray mask=noArray(), int dtype=-1);
2056 //! subtracts one matrix from another (dst = src1 - src2)
2057 CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst,
2058                            InputArray mask=noArray(), int dtype=-1);
2059
2060 //! computes element-wise weighted product of the two arrays (dst = scale*src1*src2)
2061 CV_EXPORTS_W void multiply(InputArray src1, InputArray src2,
2062                            OutputArray dst, double scale=1, int dtype=-1);
2063
2064 //! computes element-wise weighted quotient of the two arrays (dst = scale*src1/src2)
2065 CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst,
2066                          double scale=1, int dtype=-1);
2067
2068 //! computes element-wise weighted reciprocal of an array (dst = scale/src2)
2069 CV_EXPORTS_W void divide(double scale, InputArray src2,
2070                          OutputArray dst, int dtype=-1);
2071
2072 //! adds scaled array to another one (dst = alpha*src1 + src2)
2073 CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst);
2074
2075 //! computes weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma)
2076 CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2,
2077                               double beta, double gamma, OutputArray dst, int dtype=-1);
2078
2079 //! 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)
2080 CV_EXPORTS_W void convertScaleAbs(InputArray src, OutputArray dst,
2081                                   double alpha=1, double beta=0);
2082 //! transforms array of numbers using a lookup table: dst(i)=lut(src(i))
2083 CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst,
2084                       int interpolation=0);
2085
2086 //! computes sum of array elements
2087 CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src);
2088 //! computes the number of nonzero array elements
2089 CV_EXPORTS_W int countNonZero( InputArray src );
2090 //! computes mean value of selected array elements
2091 CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask=noArray());
2092 //! computes mean value and standard deviation of all or selected array elements
2093 CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev,
2094                              InputArray mask=noArray());
2095 //! computes norm of the selected array part
2096 CV_EXPORTS_W double norm(InputArray src1, int normType=NORM_L2, InputArray mask=noArray());
2097 //! computes norm of selected part of the difference between two arrays
2098 CV_EXPORTS_W double norm(InputArray src1, InputArray src2,
2099                          int normType=NORM_L2, InputArray mask=noArray());
2100
2101 //! naive nearest neighbor finder
2102 CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2,
2103                                 OutputArray dist, int dtype, OutputArray nidx,
2104                                 int normType=NORM_L2, int K=0,
2105                                 InputArray mask=noArray(), int update=0,
2106                                 bool crosscheck=false);
2107
2108 //! 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
2109 CV_EXPORTS_W void normalize( InputArray src, OutputArray dst, double alpha=1, double beta=0,
2110                              int norm_type=NORM_L2, int dtype=-1, InputArray mask=noArray());
2111
2112 //! finds global minimum and maximum array elements and returns their values and their locations
2113 CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal,
2114                            CV_OUT double* maxVal=0, CV_OUT Point* minLoc=0,
2115                            CV_OUT Point* maxLoc=0, InputArray mask=noArray());
2116 CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal,
2117                           int* minIdx=0, int* maxIdx=0, InputArray mask=noArray());
2118
2119 //! transforms 2D matrix to 1D row or column vector by taking sum, minimum, maximum or mean value over all the rows
2120 CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype=-1);
2121
2122 //! makes multi-channel array out of several single-channel arrays
2123 CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst);
2124 //! makes multi-channel array out of several single-channel arrays
2125 CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst);
2126
2127 //! copies each plane of a multi-channel array to a dedicated array
2128 CV_EXPORTS void split(const Mat& src, Mat* mvbegin);
2129 //! copies each plane of a multi-channel array to a dedicated array
2130 CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv);
2131
2132 //! copies selected channels from the input arrays to the selected channels of the output arrays
2133 CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts,
2134                             const int* fromTo, size_t npairs);
2135 CV_EXPORTS void mixChannels(const vector<Mat>& src, vector<Mat>& dst,
2136                             const int* fromTo, size_t npairs);
2137 CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputArrayOfArrays dst,
2138                               const vector<int>& fromTo);
2139
2140 //! extracts a single channel from src (coi is 0-based index)
2141 CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi);
2142
2143 //! inserts a single channel to dst (coi is 0-based index)
2144 CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi);
2145
2146 //! reverses the order of the rows, columns or both in a matrix
2147 CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode);
2148
2149 //! replicates the input matrix the specified number of times in the horizontal and/or vertical direction
2150 CV_EXPORTS_W void repeat(InputArray src, int ny, int nx, OutputArray dst);
2151 CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx);
2152
2153 CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, OutputArray dst);
2154 CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst);
2155 CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst);
2156
2157 CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst);
2158 CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst);
2159 CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst);
2160
2161 //! computes bitwise conjunction of the two arrays (dst = src1 & src2)
2162 CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2,
2163                               OutputArray dst, InputArray mask=noArray());
2164 //! computes bitwise disjunction of the two arrays (dst = src1 | src2)
2165 CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2,
2166                              OutputArray dst, InputArray mask=noArray());
2167 //! computes bitwise exclusive-or of the two arrays (dst = src1 ^ src2)
2168 CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2,
2169                               OutputArray dst, InputArray mask=noArray());
2170 //! inverts each bit of array (dst = ~src)
2171 CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst,
2172                               InputArray mask=noArray());
2173 //! computes element-wise absolute difference of two arrays (dst = abs(src1 - src2))
2174 CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst);
2175 //! set mask elements for those array elements which are within the element-specific bounding box (dst = lowerb <= src && src < upperb)
2176 CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb,
2177                           InputArray upperb, OutputArray dst);
2178 //! compares elements of two arrays (dst = src1 <cmpop> src2)
2179 CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop);
2180 //! computes per-element minimum of two arrays (dst = min(src1, src2))
2181 CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst);
2182 //! computes per-element maximum of two arrays (dst = max(src1, src2))
2183 CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst);
2184
2185 //! computes per-element minimum of two arrays (dst = min(src1, src2))
2186 CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst);
2187 //! computes per-element minimum of array and scalar (dst = min(src1, src2))
2188 CV_EXPORTS void min(const Mat& src1, double src2, Mat& dst);
2189 //! computes per-element maximum of two arrays (dst = max(src1, src2))
2190 CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst);
2191 //! computes per-element maximum of array and scalar (dst = max(src1, src2))
2192 CV_EXPORTS void max(const Mat& src1, double src2, Mat& dst);
2193
2194 //! computes square root of each matrix element (dst = src**0.5)
2195 CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst);
2196 //! raises the input matrix elements to the specified power (b = a**power)
2197 CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst);
2198 //! computes exponent of each matrix element (dst = e**src)
2199 CV_EXPORTS_W void exp(InputArray src, OutputArray dst);
2200 //! computes natural logarithm of absolute value of each matrix element: dst = log(abs(src))
2201 CV_EXPORTS_W void log(InputArray src, OutputArray dst);
2202 //! computes cube root of the argument
2203 CV_EXPORTS_W float cubeRoot(float val);
2204 //! computes the angle in degrees (0..360) of the vector (x,y)
2205 CV_EXPORTS_W float fastAtan2(float y, float x);
2206
2207 CV_EXPORTS void exp(const float* src, float* dst, int n);
2208 CV_EXPORTS void log(const float* src, float* dst, int n);
2209 CV_EXPORTS void fastAtan2(const float* y, const float* x, float* dst, int n, bool angleInDegrees);
2210 CV_EXPORTS void magnitude(const float* x, const float* y, float* dst, int n);
2211
2212 //! converts polar coordinates to Cartesian
2213 CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle,
2214                               OutputArray x, OutputArray y, bool angleInDegrees=false);
2215 //! converts Cartesian coordinates to polar
2216 CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y,
2217                               OutputArray magnitude, OutputArray angle,
2218                               bool angleInDegrees=false);
2219 //! computes angle (angle(i)) of each (x(i), y(i)) vector
2220 CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle,
2221                         bool angleInDegrees=false);
2222 //! computes magnitude (magnitude(i)) of each (x(i), y(i)) vector
2223 CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude);
2224 //! checks that each matrix element is within the specified range.
2225 CV_EXPORTS_W bool checkRange(InputArray a, bool quiet=true, CV_OUT Point* pos=0,
2226                             double minVal=-DBL_MAX, double maxVal=DBL_MAX);
2227 //! converts NaN's to the given number
2228 CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val=0);
2229
2230 //! implements generalized matrix product algorithm GEMM from BLAS
2231 CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha,
2232                        InputArray src3, double gamma, OutputArray dst, int flags=0);
2233 //! multiplies matrix by its transposition from the left or from the right
2234 CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa,
2235                                  InputArray delta=noArray(),
2236                                  double scale=1, int dtype=-1 );
2237 //! transposes the matrix
2238 CV_EXPORTS_W void transpose(InputArray src, OutputArray dst);
2239 //! performs affine transformation of each element of multi-channel input matrix
2240 CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m );
2241 //! performs perspective transformation of each element of multi-channel input matrix
2242 CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m );
2243
2244 //! extends the symmetrical matrix from the lower half or from the upper half
2245 CV_EXPORTS_W void completeSymm(InputOutputArray mtx, bool lowerToUpper=false);
2246 //! initializes scaled identity matrix
2247 CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s=Scalar(1));
2248 //! computes determinant of a square matrix
2249 CV_EXPORTS_W double determinant(InputArray mtx);
2250 //! computes trace of a matrix
2251 CV_EXPORTS_W Scalar trace(InputArray mtx);
2252 //! computes inverse or pseudo-inverse matrix
2253 CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags=DECOMP_LU);
2254 //! solves linear system or a least-square problem
2255 CV_EXPORTS_W bool solve(InputArray src1, InputArray src2,
2256                         OutputArray dst, int flags=DECOMP_LU);
2257
2258 enum
2259 {
2260         SORT_EVERY_ROW=0,
2261         SORT_EVERY_COLUMN=1,
2262         SORT_ASCENDING=0,
2263         SORT_DESCENDING=16
2264 };
2265
2266 //! sorts independently each matrix row or each matrix column
2267 CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags);
2268 //! sorts independently each matrix row or each matrix column
2269 CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags);
2270 //! finds real roots of a cubic polynomial
2271 CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots);
2272 //! finds real and complex roots of a polynomial
2273 CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters=300);
2274 //! finds eigenvalues of a symmetric matrix
2275 CV_EXPORTS bool eigen(InputArray src, OutputArray eigenvalues, int lowindex=-1,
2276                       int highindex=-1);
2277 //! finds eigenvalues and eigenvectors of a symmetric matrix
2278 CV_EXPORTS bool eigen(InputArray src, OutputArray eigenvalues,
2279                       OutputArray eigenvectors,
2280                       int lowindex=-1, int highindex=-1);
2281 CV_EXPORTS_W bool eigen(InputArray src, bool computeEigenvectors,
2282                         OutputArray eigenvalues, OutputArray eigenvectors);
2283
2284 enum
2285 {
2286         COVAR_SCRAMBLED=0,
2287         COVAR_NORMAL=1,
2288         COVAR_USE_AVG=2,
2289         COVAR_SCALE=4,
2290         COVAR_ROWS=8,
2291         COVAR_COLS=16
2292 };
2293
2294 //! computes covariation matrix of a set of samples
2295 CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean,
2296                                  int flags, int ctype=CV_64F);
2297 //! computes covariation matrix of a set of samples
2298 CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar,
2299                                    OutputArray mean, int flags, int ctype=CV_64F);
2300
2301 /*!
2302     Principal Component Analysis
2303
2304     The class PCA is used to compute the special basis for a set of vectors.
2305     The basis will consist of eigenvectors of the covariance matrix computed
2306     from the input set of vectors. After PCA is performed, vectors can be transformed from
2307     the original high-dimensional space to the subspace formed by a few most
2308     prominent eigenvectors (called the principal components),
2309     corresponding to the largest eigenvalues of the covariation matrix.
2310     Thus the dimensionality of the vector and the correlation between the coordinates is reduced.
2311
2312     The following sample is the function that takes two matrices. The first one stores the set
2313     of vectors (a row per vector) that is used to compute PCA, the second one stores another
2314     "test" set of vectors (a row per vector) that are first compressed with PCA,
2315     then reconstructed back and then the reconstruction error norm is computed and printed for each vector.
2316
2317     \code
2318     using namespace cv;
2319
2320     PCA compressPCA(const Mat& pcaset, int maxComponents,
2321                     const Mat& testset, Mat& compressed)
2322     {
2323         PCA pca(pcaset, // pass the data
2324                 Mat(), // we do not have a pre-computed mean vector,
2325                        // so let the PCA engine to compute it
2326                 CV_PCA_DATA_AS_ROW, // indicate that the vectors
2327                                     // are stored as matrix rows
2328                                     // (use CV_PCA_DATA_AS_COL if the vectors are
2329                                     // the matrix columns)
2330                 maxComponents // specify, how many principal components to retain
2331                 );
2332         // if there is no test data, just return the computed basis, ready-to-use
2333         if( !testset.data )
2334             return pca;
2335         CV_Assert( testset.cols == pcaset.cols );
2336
2337         compressed.create(testset.rows, maxComponents, testset.type());
2338
2339         Mat reconstructed;
2340         for( int i = 0; i < testset.rows; i++ )
2341         {
2342             Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed;
2343             // compress the vector, the result will be stored
2344             // in the i-th row of the output matrix
2345             pca.project(vec, coeffs);
2346             // and then reconstruct it
2347             pca.backProject(coeffs, reconstructed);
2348             // and measure the error
2349             printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2));
2350         }
2351         return pca;
2352     }
2353     \endcode
2354 */
2355 class CV_EXPORTS PCA
2356 {
2357 public:
2358     //! default constructor
2359     PCA();
2360     //! the constructor that performs PCA
2361     PCA(InputArray data, InputArray mean, int flags, int maxComponents=0);
2362     //! operator that performs PCA. The previously stored data, if any, is released
2363     PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents=0);
2364     //! projects vector from the original space to the principal components subspace
2365     Mat project(InputArray vec) const;
2366     //! projects vector from the original space to the principal components subspace
2367     void project(InputArray vec, OutputArray result) const;
2368     //! reconstructs the original vector from the projection
2369     Mat backProject(InputArray vec) const;
2370     //! reconstructs the original vector from the projection
2371     void backProject(InputArray vec, OutputArray result) const;
2372
2373     Mat eigenvectors; //!< eigenvectors of the covariation matrix
2374     Mat eigenvalues; //!< eigenvalues of the covariation matrix
2375     Mat mean; //!< mean value subtracted before the projection and added after the back projection
2376 };
2377
2378 CV_EXPORTS_W void PCACompute(InputArray data, CV_OUT InputOutputArray mean,
2379                              OutputArray eigenvectors, int maxComponents=0);
2380
2381 CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean,
2382                              InputArray eigenvectors, OutputArray result);
2383
2384 CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean,
2385                                  InputArray eigenvectors, OutputArray result);
2386
2387
2388 /*!
2389     Singular Value Decomposition class
2390
2391     The class is used to compute Singular Value Decomposition of a floating-point matrix and then
2392     use it to solve least-square problems, under-determined linear systems, invert matrices,
2393     compute condition numbers etc.
2394
2395     For a bit faster operation you can pass flags=SVD::MODIFY_A|... to modify the decomposed matrix
2396     when it is not necessarily to preserve it. If you want to compute condition number of a matrix
2397     or absolute value of its determinant - you do not need SVD::u or SVD::vt,
2398     so you can pass flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that the full-size SVD::u and SVD::vt
2399     must be computed, which is not necessary most of the time.
2400 */
2401 class CV_EXPORTS SVD
2402 {
2403 public:
2404     enum { MODIFY_A=1, NO_UV=2, FULL_UV=4 };
2405     //! the default constructor
2406     SVD();
2407     //! the constructor that performs SVD
2408     SVD( InputArray src, int flags=0 );
2409     //! the operator that performs SVD. The previously allocated SVD::u, SVD::w are SVD::vt are released.
2410     SVD& operator ()( InputArray src, int flags=0 );
2411
2412     //! decomposes matrix and stores the results to user-provided matrices
2413     static void compute( InputArray src, OutputArray w,
2414                          OutputArray u, OutputArray vt, int flags=0 );
2415     //! computes singular values of a matrix
2416     static void compute( InputArray src, OutputArray w, int flags=0 );
2417     //! performs back substitution
2418     static void backSubst( InputArray w, InputArray u,
2419                            InputArray vt, InputArray rhs,
2420                            OutputArray dst );
2421
2422     template<typename _Tp, int m, int n, int nm> static void compute( const Matx<_Tp, m, n>& a,
2423         Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt );
2424     template<typename _Tp, int m, int n, int nm> static void compute( const Matx<_Tp, m, n>& a,
2425         Matx<_Tp, nm, 1>& w );
2426     template<typename _Tp, int m, int n, int nm, int nb> static void backSubst( const Matx<_Tp, nm, 1>& w,
2427         const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst );
2428
2429     //! finds dst = arg min_{|dst|=1} |m*dst|
2430     static void solveZ( InputArray src, OutputArray dst );
2431     //! performs back substitution, so that dst is the solution or pseudo-solution of m*dst = rhs, where m is the decomposed matrix
2432     void backSubst( InputArray rhs, OutputArray dst ) const;
2433
2434     Mat u, w, vt;
2435 };
2436
2437 //! computes SVD of src
2438 CV_EXPORTS_W void SVDecomp( InputArray src, CV_OUT OutputArray w,
2439     CV_OUT OutputArray u, CV_OUT OutputArray vt, int flags=0 );
2440
2441 //! performs back substitution for the previously computed SVD
2442 CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt,
2443                                InputArray rhs, CV_OUT OutputArray dst );
2444
2445 //! computes Mahalanobis distance between two vectors: sqrt((v1-v2)'*icovar*(v1-v2)), where icovar is the inverse covariation matrix
2446 CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar);
2447 //! a synonym for Mahalanobis
2448 CV_EXPORTS double Mahalonobis(InputArray v1, InputArray v2, InputArray icovar);
2449
2450 //! performs forward or inverse 1D or 2D Discrete Fourier Transformation
2451 CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags=0, int nonzeroRows=0);
2452 //! performs inverse 1D or 2D Discrete Fourier Transformation
2453 CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags=0, int nonzeroRows=0);
2454 //! performs forward or inverse 1D or 2D Discrete Cosine Transformation
2455 CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags=0);
2456 //! performs inverse 1D or 2D Discrete Cosine Transformation
2457 CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags=0);
2458 //! computes element-wise product of the two Fourier spectrums. The second spectrum can optionally be conjugated before the multiplication
2459 CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c,
2460                                int flags, bool conjB=false);
2461 //! computes the minimal vector size vecsize1 >= vecsize so that the dft() of the vector of length vecsize1 can be computed efficiently
2462 CV_EXPORTS_W int getOptimalDFTSize(int vecsize);
2463
2464 /*!
2465  Various k-Means flags
2466 */
2467 enum
2468 {
2469     KMEANS_RANDOM_CENTERS=0, // Chooses random centers for k-Means initialization
2470     KMEANS_PP_CENTERS=2,     // Uses k-Means++ algorithm for initialization
2471     KMEANS_USE_INITIAL_LABELS=1 // Uses the user-provided labels for K-Means initialization
2472 };
2473 //! clusters the input data using k-Means algorithm
2474 CV_EXPORTS_W double kmeans( InputArray data, int K, CV_OUT InputOutputArray bestLabels,
2475                             TermCriteria criteria, int attempts,
2476                             int flags, OutputArray centers=noArray() );
2477
2478 //! returns the thread-local Random number generator
2479 CV_EXPORTS RNG& theRNG();
2480
2481 //! returns the next unifomly-distributed random number of the specified type
2482 template<typename _Tp> static inline _Tp randu() { return (_Tp)theRNG(); }
2483
2484 //! fills array with uniformly-distributed random numbers from the range [low, high)
2485 CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high);
2486
2487 //! fills array with normally-distributed random numbers with the specified mean and the standard deviation
2488 CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev);
2489
2490 //! shuffles the input array elements
2491 CV_EXPORTS void randShuffle(InputOutputArray dst, double iterFactor=1., RNG* rng=0);
2492 CV_EXPORTS_AS(randShuffle) void randShuffle_(InputOutputArray dst, double iterFactor=1.);
2493
2494 //! draws the line segment (pt1, pt2) in the image
2495 CV_EXPORTS_W void line(CV_IN_OUT Mat& img, Point pt1, Point pt2, const Scalar& color,
2496                      int thickness=1, int lineType=8, int shift=0);
2497
2498 //! draws the rectangle outline or a solid rectangle with the opposite corners pt1 and pt2 in the image
2499 CV_EXPORTS_W void rectangle(CV_IN_OUT Mat& img, Point pt1, Point pt2,
2500                           const Scalar& color, int thickness=1,
2501                           int lineType=8, int shift=0);
2502
2503 //! draws the rectangle outline or a solid rectangle covering rec in the image
2504 CV_EXPORTS void rectangle(CV_IN_OUT Mat& img, Rect rec,
2505                           const Scalar& color, int thickness=1,
2506                           int lineType=8, int shift=0);
2507
2508 //! draws the circle outline or a solid circle in the image
2509 CV_EXPORTS_W void circle(CV_IN_OUT Mat& img, Point center, int radius,
2510                        const Scalar& color, int thickness=1,
2511                        int lineType=8, int shift=0);
2512
2513 //! draws an elliptic arc, ellipse sector or a rotated ellipse in the image
2514 CV_EXPORTS_W void ellipse(CV_IN_OUT Mat& img, Point center, Size axes,
2515                         double angle, double startAngle, double endAngle,
2516                         const Scalar& color, int thickness=1,
2517                         int lineType=8, int shift=0);
2518
2519 //! draws a rotated ellipse in the image
2520 CV_EXPORTS_W void ellipse(CV_IN_OUT Mat& img, const RotatedRect& box, const Scalar& color,
2521                         int thickness=1, int lineType=8);
2522
2523 //! draws a filled convex polygon in the image
2524 CV_EXPORTS void fillConvexPoly(Mat& img, const Point* pts, int npts,
2525                                const Scalar& color, int lineType=8,
2526                                int shift=0);
2527 CV_EXPORTS_W void fillConvexPoly(InputOutputArray img, InputArray points,
2528                                  const Scalar& color, int lineType=8,
2529                                  int shift=0);
2530
2531 //! fills an area bounded by one or more polygons
2532 CV_EXPORTS void fillPoly(Mat& img, const Point** pts,
2533                          const int* npts, int ncontours,
2534                          const Scalar& color, int lineType=8, int shift=0,
2535                          Point offset=Point() );
2536
2537 CV_EXPORTS_W void fillPoly(InputOutputArray img, InputArrayOfArrays pts,
2538                            const Scalar& color, int lineType=8, int shift=0,
2539                            Point offset=Point() );
2540
2541 //! draws one or more polygonal curves
2542 CV_EXPORTS void polylines(Mat& img, const Point* const* pts, const int* npts,
2543                           int ncontours, bool isClosed, const Scalar& color,
2544                           int thickness=1, int lineType=8, int shift=0 );
2545
2546 CV_EXPORTS_W void polylines(InputOutputArray img, InputArrayOfArrays pts,
2547                             bool isClosed, const Scalar& color,
2548                             int thickness=1, int lineType=8, int shift=0 );
2549
2550 //! draws contours in the image
2551 CV_EXPORTS_W void drawContours( InputOutputArray image, InputArrayOfArrays contours,
2552                               int contourIdx, const Scalar& color,
2553                               int thickness=1, int lineType=8,
2554                               InputArray hierarchy=noArray(),
2555                               int maxLevel=INT_MAX, Point offset=Point() );
2556
2557 //! clips the line segment by the rectangle Rect(0, 0, imgSize.width, imgSize.height)
2558 CV_EXPORTS bool clipLine(Size imgSize, CV_IN_OUT Point& pt1, CV_IN_OUT Point& pt2);
2559
2560 //! clips the line segment by the rectangle imgRect
2561 CV_EXPORTS_W bool clipLine(Rect imgRect, CV_OUT CV_IN_OUT Point& pt1, CV_OUT CV_IN_OUT Point& pt2);
2562
2563 /*!
2564    Line iterator class
2565
2566    The class is used to iterate over all the pixels on the raster line
2567    segment connecting two specified points.
2568 */
2569 class CV_EXPORTS LineIterator
2570 {
2571 public:
2572     //! intializes the iterator
2573     LineIterator( const Mat& img, Point pt1, Point pt2,
2574                   int connectivity=8, bool leftToRight=false );
2575     //! returns pointer to the current pixel
2576     uchar* operator *();
2577     //! prefix increment operator (++it). shifts iterator to the next pixel
2578     LineIterator& operator ++();
2579     //! postfix increment operator (it++). shifts iterator to the next pixel
2580     LineIterator operator ++(int);
2581     //! returns coordinates of the current pixel
2582     Point pos() const;
2583
2584     uchar* ptr;
2585     const uchar* ptr0;
2586     int step, elemSize;
2587     int err, count;
2588     int minusDelta, plusDelta;
2589     int minusStep, plusStep;
2590 };
2591
2592 //! converts elliptic arc to a polygonal curve
2593 CV_EXPORTS_W void ellipse2Poly( Point center, Size axes, int angle,
2594                                 int arcStart, int arcEnd, int delta,
2595                                 CV_OUT vector<Point>& pts );
2596
2597 enum
2598 {
2599     FONT_HERSHEY_SIMPLEX = 0,
2600     FONT_HERSHEY_PLAIN = 1,
2601     FONT_HERSHEY_DUPLEX = 2,
2602     FONT_HERSHEY_COMPLEX = 3,
2603     FONT_HERSHEY_TRIPLEX = 4,
2604     FONT_HERSHEY_COMPLEX_SMALL = 5,
2605     FONT_HERSHEY_SCRIPT_SIMPLEX = 6,
2606     FONT_HERSHEY_SCRIPT_COMPLEX = 7,
2607     FONT_ITALIC = 16
2608 };
2609
2610 //! renders text string in the image
2611 CV_EXPORTS_W void putText( Mat& img, const string& text, Point org,
2612                          int fontFace, double fontScale, Scalar color,
2613                          int thickness=1, int lineType=8,
2614                          bool bottomLeftOrigin=false );
2615
2616 //! returns bounding box of the text string
2617 CV_EXPORTS_W Size getTextSize(const string& text, int fontFace,
2618                             double fontScale, int thickness,
2619                             CV_OUT int* baseLine);
2620
2621 ///////////////////////////////// Mat_<_Tp> ////////////////////////////////////
2622
2623 /*!
2624  Template matrix class derived from Mat
2625
2626  The class Mat_ is a "thin" template wrapper on top of cv::Mat. It does not have any extra data fields,
2627  nor it or cv::Mat have any virtual methods and thus references or pointers to these two classes
2628  can be safely converted one to another. But do it with care, for example:
2629
2630  \code
2631  // create 100x100 8-bit matrix
2632  Mat M(100,100,CV_8U);
2633  // this will compile fine. no any data conversion will be done.
2634  Mat_<float>& M1 = (Mat_<float>&)M;
2635  // the program will likely crash at the statement below
2636  M1(99,99) = 1.f;
2637  \endcode
2638
2639  While cv::Mat is sufficient in most cases, cv::Mat_ can be more convenient if you use a lot of element
2640  access operations and if you know matrix type at compile time.
2641  Note that cv::Mat::at<_Tp>(int y, int x) and cv::Mat_<_Tp>::operator ()(int y, int x) do absolutely the
2642  same thing and run at the same speed, but the latter is certainly shorter:
2643
2644  \code
2645  Mat_<double> M(20,20);
2646  for(int i = 0; i < M.rows; i++)
2647     for(int j = 0; j < M.cols; j++)
2648        M(i,j) = 1./(i+j+1);
2649  Mat E, V;
2650  eigen(M,E,V);
2651  cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
2652  \endcode
2653
2654  It is easy to use Mat_ for multi-channel images/matrices - just pass cv::Vec as cv::Mat_ template parameter:
2655
2656  \code
2657  // allocate 320x240 color image and fill it with green (in RGB space)
2658  Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
2659  // now draw a diagonal white line
2660  for(int i = 0; i < 100; i++)
2661      img(i,i)=Vec3b(255,255,255);
2662  // and now modify the 2nd (red) channel of each pixel
2663  for(int i = 0; i < img.rows; i++)
2664     for(int j = 0; j < img.cols; j++)
2665        img(i,j)[2] ^= (uchar)(i ^ j); // img(y,x)[c] accesses c-th channel of the pixel (x,y)
2666  \endcode
2667 */
2668 template<typename _Tp> class CV_EXPORTS Mat_ : public Mat
2669 {
2670 public:
2671     typedef _Tp value_type;
2672     typedef typename DataType<_Tp>::channel_type channel_type;
2673     typedef MatIterator_<_Tp> iterator;
2674     typedef MatConstIterator_<_Tp> const_iterator;
2675
2676     //! default constructor
2677     Mat_();
2678     //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type)
2679     Mat_(int _rows, int _cols);
2680     //! constructor that sets each matrix element to specified value
2681     Mat_(int _rows, int _cols, const _Tp& value);
2682     //! equivalent to Mat(_size, DataType<_Tp>::type)
2683     explicit Mat_(Size _size);
2684     //! constructor that sets each matrix element to specified value
2685     Mat_(Size _size, const _Tp& value);
2686     //! n-dim array constructor
2687     Mat_(int _ndims, const int* _sizes);
2688     //! n-dim array constructor that sets each matrix element to specified value
2689     Mat_(int _ndims, const int* _sizes, const _Tp& value);
2690     //! copy/conversion contructor. If m is of different type, it's converted
2691     Mat_(const Mat& m);
2692     //! copy constructor
2693     Mat_(const Mat_& m);
2694     //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type
2695     Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP);
2696     //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type
2697     Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0);
2698     //! selects a submatrix
2699     Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all());
2700     //! selects a submatrix
2701     Mat_(const Mat_& m, const Rect& roi);
2702     //! selects a submatrix, n-dim version
2703     Mat_(const Mat_& m, const Range* ranges);
2704     //! from a matrix expression
2705     explicit Mat_(const MatExpr& e);
2706     //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column
2707     explicit Mat_(const vector<_Tp>& vec, bool copyData=false);
2708     template<int n> explicit Mat_(const Vec<typename DataType<_Tp>::channel_type, n>& vec, bool copyData=true);
2709     template<int m, int n> explicit Mat_(const Matx<typename DataType<_Tp>::channel_type, m, n>& mtx, bool copyData=true);
2710     explicit Mat_(const Point_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
2711     explicit Mat_(const Point3_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
2712     explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer);
2713
2714     Mat_& operator = (const Mat& m);
2715     Mat_& operator = (const Mat_& m);
2716     //! set all the elements to s.
2717     Mat_& operator = (const _Tp& s);
2718     //! assign a matrix expression
2719     Mat_& operator = (const MatExpr& e);
2720
2721     //! iterators; they are smart enough to skip gaps in the end of rows
2722     iterator begin();
2723     iterator end();
2724     const_iterator begin() const;
2725     const_iterator end() const;
2726
2727     //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type)
2728     void create(int _rows, int _cols);
2729     //! equivalent to Mat::create(_size, DataType<_Tp>::type)
2730     void create(Size _size);
2731     //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type)
2732     void create(int _ndims, const int* _sizes);
2733     //! cross-product
2734     Mat_ cross(const Mat_& m) const;
2735     //! data type conversion
2736     template<typename T2> operator Mat_<T2>() const;
2737     //! overridden forms of Mat::row() etc.
2738     Mat_ row(int y) const;
2739     Mat_ col(int x) const;
2740     Mat_ diag(int d=0) const;
2741     Mat_ clone() const;
2742
2743     //! overridden forms of Mat::elemSize() etc.
2744     size_t elemSize() const;
2745     size_t elemSize1() const;
2746     int type() const;
2747     int depth() const;
2748     int channels() const;
2749     size_t step1(int i=0) const;
2750     //! returns step()/sizeof(_Tp)
2751     size_t stepT(int i=0) const;
2752
2753     //! overridden forms of Mat::zeros() etc. Data type is omitted, of course
2754     static MatExpr zeros(int rows, int cols);
2755     static MatExpr zeros(Size size);
2756     static MatExpr zeros(int _ndims, const int* _sizes);
2757     static MatExpr ones(int rows, int cols);
2758     static MatExpr ones(Size size);
2759     static MatExpr ones(int _ndims, const int* _sizes);
2760     static MatExpr eye(int rows, int cols);
2761     static MatExpr eye(Size size);
2762
2763     //! some more overriden methods
2764     Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright );
2765     Mat_ operator()( const Range& rowRange, const Range& colRange ) const;
2766     Mat_ operator()( const Rect& roi ) const;
2767     Mat_ operator()( const Range* ranges ) const;
2768
2769     //! more convenient forms of row and element access operators
2770     _Tp* operator [](int y);
2771     const _Tp* operator [](int y) const;
2772
2773     //! returns reference to the specified element
2774     _Tp& operator ()(const int* idx);
2775     //! returns read-only reference to the specified element
2776     const _Tp& operator ()(const int* idx) const;
2777
2778     //! returns reference to the specified element
2779     template<int n> _Tp& operator ()(const Vec<int, n>& idx);
2780     //! returns read-only reference to the specified element
2781     template<int n> const _Tp& operator ()(const Vec<int, n>& idx) const;
2782
2783     //! returns reference to the specified element (1D case)
2784     _Tp& operator ()(int idx0);
2785     //! returns read-only reference to the specified element (1D case)
2786     const _Tp& operator ()(int idx0) const;
2787     //! returns reference to the specified element (2D case)
2788     _Tp& operator ()(int idx0, int idx1);
2789     //! returns read-only reference to the specified element (2D case)
2790     const _Tp& operator ()(int idx0, int idx1) const;
2791     //! returns reference to the specified element (3D case)
2792     _Tp& operator ()(int idx0, int idx1, int idx2);
2793     //! returns read-only reference to the specified element (3D case)
2794     const _Tp& operator ()(int idx0, int idx1, int idx2) const;
2795
2796     _Tp& operator ()(Point pt);
2797     const _Tp& operator ()(Point pt) const;
2798
2799     //! conversion to vector.
2800     operator vector<_Tp>() const;
2801     //! conversion to Vec
2802     template<int n> operator Vec<typename DataType<_Tp>::channel_type, n>() const;
2803     //! conversion to Matx
2804     template<int m, int n> operator Matx<typename DataType<_Tp>::channel_type, m, n>() const;
2805 };
2806
2807 typedef Mat_<uchar> Mat1b;
2808 typedef Mat_<Vec2b> Mat2b;
2809 typedef Mat_<Vec3b> Mat3b;
2810 typedef Mat_<Vec4b> Mat4b;
2811
2812 typedef Mat_<short> Mat1s;
2813 typedef Mat_<Vec2s> Mat2s;
2814 typedef Mat_<Vec3s> Mat3s;
2815 typedef Mat_<Vec4s> Mat4s;
2816
2817 typedef Mat_<ushort> Mat1w;
2818 typedef Mat_<Vec2w> Mat2w;
2819 typedef Mat_<Vec3w> Mat3w;
2820 typedef Mat_<Vec4w> Mat4w;
2821
2822 typedef Mat_<int>   Mat1i;
2823 typedef Mat_<Vec2i> Mat2i;
2824 typedef Mat_<Vec3i> Mat3i;
2825 typedef Mat_<Vec4i> Mat4i;
2826
2827 typedef Mat_<float> Mat1f;
2828 typedef Mat_<Vec2f> Mat2f;
2829 typedef Mat_<Vec3f> Mat3f;
2830 typedef Mat_<Vec4f> Mat4f;
2831
2832 typedef Mat_<double> Mat1d;
2833 typedef Mat_<Vec2d> Mat2d;
2834 typedef Mat_<Vec3d> Mat3d;
2835 typedef Mat_<Vec4d> Mat4d;
2836
2837 //////////// Iterators & Comma initializers //////////////////
2838
2839 class CV_EXPORTS MatConstIterator
2840 {
2841 public:
2842     typedef uchar* value_type;
2843     typedef ptrdiff_t difference_type;
2844     typedef const uchar** pointer;
2845     typedef uchar* reference;
2846     typedef std::random_access_iterator_tag iterator_category;
2847
2848     //! default constructor
2849     MatConstIterator();
2850     //! constructor that sets the iterator to the beginning of the matrix
2851     MatConstIterator(const Mat* _m);
2852     //! constructor that sets the iterator to the specified element of the matrix
2853     MatConstIterator(const Mat* _m, int _row, int _col=0);
2854     //! constructor that sets the iterator to the specified element of the matrix
2855     MatConstIterator(const Mat* _m, Point _pt);
2856     //! constructor that sets the iterator to the specified element of the matrix
2857     MatConstIterator(const Mat* _m, const int* _idx);
2858     //! copy constructor
2859     MatConstIterator(const MatConstIterator& it);
2860
2861     //! copy operator
2862     MatConstIterator& operator = (const MatConstIterator& it);
2863     //! returns the current matrix element
2864     uchar* operator *() const;
2865     //! returns the i-th matrix element, relative to the current
2866     uchar* operator [](ptrdiff_t i) const;
2867
2868     //! shifts the iterator forward by the specified number of elements
2869     MatConstIterator& operator += (ptrdiff_t ofs);
2870     //! shifts the iterator backward by the specified number of elements
2871     MatConstIterator& operator -= (ptrdiff_t ofs);
2872     //! decrements the iterator
2873     MatConstIterator& operator --();
2874     //! decrements the iterator
2875     MatConstIterator operator --(int);
2876     //! increments the iterator
2877     MatConstIterator& operator ++();
2878     //! increments the iterator
2879     MatConstIterator operator ++(int);
2880     //! returns the current iterator position
2881     Point pos() const;
2882     //! returns the current iterator position
2883     void pos(int* _idx) const;
2884     ptrdiff_t lpos() const;
2885     void seek(ptrdiff_t ofs, bool relative=false);
2886     void seek(const int* _idx, bool relative=false);
2887
2888     const Mat* m;
2889     size_t elemSize;
2890     uchar* ptr;
2891     uchar* sliceStart;
2892     uchar* sliceEnd;
2893 };
2894
2895 /*!
2896  Matrix read-only iterator
2897
2898  */
2899 template<typename _Tp>
2900 class CV_EXPORTS MatConstIterator_ : public MatConstIterator
2901 {
2902 public:
2903     typedef _Tp value_type;
2904     typedef ptrdiff_t difference_type;
2905     typedef const _Tp* pointer;
2906     typedef const _Tp& reference;
2907     typedef std::random_access_iterator_tag iterator_category;
2908
2909     //! default constructor
2910     MatConstIterator_();
2911     //! constructor that sets the iterator to the beginning of the matrix
2912     MatConstIterator_(const Mat_<_Tp>* _m);
2913     //! constructor that sets the iterator to the specified element of the matrix
2914     MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0);
2915     //! constructor that sets the iterator to the specified element of the matrix
2916     MatConstIterator_(const Mat_<_Tp>* _m, Point _pt);
2917     //! constructor that sets the iterator to the specified element of the matrix
2918     MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx);
2919     //! copy constructor
2920     MatConstIterator_(const MatConstIterator_& it);
2921
2922     //! copy operator
2923     MatConstIterator_& operator = (const MatConstIterator_& it);
2924     //! returns the current matrix element
2925     _Tp operator *() const;
2926     //! returns the i-th matrix element, relative to the current
2927     _Tp operator [](ptrdiff_t i) const;
2928
2929     //! shifts the iterator forward by the specified number of elements
2930     MatConstIterator_& operator += (ptrdiff_t ofs);
2931     //! shifts the iterator backward by the specified number of elements
2932     MatConstIterator_& operator -= (ptrdiff_t ofs);
2933     //! decrements the iterator
2934     MatConstIterator_& operator --();
2935     //! decrements the iterator
2936     MatConstIterator_ operator --(int);
2937     //! increments the iterator
2938     MatConstIterator_& operator ++();
2939     //! increments the iterator
2940     MatConstIterator_ operator ++(int);
2941     //! returns the current iterator position
2942     Point pos() const;
2943 };
2944
2945
2946 /*!
2947  Matrix read-write iterator
2948
2949 */
2950 template<typename _Tp>
2951 class CV_EXPORTS MatIterator_ : public MatConstIterator_<_Tp>
2952 {
2953 public:
2954     typedef _Tp* pointer;
2955     typedef _Tp& reference;
2956     typedef std::random_access_iterator_tag iterator_category;
2957
2958     //! the default constructor
2959     MatIterator_();
2960     //! constructor that sets the iterator to the beginning of the matrix
2961     MatIterator_(Mat_<_Tp>* _m);
2962     //! constructor that sets the iterator to the specified element of the matrix
2963     MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0);
2964     //! constructor that sets the iterator to the specified element of the matrix
2965     MatIterator_(const Mat_<_Tp>* _m, Point _pt);
2966     //! constructor that sets the iterator to the specified element of the matrix
2967     MatIterator_(const Mat_<_Tp>* _m, const int* _idx);
2968     //! copy constructor
2969     MatIterator_(const MatIterator_& it);
2970     //! copy operator
2971     MatIterator_& operator = (const MatIterator_<_Tp>& it );
2972
2973     //! returns the current matrix element
2974     _Tp& operator *() const;
2975     //! returns the i-th matrix element, relative to the current
2976     _Tp& operator [](ptrdiff_t i) const;
2977
2978     //! shifts the iterator forward by the specified number of elements
2979     MatIterator_& operator += (ptrdiff_t ofs);
2980     //! shifts the iterator backward by the specified number of elements
2981     MatIterator_& operator -= (ptrdiff_t ofs);
2982     //! decrements the iterator
2983     MatIterator_& operator --();
2984     //! decrements the iterator
2985     MatIterator_ operator --(int);
2986     //! increments the iterator
2987     MatIterator_& operator ++();
2988     //! increments the iterator
2989     MatIterator_ operator ++(int);
2990 };
2991
2992 template<typename _Tp> class CV_EXPORTS MatOp_Iter_;
2993
2994 /*!
2995  Comma-separated Matrix Initializer
2996
2997  The class instances are usually not created explicitly.
2998  Instead, they are created on "matrix << firstValue" operator.
2999
3000  The sample below initializes 2x2 rotation matrix:
3001
3002  \code
3003  double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180);
3004  Mat R = (Mat_<double>(2,2) << a, -b, b, a);
3005  \endcode
3006 */
3007 template<typename _Tp> class CV_EXPORTS MatCommaInitializer_
3008 {
3009 public:
3010     //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat
3011     MatCommaInitializer_(Mat_<_Tp>* _m);
3012     //! the operator that takes the next value and put it to the matrix
3013     template<typename T2> MatCommaInitializer_<_Tp>& operator , (T2 v);
3014     //! another form of conversion operator
3015     Mat_<_Tp> operator *() const;
3016     operator Mat_<_Tp>() const;
3017 protected:
3018     MatIterator_<_Tp> it;
3019 };
3020
3021
3022 template<typename _Tp, int m, int n> class CV_EXPORTS MatxCommaInitializer
3023 {
3024 public:
3025     MatxCommaInitializer(Matx<_Tp, m, n>* _mtx);
3026     template<typename T2> MatxCommaInitializer<_Tp, m, n>& operator , (T2 val);
3027     Matx<_Tp, m, n> operator *() const;
3028
3029     Matx<_Tp, m, n>* dst;
3030     int idx;
3031 };
3032
3033 template<typename _Tp, int m> class CV_EXPORTS VecCommaInitializer : public MatxCommaInitializer<_Tp, m, 1>
3034 {
3035 public:
3036     VecCommaInitializer(Vec<_Tp, m>* _vec);
3037     template<typename T2> VecCommaInitializer<_Tp, m>& operator , (T2 val);
3038     Vec<_Tp, m> operator *() const;
3039 };
3040
3041 /*!
3042  Automatically Allocated Buffer Class
3043
3044  The class is used for temporary buffers in functions and methods.
3045  If a temporary buffer is usually small (a few K's of memory),
3046  but its size depends on the parameters, it makes sense to create a small
3047  fixed-size array on stack and use it if it's large enough. If the required buffer size
3048  is larger than the fixed size, another buffer of sufficient size is allocated dynamically
3049  and released after the processing. Therefore, in typical cases, when the buffer size is small,
3050  there is no overhead associated with malloc()/free().
3051  At the same time, there is no limit on the size of processed data.
3052
3053  This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and
3054  the number of stack-allocated elements. Here is how the class is used:
3055
3056  \code
3057  void my_func(const cv::Mat& m)
3058  {
3059     cv::AutoBuffer<float, 1000> buf; // create automatic buffer containing 1000 floats
3060
3061     buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used,
3062                           // otherwise the buffer of "m.rows" floats will be allocated
3063                           // dynamically and deallocated in cv::AutoBuffer destructor
3064     ...
3065  }
3066  \endcode
3067 */
3068 template<typename _Tp, size_t fixed_size=4096/sizeof(_Tp)+8> class CV_EXPORTS AutoBuffer
3069 {
3070 public:
3071     typedef _Tp value_type;
3072     enum { buffer_padding = (int)((16 + sizeof(_Tp) - 1)/sizeof(_Tp)) };
3073
3074     //! the default contructor
3075     AutoBuffer();
3076     //! constructor taking the real buffer size
3077     AutoBuffer(size_t _size);
3078     //! destructor. calls deallocate()
3079     ~AutoBuffer();
3080
3081     //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used
3082     void allocate(size_t _size);
3083     //! deallocates the buffer if it was dynamically allocated
3084     void deallocate();
3085     //! returns pointer to the real buffer, stack-allocated or head-allocated
3086     operator _Tp* ();
3087     //! returns read-only pointer to the real buffer, stack-allocated or head-allocated
3088     operator const _Tp* () const;
3089
3090 protected:
3091     //! pointer to the real buffer, can point to buf if the buffer is small enough
3092     _Tp* ptr;
3093     //! size of the real buffer
3094     size_t size;
3095     //! pre-allocated buffer
3096     _Tp buf[fixed_size+buffer_padding];
3097 };
3098
3099 /////////////////////////// multi-dimensional dense matrix //////////////////////////
3100
3101 /*!
3102  n-Dimensional Dense Matrix Iterator Class.
3103
3104  The class cv::NAryMatIterator is used for iterating over one or more n-dimensional dense arrays (cv::Mat's).
3105
3106  The iterator is completely different from cv::Mat_ and cv::SparseMat_ iterators.
3107  It iterates through the slices (or planes), not the elements, where "slice" is a continuous part of the arrays.
3108
3109  Here is the example on how the iterator can be used to normalize 3D histogram:
3110
3111  \code
3112  void normalizeColorHist(Mat& hist)
3113  {
3114  #if 1
3115      // intialize iterator (the style is different from STL).
3116      // after initialization the iterator will contain
3117      // the number of slices or planes
3118      // the iterator will go through
3119      Mat* arrays[] = { &hist, 0 };
3120      Mat planes[1];
3121      NAryMatIterator it(arrays, planes);
3122      double s = 0;
3123      // iterate through the matrix. on each iteration
3124      // it.planes[i] (of type Mat) will be set to the current plane of
3125      // i-th n-dim matrix passed to the iterator constructor.
3126      for(int p = 0; p < it.nplanes; p++, ++it)
3127         s += sum(it.planes[0])[0];
3128      it = NAryMatIterator(hist);
3129      s = 1./s;
3130      for(int p = 0; p < it.nplanes; p++, ++it)
3131         it.planes[0] *= s;
3132  #elif 1
3133      // this is a shorter implementation of the above
3134      // using built-in operations on Mat
3135      double s = sum(hist)[0];
3136      hist.convertTo(hist, hist.type(), 1./s, 0);
3137  #else
3138      // and this is even shorter one
3139      // (assuming that the histogram elements are non-negative)
3140      normalize(hist, hist, 1, 0, NORM_L1);
3141  #endif
3142  }
3143  \endcode
3144
3145  You can iterate through several matrices simultaneously as long as they have the same geometry
3146  (dimensionality and all the dimension sizes are the same), which is useful for binary
3147  and n-ary operations on such matrices. Just pass those matrices to cv::MatNDIterator.
3148  Then, during the iteration it.planes[0], it.planes[1], ... will
3149  be the slices of the corresponding matrices
3150 */
3151 class CV_EXPORTS NAryMatIterator
3152 {
3153 public:
3154     //! the default constructor
3155     NAryMatIterator();
3156     //! the full constructor taking arbitrary number of n-dim matrices
3157     NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1);
3158     //! the full constructor taking arbitrary number of n-dim matrices
3159     NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1);
3160     //! the separate iterator initialization method
3161     void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1);
3162
3163     //! proceeds to the next plane of every iterated matrix
3164     NAryMatIterator& operator ++();
3165     //! proceeds to the next plane of every iterated matrix (postfix increment operator)
3166     NAryMatIterator operator ++(int);
3167
3168     //! the iterated arrays
3169     const Mat** arrays;
3170     //! the current planes
3171     Mat* planes;
3172     //! data pointers
3173     uchar** ptrs;
3174     //! the number of arrays
3175     int narrays;
3176     //! the number of hyper-planes that the iterator steps through
3177     size_t nplanes;
3178     //! the size of each segment (in elements)
3179     size_t size;
3180 protected:
3181     int iterdepth;
3182     size_t idx;
3183 };
3184
3185 //typedef NAryMatIterator NAryMatNDIterator;
3186
3187 typedef void (*ConvertData)(const void* from, void* to, int cn);
3188 typedef void (*ConvertScaleData)(const void* from, void* to, int cn, double alpha, double beta);
3189
3190 //! returns the function for converting pixels from one data type to another
3191 CV_EXPORTS ConvertData getConvertElem(int fromType, int toType);
3192 //! returns the function for converting pixels from one data type to another with the optional scaling
3193 CV_EXPORTS ConvertScaleData getConvertScaleElem(int fromType, int toType);
3194
3195
3196 /////////////////////////// multi-dimensional sparse matrix //////////////////////////
3197
3198 class SparseMatIterator;
3199 class SparseMatConstIterator;
3200 template<typename _Tp> class SparseMatIterator_;
3201 template<typename _Tp> class SparseMatConstIterator_;
3202
3203 /*!
3204  Sparse matrix class.
3205
3206  The class represents multi-dimensional sparse numerical arrays. Such a sparse array can store elements
3207  of any type that cv::Mat is able to store. "Sparse" means that only non-zero elements
3208  are stored (though, as a result of some operations on a sparse matrix, some of its stored elements
3209  can actually become 0. It's user responsibility to detect such elements and delete them using cv::SparseMat::erase().
3210  The non-zero elements are stored in a hash table that grows when it's filled enough,
3211  so that the search time remains O(1) in average. Elements can be accessed using the following methods:
3212
3213  <ol>
3214  <li>Query operations: cv::SparseMat::ptr() and the higher-level cv::SparseMat::ref(),
3215       cv::SparseMat::value() and cv::SparseMat::find, for example:
3216  \code
3217  const int dims = 5;
3218  int size[] = {10, 10, 10, 10, 10};
3219  SparseMat sparse_mat(dims, size, CV_32F);
3220  for(int i = 0; i < 1000; i++)
3221  {
3222      int idx[dims];
3223      for(int k = 0; k < dims; k++)
3224         idx[k] = rand()%sparse_mat.size(k);
3225      sparse_mat.ref<float>(idx) += 1.f;
3226  }
3227  \endcode
3228
3229  <li>Sparse matrix iterators. Like cv::Mat iterators and unlike cv::Mat iterators, the sparse matrix iterators are STL-style,
3230  that is, the iteration is done as following:
3231  \code
3232  // prints elements of a sparse floating-point matrix and the sum of elements.
3233  SparseMatConstIterator_<float>
3234         it = sparse_mat.begin<float>(),
3235         it_end = sparse_mat.end<float>();
3236  double s = 0;
3237  int dims = sparse_mat.dims();
3238  for(; it != it_end; ++it)
3239  {
3240      // print element indices and the element value
3241      const Node* n = it.node();
3242      printf("(")
3243      for(int i = 0; i < dims; i++)
3244         printf("%3d%c", n->idx[i], i < dims-1 ? ',' : ')');
3245      printf(": %f\n", *it);
3246      s += *it;
3247  }
3248  printf("Element sum is %g\n", s);
3249  \endcode
3250  If you run this loop, you will notice that elements are enumerated
3251  in no any logical order (lexicographical etc.),
3252  they come in the same order as they stored in the hash table, i.e. semi-randomly.
3253
3254  You may collect pointers to the nodes and sort them to get the proper ordering.
3255  Note, however, that pointers to the nodes may become invalid when you add more
3256  elements to the matrix; this is because of possible buffer reallocation.
3257
3258  <li>A combination of the above 2 methods when you need to process 2 or more sparse
3259  matrices simultaneously, e.g. this is how you can compute unnormalized
3260  cross-correlation of the 2 floating-point sparse matrices:
3261  \code
3262  double crossCorr(const SparseMat& a, const SparseMat& b)
3263  {
3264      const SparseMat *_a = &a, *_b = &b;
3265      // if b contains less elements than a,
3266      // it's faster to iterate through b
3267      if(_a->nzcount() > _b->nzcount())
3268         std::swap(_a, _b);
3269      SparseMatConstIterator_<float> it = _a->begin<float>(),
3270                                     it_end = _a->end<float>();
3271      double ccorr = 0;
3272      for(; it != it_end; ++it)
3273      {
3274          // take the next element from the first matrix
3275          float avalue = *it;
3276          const Node* anode = it.node();
3277          // and try to find element with the same index in the second matrix.
3278          // since the hash value depends only on the element index,
3279          // we reuse hashvalue stored in the node
3280          float bvalue = _b->value<float>(anode->idx,&anode->hashval);
3281          ccorr += avalue*bvalue;
3282      }
3283      return ccorr;
3284  }
3285  \endcode
3286  </ol>
3287 */
3288 class CV_EXPORTS SparseMat
3289 {
3290 public:
3291     typedef SparseMatIterator iterator;
3292     typedef SparseMatConstIterator const_iterator;
3293
3294     //! the sparse matrix header
3295     struct CV_EXPORTS Hdr
3296     {
3297         Hdr(int _dims, const int* _sizes, int _type);
3298         void clear();
3299         int refcount;
3300         int dims;
3301         int valueOffset;
3302         size_t nodeSize;
3303         size_t nodeCount;
3304         size_t freeList;
3305         vector<uchar> pool;
3306         vector<size_t> hashtab;
3307         int size[CV_MAX_DIM];
3308     };
3309
3310     //! sparse matrix node - element of a hash table
3311     struct CV_EXPORTS Node
3312     {
3313         //! hash value
3314         size_t hashval;
3315         //! index of the next node in the same hash table entry
3316         size_t next;
3317         //! index of the matrix element
3318         int idx[CV_MAX_DIM];
3319     };
3320
3321     //! default constructor
3322     SparseMat();
3323     //! creates matrix of the specified size and type
3324     SparseMat(int dims, const int* _sizes, int _type);
3325     //! copy constructor
3326     SparseMat(const SparseMat& m);
3327     //! converts dense 2d matrix to the sparse form
3328     /*!
3329      \param m the input matrix
3330      \param try1d if true and m is a single-column matrix (Nx1),
3331             then the sparse matrix will be 1-dimensional.
3332     */
3333     explicit SparseMat(const Mat& m);
3334     //! converts old-style sparse matrix to the new-style. All the data is copied
3335     SparseMat(const CvSparseMat* m);
3336     //! the destructor
3337     ~SparseMat();
3338
3339     //! assignment operator. This is O(1) operation, i.e. no data is copied
3340     SparseMat& operator = (const SparseMat& m);
3341     //! equivalent to the corresponding constructor
3342     SparseMat& operator = (const Mat& m);
3343
3344     //! creates full copy of the matrix
3345     SparseMat clone() const;
3346
3347     //! copies all the data to the destination matrix. All the previous content of m is erased
3348     void copyTo( SparseMat& m ) const;
3349     //! converts sparse matrix to dense matrix.
3350     void copyTo( Mat& m ) const;
3351     //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type
3352     void convertTo( SparseMat& m, int rtype, double alpha=1 ) const;
3353     //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling.
3354     /*!
3355       \param rtype The output matrix data type. When it is =-1, the output array will have the same data type as (*this)
3356       \param alpha The scale factor
3357       \param beta The optional delta added to the scaled values before the conversion
3358     */
3359     void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
3360
3361     // not used now
3362     void assignTo( SparseMat& m, int type=-1 ) const;
3363
3364     //! reallocates sparse matrix.
3365     /*!
3366         If the matrix already had the proper size and type,
3367         it is simply cleared with clear(), otherwise,
3368         the old matrix is released (using release()) and the new one is allocated.
3369     */
3370     void create(int dims, const int* _sizes, int _type);
3371     //! sets all the sparse matrix elements to 0, which means clearing the hash table.
3372     void clear();
3373     //! manually increments the reference counter to the header.
3374     void addref();
3375     // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated.
3376     void release();
3377
3378     //! converts sparse matrix to the old-style representation; all the elements are copied.
3379     operator CvSparseMat*() const;
3380     //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements)
3381     size_t elemSize() const;
3382     //! returns elemSize()/channels()
3383     size_t elemSize1() const;
3384
3385     //! returns type of sparse matrix elements
3386     int type() const;
3387     //! returns the depth of sparse matrix elements
3388     int depth() const;
3389     //! returns the number of channels
3390     int channels() const;
3391
3392     //! returns the array of sizes, or NULL if the matrix is not allocated
3393     const int* size() const;
3394     //! returns the size of i-th matrix dimension (or 0)
3395     int size(int i) const;
3396     //! returns the matrix dimensionality
3397     int dims() const;
3398     //! returns the number of non-zero elements (=the number of hash table nodes)
3399     size_t nzcount() const;
3400
3401     //! computes the element hash value (1D case)
3402     size_t hash(int i0) const;
3403     //! computes the element hash value (2D case)
3404     size_t hash(int i0, int i1) const;
3405     //! computes the element hash value (3D case)
3406     size_t hash(int i0, int i1, int i2) const;
3407     //! computes the element hash value (nD case)
3408     size_t hash(const int* idx) const;
3409
3410     //@{
3411     /*!
3412      specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case.
3413
3414      return pointer to the matrix element.
3415      <ul>
3416       <li>if the element is there (it's non-zero), the pointer to it is returned
3417       <li>if it's not there and createMissing=false, NULL pointer is returned
3418       <li>if it's not there and createMissing=true, then the new element
3419         is created and initialized with 0. Pointer to it is returned
3420       <li>if the optional hashval pointer is not NULL, the element hash value is
3421       not computed, but *hashval is taken instead.
3422      </ul>
3423     */
3424     //! returns pointer to the specified element (1D case)
3425     uchar* ptr(int i0, bool createMissing, size_t* hashval=0);
3426     //! returns pointer to the specified element (2D case)
3427     uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0);
3428     //! returns pointer to the specified element (3D case)
3429     uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0);
3430     //! returns pointer to the specified element (nD case)
3431     uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0);
3432     //@}
3433
3434     //@{
3435     /*!
3436      return read-write reference to the specified sparse matrix element.
3437
3438      ref<_Tp>(i0,...[,hashval]) is equivalent to *(_Tp*)ptr(i0,...,true[,hashval]).
3439      The methods always return a valid reference.
3440      If the element did not exist, it is created and initialiazed with 0.
3441     */
3442     //! returns reference to the specified element (1D case)
3443     template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0);
3444     //! returns reference to the specified element (2D case)
3445     template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0);
3446     //! returns reference to the specified element (3D case)
3447     template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
3448     //! returns reference to the specified element (nD case)
3449     template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0);
3450     //@}
3451
3452     //@{
3453     /*!
3454      return value of the specified sparse matrix element.
3455
3456      value<_Tp>(i0,...[,hashval]) is equivalent
3457
3458      \code
3459      { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); }
3460      \endcode
3461
3462      That is, if the element did not exist, the methods return 0.
3463      */
3464     //! returns value of the specified element (1D case)
3465     template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const;
3466     //! returns value of the specified element (2D case)
3467     template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const;
3468     //! returns value of the specified element (3D case)
3469     template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0) const;
3470     //! returns value of the specified element (nD case)
3471     template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const;
3472     //@}
3473
3474     //@{
3475     /*!
3476      Return pointer to the specified sparse matrix element if it exists
3477
3478      find<_Tp>(i0,...[,hashval]) is equivalent to (_const Tp*)ptr(i0,...false[,hashval]).
3479
3480      If the specified element does not exist, the methods return NULL.
3481     */
3482     //! returns pointer to the specified element (1D case)
3483     template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const;
3484     //! returns pointer to the specified element (2D case)
3485     template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0) const;
3486     //! returns pointer to the specified element (3D case)
3487     template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const;
3488     //! returns pointer to the specified element (nD case)
3489     template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0) const;
3490
3491     //! erases the specified element (2D case)
3492     void erase(int i0, int i1, size_t* hashval=0);
3493     //! erases the specified element (3D case)
3494     void erase(int i0, int i1, int i2, size_t* hashval=0);
3495     //! erases the specified element (nD case)
3496     void erase(const int* idx, size_t* hashval=0);
3497
3498     //@{
3499     /*!
3500        return the sparse matrix iterator pointing to the first sparse matrix element
3501     */
3502     //! returns the sparse matrix iterator at the matrix beginning
3503     SparseMatIterator begin();
3504     //! returns the sparse matrix iterator at the matrix beginning
3505     template<typename _Tp> SparseMatIterator_<_Tp> begin();
3506     //! returns the read-only sparse matrix iterator at the matrix beginning
3507     SparseMatConstIterator begin() const;
3508     //! returns the read-only sparse matrix iterator at the matrix beginning
3509     template<typename _Tp> SparseMatConstIterator_<_Tp> begin() const;
3510     //@}
3511     /*!
3512        return the sparse matrix iterator pointing to the element following the last sparse matrix element
3513     */
3514     //! returns the sparse matrix iterator at the matrix end
3515     SparseMatIterator end();
3516     //! returns the read-only sparse matrix iterator at the matrix end
3517     SparseMatConstIterator end() const;
3518     //! returns the typed sparse matrix iterator at the matrix end
3519     template<typename _Tp> SparseMatIterator_<_Tp> end();
3520     //! returns the typed read-only sparse matrix iterator at the matrix end
3521     template<typename _Tp> SparseMatConstIterator_<_Tp> end() const;
3522
3523     //! returns the value stored in the sparse martix node
3524     template<typename _Tp> _Tp& value(Node* n);
3525     //! returns the value stored in the sparse martix node
3526     template<typename _Tp> const _Tp& value(const Node* n) const;
3527
3528     ////////////// some internal-use methods ///////////////
3529     Node* node(size_t nidx);
3530     const Node* node(size_t nidx) const;
3531
3532     uchar* newNode(const int* idx, size_t hashval);
3533     void removeNode(size_t hidx, size_t nidx, size_t previdx);
3534     void resizeHashTab(size_t newsize);
3535
3536     enum { MAGIC_VAL=0x42FD0000, MAX_DIM=CV_MAX_DIM, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 };
3537
3538     int flags;
3539     Hdr* hdr;
3540 };
3541
3542 //! finds global minimum and maximum sparse array elements and returns their values and their locations
3543 CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal,
3544                           double* maxVal, int* minIdx=0, int* maxIdx=0);
3545 //! computes norm of a sparse matrix
3546 CV_EXPORTS double norm( const SparseMat& src, int normType );
3547 //! 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
3548 CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType );
3549
3550 /*!
3551  Read-Only Sparse Matrix Iterator.
3552  Here is how to use the iterator to compute the sum of floating-point sparse matrix elements:
3553
3554  \code
3555  SparseMatConstIterator it = m.begin(), it_end = m.end();
3556  double s = 0;
3557  CV_Assert( m.type() == CV_32F );
3558  for( ; it != it_end; ++it )
3559     s += it.value<float>();
3560  \endcode
3561 */
3562 class CV_EXPORTS SparseMatConstIterator
3563 {
3564 public:
3565     //! the default constructor
3566     SparseMatConstIterator();
3567     //! the full constructor setting the iterator to the first sparse matrix element
3568     SparseMatConstIterator(const SparseMat* _m);
3569     //! the copy constructor
3570     SparseMatConstIterator(const SparseMatConstIterator& it);
3571
3572     //! the assignment operator
3573     SparseMatConstIterator& operator = (const SparseMatConstIterator& it);
3574
3575     //! template method returning the current matrix element
3576     template<typename _Tp> const _Tp& value() const;
3577     //! returns the current node of the sparse matrix. it.node->idx is the current element index
3578     const SparseMat::Node* node() const;
3579
3580     //! moves iterator to the previous element
3581     SparseMatConstIterator& operator --();
3582     //! moves iterator to the previous element
3583     SparseMatConstIterator operator --(int);
3584     //! moves iterator to the next element
3585     SparseMatConstIterator& operator ++();
3586     //! moves iterator to the next element
3587     SparseMatConstIterator operator ++(int);
3588
3589     //! moves iterator to the element after the last element
3590     void seekEnd();
3591
3592     const SparseMat* m;
3593     size_t hashidx;
3594     uchar* ptr;
3595 };
3596
3597 /*!
3598  Read-write Sparse Matrix Iterator
3599
3600  The class is similar to cv::SparseMatConstIterator,
3601  but can be used for in-place modification of the matrix elements.
3602 */
3603 class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator
3604 {
3605 public:
3606     //! the default constructor
3607     SparseMatIterator();
3608     //! the full constructor setting the iterator to the first sparse matrix element
3609     SparseMatIterator(SparseMat* _m);
3610     //! the full constructor setting the iterator to the specified sparse matrix element
3611     SparseMatIterator(SparseMat* _m, const int* idx);
3612     //! the copy constructor
3613     SparseMatIterator(const SparseMatIterator& it);
3614
3615     //! the assignment operator
3616     SparseMatIterator& operator = (const SparseMatIterator& it);
3617     //! returns read-write reference to the current sparse matrix element
3618     template<typename _Tp> _Tp& value() const;
3619     //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!)
3620     SparseMat::Node* node() const;
3621
3622     //! moves iterator to the next element
3623     SparseMatIterator& operator ++();
3624     //! moves iterator to the next element
3625     SparseMatIterator operator ++(int);
3626 };
3627
3628 /*!
3629  The Template Sparse Matrix class derived from cv::SparseMat
3630
3631  The class provides slightly more convenient operations for accessing elements.
3632
3633  \code
3634  SparseMat m;
3635  ...
3636  SparseMat_<int> m_ = (SparseMat_<int>&)m;
3637  m_.ref(1)++; // equivalent to m.ref<int>(1)++;
3638  m_.ref(2) += m_(3); // equivalent to m.ref<int>(2) += m.value<int>(3);
3639  \endcode
3640 */
3641 template<typename _Tp> class CV_EXPORTS SparseMat_ : public SparseMat
3642 {
3643 public:
3644     typedef SparseMatIterator_<_Tp> iterator;
3645     typedef SparseMatConstIterator_<_Tp> const_iterator;
3646
3647     //! the default constructor
3648     SparseMat_();
3649     //! the full constructor equivelent to SparseMat(dims, _sizes, DataType<_Tp>::type)
3650     SparseMat_(int dims, const int* _sizes);
3651     //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted
3652     SparseMat_(const SparseMat& m);
3653     //! the copy constructor. This is O(1) operation - no data is copied
3654     SparseMat_(const SparseMat_& m);
3655     //! converts dense matrix to the sparse form
3656     SparseMat_(const Mat& m);
3657     //! converts the old-style sparse matrix to the C++ class. All the elements are copied
3658     SparseMat_(const CvSparseMat* m);
3659     //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted
3660     SparseMat_& operator = (const SparseMat& m);
3661     //! the assignment operator. This is O(1) operation - no data is copied
3662     SparseMat_& operator = (const SparseMat_& m);
3663     //! converts dense matrix to the sparse form
3664     SparseMat_& operator = (const Mat& m);
3665
3666     //! makes full copy of the matrix. All the elements are duplicated
3667     SparseMat_ clone() const;
3668     //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type)
3669     void create(int dims, const int* _sizes);
3670     //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied
3671     operator CvSparseMat*() const;
3672
3673     //! returns type of the matrix elements
3674     int type() const;
3675     //! returns depth of the matrix elements
3676     int depth() const;
3677     //! returns the number of channels in each matrix element
3678     int channels() const;
3679
3680     //! equivalent to SparseMat::ref<_Tp>(i0, hashval)
3681     _Tp& ref(int i0, size_t* hashval=0);
3682     //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval)
3683     _Tp& ref(int i0, int i1, size_t* hashval=0);
3684     //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval)
3685     _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
3686     //! equivalent to SparseMat::ref<_Tp>(idx, hashval)
3687     _Tp& ref(const int* idx, size_t* hashval=0);
3688
3689     //! equivalent to SparseMat::value<_Tp>(i0, hashval)
3690     _Tp operator()(int i0, size_t* hashval=0) const;
3691     //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval)
3692     _Tp operator()(int i0, int i1, size_t* hashval=0) const;
3693     //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval)
3694     _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const;
3695     //! equivalent to SparseMat::value<_Tp>(idx, hashval)
3696     _Tp operator()(const int* idx, size_t* hashval=0) const;
3697
3698     //! returns sparse matrix iterator pointing to the first sparse matrix element
3699     SparseMatIterator_<_Tp> begin();
3700     //! returns read-only sparse matrix iterator pointing to the first sparse matrix element
3701     SparseMatConstIterator_<_Tp> begin() const;
3702     //! returns sparse matrix iterator pointing to the element following the last sparse matrix element
3703     SparseMatIterator_<_Tp> end();
3704     //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element
3705     SparseMatConstIterator_<_Tp> end() const;
3706 };
3707
3708
3709 /*!
3710  Template Read-Only Sparse Matrix Iterator Class.
3711
3712  This is the derived from SparseMatConstIterator class that
3713  introduces more convenient operator *() for accessing the current element.
3714 */
3715 template<typename _Tp> class CV_EXPORTS SparseMatConstIterator_ : public SparseMatConstIterator
3716 {
3717 public:
3718     typedef std::forward_iterator_tag iterator_category;
3719
3720     //! the default constructor
3721     SparseMatConstIterator_();
3722     //! the full constructor setting the iterator to the first sparse matrix element
3723     SparseMatConstIterator_(const SparseMat_<_Tp>* _m);
3724     //! the copy constructor
3725     SparseMatConstIterator_(const SparseMatConstIterator_& it);
3726
3727     //! the assignment operator
3728     SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it);
3729     //! the element access operator
3730     const _Tp& operator *() const;
3731
3732     //! moves iterator to the next element
3733     SparseMatConstIterator_& operator ++();
3734     //! moves iterator to the next element
3735     SparseMatConstIterator_ operator ++(int);
3736 };
3737
3738 /*!
3739  Template Read-Write Sparse Matrix Iterator Class.
3740
3741  This is the derived from cv::SparseMatConstIterator_ class that
3742  introduces more convenient operator *() for accessing the current element.
3743 */
3744 template<typename _Tp> class CV_EXPORTS SparseMatIterator_ : public SparseMatConstIterator_<_Tp>
3745 {
3746 public:
3747     typedef std::forward_iterator_tag iterator_category;
3748
3749     //! the default constructor
3750     SparseMatIterator_();
3751     //! the full constructor setting the iterator to the first sparse matrix element
3752     SparseMatIterator_(SparseMat_<_Tp>* _m);
3753     //! the copy constructor
3754     SparseMatIterator_(const SparseMatIterator_& it);
3755
3756     //! the assignment operator
3757     SparseMatIterator_& operator = (const SparseMatIterator_& it);
3758     //! returns the reference to the current element
3759     _Tp& operator *() const;
3760
3761     //! moves the iterator to the next element
3762     SparseMatIterator_& operator ++();
3763     //! moves the iterator to the next element
3764     SparseMatIterator_ operator ++(int);
3765 };
3766
3767 //////////////////// Fast Nearest-Neighbor Search Structure ////////////////////
3768
3769 /*!
3770  Fast Nearest Neighbor Search Class.
3771
3772  The class implements D. Lowe BBF (Best-Bin-First) algorithm for the last
3773  approximate (or accurate) nearest neighbor search in multi-dimensional spaces.
3774
3775  First, a set of vectors is passed to KDTree::KDTree() constructor
3776  or KDTree::build() method, where it is reordered.
3777
3778  Then arbitrary vectors can be passed to KDTree::findNearest() methods, which
3779  find the K nearest neighbors among the vectors from the initial set.
3780  The user can balance between the speed and accuracy of the search by varying Emax
3781  parameter, which is the number of leaves that the algorithm checks.
3782  The larger parameter values yield more accurate results at the expense of lower processing speed.
3783
3784  \code
3785  KDTree T(points, false);
3786  const int K = 3, Emax = INT_MAX;
3787  int idx[K];
3788  float dist[K];
3789  T.findNearest(query_vec, K, Emax, idx, 0, dist);
3790  CV_Assert(dist[0] <= dist[1] && dist[1] <= dist[2]);
3791  \endcode
3792 */
3793 class CV_EXPORTS_W KDTree
3794 {
3795 public:
3796     /*!
3797         The node of the search tree.
3798     */
3799     struct Node
3800     {
3801         Node() : idx(-1), left(-1), right(-1), boundary(0.f) {}
3802         Node(int _idx, int _left, int _right, float _boundary)
3803             : idx(_idx), left(_left), right(_right), boundary(_boundary) {}
3804         //! split dimension; >=0 for nodes (dim), < 0 for leaves (index of the point)
3805         int idx;
3806         //! node indices of the left and the right branches
3807         int left, right;
3808         //! go to the left if query_vec[node.idx]<=node.boundary, otherwise go to the right
3809         float boundary;
3810     };
3811
3812     //! the default constructor
3813     CV_WRAP KDTree();
3814     //! the full constructor that builds the search tree
3815     CV_WRAP KDTree(InputArray points, bool copyAndReorderPoints=false);
3816     //! the full constructor that builds the search tree
3817     CV_WRAP KDTree(InputArray points, InputArray _labels,
3818                    bool copyAndReorderPoints=false);
3819     //! builds the search tree
3820     CV_WRAP void build(InputArray points, bool copyAndReorderPoints=false);
3821     //! builds the search tree
3822     CV_WRAP void build(InputArray points, InputArray labels,
3823                        bool copyAndReorderPoints=false);
3824     //! finds the K nearest neighbors of "vec" while looking at Emax (at most) leaves
3825     CV_WRAP int findNearest(InputArray vec, int K, int Emax,
3826                             OutputArray neighborsIdx,
3827                             OutputArray neighbors=noArray(),
3828                             OutputArray dist=noArray(),
3829                             OutputArray labels=noArray()) const;
3830     //! finds all the points from the initial set that belong to the specified box
3831     CV_WRAP void findOrthoRange(InputArray minBounds,
3832                                 InputArray maxBounds,
3833                                 OutputArray neighborsIdx,
3834                                 OutputArray neighbors=noArray(),
3835                                 OutputArray labels=noArray()) const;
3836     //! returns vectors with the specified indices
3837     CV_WRAP void getPoints(InputArray idx, OutputArray pts,
3838                            OutputArray labels=noArray()) const;
3839     //! return a vector with the specified index
3840     const float* getPoint(int ptidx, int* label=0) const;
3841     //! returns the search space dimensionality
3842     CV_WRAP int dims() const;
3843
3844     vector<Node> nodes; //!< all the tree nodes
3845     CV_PROP Mat points; //!< all the points. It can be a reordered copy of the input vector set or the original vector set.
3846     CV_PROP vector<int> labels; //!< the parallel array of labels.
3847     CV_PROP int maxDepth; //!< maximum depth of the search tree. Do not modify it
3848     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
3849 };
3850
3851 //////////////////////////////////////// XML & YAML I/O ////////////////////////////////////
3852
3853 class CV_EXPORTS FileNode;
3854
3855 /*!
3856  XML/YAML File Storage Class.
3857
3858  The class describes an object associated with XML or YAML file.
3859  It can be used to store data to such a file or read and decode the data.
3860
3861  The storage is organized as a tree of nested sequences (or lists) and mappings.
3862  Sequence is a heterogenious array, which elements are accessed by indices or sequentially using an iterator.
3863  Mapping is analogue of std::map or C structure, which elements are accessed by names.
3864  The most top level structure is a mapping.
3865  Leaves of the file storage tree are integers, floating-point numbers and text strings.
3866
3867  For example, the following code:
3868
3869  \code
3870  // open file storage for writing. Type of the file is determined from the extension
3871  FileStorage fs("test.yml", FileStorage::WRITE);
3872  fs << "test_int" << 5 << "test_real" << 3.1 << "test_string" << "ABCDEFGH";
3873  fs << "test_mat" << Mat::eye(3,3,CV_32F);
3874
3875  fs << "test_list" << "[" << 0.0000000000001 << 2 << CV_PI << -3435345 << "2-502 2-029 3egegeg" <<
3876  "{:" << "month" << 12 << "day" << 31 << "year" << 1969 << "}" << "]";
3877  fs << "test_map" << "{" << "x" << 1 << "y" << 2 << "width" << 100 << "height" << 200 << "lbp" << "[:";
3878
3879  const uchar arr[] = {0, 1, 1, 0, 1, 1, 0, 1};
3880  fs.writeRaw("u", arr, (int)(sizeof(arr)/sizeof(arr[0])));
3881
3882  fs << "]" << "}";
3883  \endcode
3884
3885  will produce the following file:
3886
3887  \verbatim
3888  %YAML:1.0
3889  test_int: 5
3890  test_real: 3.1000000000000001e+00
3891  test_string: ABCDEFGH
3892  test_mat: !!opencv-matrix
3893      rows: 3
3894      cols: 3
3895      dt: f
3896      data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1. ]
3897  test_list:
3898      - 1.0000000000000000e-13
3899      - 2
3900      - 3.1415926535897931e+00
3901      - -3435345
3902      - "2-502 2-029 3egegeg"
3903      - { month:12, day:31, year:1969 }
3904  test_map:
3905      x: 1
3906      y: 2
3907      width: 100
3908      height: 200
3909      lbp: [ 0, 1, 1, 0, 1, 1, 0, 1 ]
3910  \endverbatim
3911
3912  and to read the file above, the following code can be used:
3913
3914  \code
3915  // open file storage for reading.
3916  // Type of the file is determined from the content, not the extension
3917  FileStorage fs("test.yml", FileStorage::READ);
3918  int test_int = (int)fs["test_int"];
3919  double test_real = (double)fs["test_real"];
3920  string test_string = (string)fs["test_string"];
3921
3922  Mat M;
3923  fs["test_mat"] >> M;
3924
3925  FileNode tl = fs["test_list"];
3926  CV_Assert(tl.type() == FileNode::SEQ && tl.size() == 6);
3927  double tl0 = (double)tl[0];
3928  int tl1 = (int)tl[1];
3929  double tl2 = (double)tl[2];
3930  int tl3 = (int)tl[3];
3931  string tl4 = (string)tl[4];
3932  CV_Assert(tl[5].type() == FileNode::MAP && tl[5].size() == 3);
3933
3934  int month = (int)tl[5]["month"];
3935  int day = (int)tl[5]["day"];
3936  int year = (int)tl[5]["year"];
3937
3938  FileNode tm = fs["test_map"];
3939
3940  int x = (int)tm["x"];
3941  int y = (int)tm["y"];
3942  int width = (int)tm["width"];
3943  int height = (int)tm["height"];
3944
3945  int lbp_val = 0;
3946  FileNodeIterator it = tm["lbp"].begin();
3947
3948  for(int k = 0; k < 8; k++, ++it)
3949     lbp_val |= ((int)*it) << k;
3950  \endcode
3951 */
3952 class CV_EXPORTS_W FileStorage
3953 {
3954 public:
3955     //! file storage mode
3956     enum
3957     {
3958         READ=0, //! read mode
3959         WRITE=1, //! write mode
3960         APPEND=2, //! append mode
3961         MEMORY=4,
3962         FORMAT_MASK=(7<<3),
3963         FORMAT_AUTO=0,
3964         FORMAT_XML=(1<<3),
3965         FORMAT_YAML=(2<<3)
3966     };
3967     enum
3968     {
3969         UNDEFINED=0,
3970         VALUE_EXPECTED=1,
3971         NAME_EXPECTED=2,
3972         INSIDE_MAP=4
3973     };
3974     //! the default constructor
3975     CV_WRAP FileStorage();
3976     //! the full constructor that opens file storage for reading or writing
3977     CV_WRAP FileStorage(const string& source, int flags, const string& encoding=string());
3978     //! the constructor that takes pointer to the C FileStorage structure
3979     FileStorage(CvFileStorage* fs);
3980     //! the destructor. calls release()
3981     virtual ~FileStorage();
3982
3983     //! opens file storage for reading or writing. The previous storage is closed with release()
3984     CV_WRAP virtual bool open(const string& filename, int flags, const string& encoding=string());
3985     //! returns true if the object is associated with currently opened file.
3986     CV_WRAP virtual bool isOpened() const;
3987     //! closes the file and releases all the memory buffers
3988     CV_WRAP virtual void release();
3989     //! closes the file, releases all the memory buffers and returns the text string
3990     CV_WRAP virtual string releaseAndGetString();
3991
3992     //! returns the first element of the top-level mapping
3993     CV_WRAP FileNode getFirstTopLevelNode() const;
3994     //! returns the top-level mapping. YAML supports multiple streams
3995     CV_WRAP FileNode root(int streamidx=0) const;
3996     //! returns the specified element of the top-level mapping
3997     FileNode operator[](const string& nodename) const;
3998     //! returns the specified element of the top-level mapping
3999     CV_WRAP FileNode operator[](const char* nodename) const;
4000
4001     //! returns pointer to the underlying C FileStorage structure
4002     CvFileStorage* operator *() { return fs; }
4003     //! returns pointer to the underlying C FileStorage structure
4004     const CvFileStorage* operator *() const { return fs; }
4005     //! writes one or more numbers of the specified format to the currently written structure
4006     void writeRaw( const string& fmt, const uchar* vec, size_t len );
4007     //! writes the registered C structure (CvMat, CvMatND, CvSeq). See cvWrite()
4008     void writeObj( const string& name, const void* obj );
4009
4010     //! returns the normalized object name for the specified file name
4011     static string getDefaultObjectName(const string& filename);
4012
4013     Ptr<CvFileStorage> fs; //!< the underlying C FileStorage structure
4014     string elname; //!< the currently written element
4015     vector<char> structs; //!< the stack of written structures
4016     int state; //!< the writer state
4017 };
4018
4019 class CV_EXPORTS FileNodeIterator;
4020
4021 /*!
4022  File Storage Node class
4023
4024  The node is used to store each and every element of the file storage opened for reading -
4025  from the primitive objects, such as numbers and text strings, to the complex nodes:
4026  sequences, mappings and the registered objects.
4027
4028  Note that file nodes are only used for navigating file storages opened for reading.
4029  When a file storage is opened for writing, no data is stored in memory after it is written.
4030 */
4031 class CV_EXPORTS_W_SIMPLE FileNode
4032 {
4033 public:
4034     //! type of the file storage node
4035     enum
4036     {
4037         NONE=0, //!< empty node
4038         INT=1, //!< an integer
4039         REAL=2, //!< floating-point number
4040         FLOAT=REAL, //!< synonym or REAL
4041         STR=3, //!< text string in UTF-8 encoding
4042         STRING=STR, //!< synonym for STR
4043         REF=4, //!< integer of size size_t. Typically used for storing complex dynamic structures where some elements reference the others
4044         SEQ=5, //!< sequence
4045         MAP=6, //!< mapping
4046         TYPE_MASK=7,
4047         FLOW=8, //!< compact representation of a sequence or mapping. Used only by YAML writer
4048         USER=16, //!< a registered object (e.g. a matrix)
4049         EMPTY=32, //!< empty structure (sequence or mapping)
4050         NAMED=64 //!< the node has a name (i.e. it is element of a mapping)
4051     };
4052     //! the default constructor
4053     CV_WRAP FileNode();
4054     //! the full constructor wrapping CvFileNode structure.
4055     FileNode(const CvFileStorage* fs, const CvFileNode* node);
4056     //! the copy constructor
4057     FileNode(const FileNode& node);
4058     //! returns element of a mapping node
4059     FileNode operator[](const string& nodename) const;
4060     //! returns element of a mapping node
4061     CV_WRAP FileNode operator[](const char* nodename) const;
4062     //! returns element of a sequence node
4063     CV_WRAP FileNode operator[](int i) const;
4064     //! returns type of the node
4065     CV_WRAP int type() const;
4066
4067     //! returns true if the node is empty
4068     CV_WRAP bool empty() const;
4069     //! returns true if the node is a "none" object
4070     CV_WRAP bool isNone() const;
4071     //! returns true if the node is a sequence
4072     CV_WRAP bool isSeq() const;
4073     //! returns true if the node is a mapping
4074     CV_WRAP bool isMap() const;
4075     //! returns true if the node is an integer
4076     CV_WRAP bool isInt() const;
4077     //! returns true if the node is a floating-point number
4078     CV_WRAP bool isReal() const;
4079     //! returns true if the node is a text string
4080     CV_WRAP bool isString() const;
4081     //! returns true if the node has a name
4082     CV_WRAP bool isNamed() const;
4083     //! returns the node name or an empty string if the node is nameless
4084     CV_WRAP string name() const;
4085     //! returns the number of elements in the node, if it is a sequence or mapping, or 1 otherwise.
4086     CV_WRAP size_t size() const;
4087     //! returns the node content as an integer. If the node stores floating-point number, it is rounded.
4088     operator int() const;
4089     //! returns the node content as float
4090     operator float() const;
4091     //! returns the node content as double
4092     operator double() const;
4093     //! returns the node content as text string
4094     operator string() const;
4095
4096     //! returns pointer to the underlying file node
4097     CvFileNode* operator *();
4098     //! returns pointer to the underlying file node
4099     const CvFileNode* operator* () const;
4100
4101     //! returns iterator pointing to the first node element
4102     FileNodeIterator begin() const;
4103     //! returns iterator pointing to the element following the last node element
4104     FileNodeIterator end() const;
4105
4106     //! reads node elements to the buffer with the specified format
4107     void readRaw( const string& fmt, uchar* vec, size_t len ) const;
4108     //! reads the registered object and returns pointer to it
4109     void* readObj() const;
4110
4111     // do not use wrapper pointer classes for better efficiency
4112     const CvFileStorage* fs;
4113     const CvFileNode* node;
4114 };
4115
4116
4117 /*!
4118  File Node Iterator
4119
4120  The class is used for iterating sequences (usually) and mappings.
4121  */
4122 class CV_EXPORTS FileNodeIterator
4123 {
4124 public:
4125     //! the default constructor
4126     FileNodeIterator();
4127     //! the full constructor set to the ofs-th element of the node
4128     FileNodeIterator(const CvFileStorage* fs, const CvFileNode* node, size_t ofs=0);
4129     //! the copy constructor
4130     FileNodeIterator(const FileNodeIterator& it);
4131     //! returns the currently observed element
4132     FileNode operator *() const;
4133     //! accesses the currently observed element methods
4134     FileNode operator ->() const;
4135
4136     //! moves iterator to the next node
4137     FileNodeIterator& operator ++ ();
4138     //! moves iterator to the next node
4139     FileNodeIterator operator ++ (int);
4140     //! moves iterator to the previous node
4141     FileNodeIterator& operator -- ();
4142     //! moves iterator to the previous node
4143     FileNodeIterator operator -- (int);
4144     //! moves iterator forward by the specified offset (possibly negative)
4145     FileNodeIterator& operator += (int ofs);
4146     //! moves iterator backward by the specified offset (possibly negative)
4147     FileNodeIterator& operator -= (int ofs);
4148
4149     //! reads the next maxCount elements (or less, if the sequence/mapping last element occurs earlier) to the buffer with the specified format
4150     FileNodeIterator& readRaw( const string& fmt, uchar* vec,
4151                                size_t maxCount=(size_t)INT_MAX );
4152
4153     const CvFileStorage* fs;
4154     const CvFileNode* container;
4155     CvSeqReader reader;
4156     size_t remaining;
4157 };
4158
4159 ////////////// convenient wrappers for operating old-style dynamic structures //////////////
4160
4161 template<typename _Tp> class SeqIterator;
4162
4163 typedef Ptr<CvMemStorage> MemStorage;
4164
4165 /*!
4166  Template Sequence Class derived from CvSeq
4167
4168  The class provides more convenient access to sequence elements,
4169  STL-style operations and iterators.
4170
4171  \note The class is targeted for simple data types,
4172     i.e. no constructors or destructors
4173     are called for the sequence elements.
4174 */
4175 template<typename _Tp> class CV_EXPORTS Seq
4176 {
4177 public:
4178     typedef SeqIterator<_Tp> iterator;
4179     typedef SeqIterator<_Tp> const_iterator;
4180
4181     //! the default constructor
4182     Seq();
4183     //! the constructor for wrapping CvSeq structure. The real element type in CvSeq should match _Tp.
4184     Seq(const CvSeq* seq);
4185     //! creates the empty sequence that resides in the specified storage
4186     Seq(MemStorage& storage, int headerSize = sizeof(CvSeq));
4187     //! returns read-write reference to the specified element
4188     _Tp& operator [](int idx);
4189     //! returns read-only reference to the specified element
4190     const _Tp& operator[](int idx) const;
4191     //! returns iterator pointing to the beginning of the sequence
4192     SeqIterator<_Tp> begin() const;
4193     //! returns iterator pointing to the element following the last sequence element
4194     SeqIterator<_Tp> end() const;
4195     //! returns the number of elements in the sequence
4196     size_t size() const;
4197     //! returns the type of sequence elements (CV_8UC1 ... CV_64FC(CV_CN_MAX) ...)
4198     int type() const;
4199     //! returns the depth of sequence elements (CV_8U ... CV_64F)
4200     int depth() const;
4201     //! returns the number of channels in each sequence element
4202     int channels() const;
4203     //! returns the size of each sequence element
4204     size_t elemSize() const;
4205     //! returns index of the specified sequence element
4206     size_t index(const _Tp& elem) const;
4207     //! appends the specified element to the end of the sequence
4208     void push_back(const _Tp& elem);
4209     //! appends the specified element to the front of the sequence
4210     void push_front(const _Tp& elem);
4211     //! appends zero or more elements to the end of the sequence
4212     void push_back(const _Tp* elems, size_t count);
4213     //! appends zero or more elements to the front of the sequence
4214     void push_front(const _Tp* elems, size_t count);
4215     //! inserts the specified element to the specified position
4216     void insert(int idx, const _Tp& elem);
4217     //! inserts zero or more elements to the specified position
4218     void insert(int idx, const _Tp* elems, size_t count);
4219     //! removes element at the specified position
4220     void remove(int idx);
4221     //! removes the specified subsequence
4222     void remove(const Range& r);
4223
4224     //! returns reference to the first sequence element
4225     _Tp& front();
4226     //! returns read-only reference to the first sequence element
4227     const _Tp& front() const;
4228     //! returns reference to the last sequence element
4229     _Tp& back();
4230     //! returns read-only reference to the last sequence element
4231     const _Tp& back() const;
4232     //! returns true iff the sequence contains no elements
4233     bool empty() const;
4234
4235     //! removes all the elements from the sequence
4236     void clear();
4237     //! removes the first element from the sequence
4238     void pop_front();
4239     //! removes the last element from the sequence
4240     void pop_back();
4241     //! removes zero or more elements from the beginning of the sequence
4242     void pop_front(_Tp* elems, size_t count);
4243     //! removes zero or more elements from the end of the sequence
4244     void pop_back(_Tp* elems, size_t count);
4245
4246     //! copies the whole sequence or the sequence slice to the specified vector
4247     void copyTo(vector<_Tp>& vec, const Range& range=Range::all()) const;
4248     //! returns the vector containing all the sequence elements
4249     operator vector<_Tp>() const;
4250
4251     CvSeq* seq;
4252 };
4253
4254
4255 /*!
4256  STL-style Sequence Iterator inherited from the CvSeqReader structure
4257 */
4258 template<typename _Tp> class CV_EXPORTS SeqIterator : public CvSeqReader
4259 {
4260 public:
4261     //! the default constructor
4262     SeqIterator();
4263     //! the constructor setting the iterator to the beginning or to the end of the sequence
4264     SeqIterator(const Seq<_Tp>& seq, bool seekEnd=false);
4265     //! positions the iterator within the sequence
4266     void seek(size_t pos);
4267     //! reports the current iterator position
4268     size_t tell() const;
4269     //! returns reference to the current sequence element
4270     _Tp& operator *();
4271     //! returns read-only reference to the current sequence element
4272     const _Tp& operator *() const;
4273     //! moves iterator to the next sequence element
4274     SeqIterator& operator ++();
4275     //! moves iterator to the next sequence element
4276     SeqIterator operator ++(int) const;
4277     //! moves iterator to the previous sequence element
4278     SeqIterator& operator --();
4279     //! moves iterator to the previous sequence element
4280     SeqIterator operator --(int) const;
4281
4282     //! moves iterator forward by the specified offset (possibly negative)
4283     SeqIterator& operator +=(int);
4284     //! moves iterator backward by the specified offset (possibly negative)
4285     SeqIterator& operator -=(int);
4286
4287     // this is index of the current element module seq->total*2
4288     // (to distinguish between 0 and seq->total)
4289     int index;
4290 };
4291
4292
4293 class CV_EXPORTS Algorithm;
4294 class CV_EXPORTS AlgorithmInfo;
4295 struct CV_EXPORTS AlgorithmInfoData;
4296
4297 template<typename _Tp> struct ParamType {};
4298
4299 /*!
4300   Base class for high-level OpenCV algorithms
4301 */
4302 class CV_EXPORTS_W Algorithm
4303 {
4304 public:
4305     Algorithm();
4306     virtual ~Algorithm();
4307     string name() const;
4308
4309     template<typename _Tp> typename ParamType<_Tp>::member_type get(const string& name) const;
4310     template<typename _Tp> typename ParamType<_Tp>::member_type get(const char* name) const;
4311
4312     CV_WRAP int getInt(const string& name) const;
4313     CV_WRAP double getDouble(const string& name) const;
4314     CV_WRAP bool getBool(const string& name) const;
4315     CV_WRAP string getString(const string& name) const;
4316     CV_WRAP Mat getMat(const string& name) const;
4317     CV_WRAP vector<Mat> getMatVector(const string& name) const;
4318     CV_WRAP Ptr<Algorithm> getAlgorithm(const string& name) const;
4319
4320     CV_WRAP_AS(setInt) void set(const string& name, int value);
4321     CV_WRAP_AS(setDouble) void set(const string& name, double value);
4322     CV_WRAP_AS(setBool) void set(const string& name, bool value);
4323     CV_WRAP_AS(setString) void set(const string& name, const string& value);
4324     CV_WRAP_AS(setMat) void set(const string& name, const Mat& value);
4325     CV_WRAP_AS(setMatVector) void set(const string& name, const vector<Mat>& value);
4326     CV_WRAP_AS(setAlgorithm) void set(const string& name, const Ptr<Algorithm>& value);
4327     template<typename _Tp> void set(const string& name, const Ptr<_Tp>& value);
4328
4329     void set(const char* name, int value);
4330     void set(const char* name, double value);
4331     void set(const char* name, bool value);
4332     void set(const char* name, const string& value);
4333     void set(const char* name, const Mat& value);
4334     void set(const char* name, const vector<Mat>& value);
4335     void set(const char* name, const Ptr<Algorithm>& value);
4336     template<typename _Tp> void set(const char* name, const Ptr<_Tp>& value);
4337
4338     CV_WRAP string paramHelp(const string& name) const;
4339     int paramType(const char* name) const;
4340     CV_WRAP int paramType(const string& name) const;
4341     CV_WRAP void getParams(CV_OUT vector<string>& names) const;
4342
4343
4344     virtual void write(FileStorage& fs) const;
4345     virtual void read(const FileNode& fn);
4346
4347     typedef Algorithm* (*Constructor)(void);
4348     typedef int (Algorithm::*Getter)() const;
4349     typedef void (Algorithm::*Setter)(int);
4350
4351     CV_WRAP static void getList(CV_OUT vector<string>& algorithms);
4352     CV_WRAP static Ptr<Algorithm> _create(const string& name);
4353     template<typename _Tp> static Ptr<_Tp> create(const string& name);
4354
4355     virtual AlgorithmInfo* info() const /* TODO: make it = 0;*/ { return 0; }
4356 };
4357
4358
4359 class CV_EXPORTS AlgorithmInfo
4360 {
4361 public:
4362     friend class Algorithm;
4363     AlgorithmInfo(const string& name, Algorithm::Constructor create);
4364     ~AlgorithmInfo();
4365     void get(const Algorithm* algo, const char* name, int argType, void* value) const;
4366     void addParam_(Algorithm& algo, const char* name, int argType,
4367                    void* value, bool readOnly,
4368                    Algorithm::Getter getter, Algorithm::Setter setter,
4369                    const string& help=string());
4370     string paramHelp(const char* name) const;
4371     int paramType(const char* name) const;
4372     void getParams(vector<string>& names) const;
4373
4374     void write(const Algorithm* algo, FileStorage& fs) const;
4375     void read(Algorithm* algo, const FileNode& fn) const;
4376     string name() const;
4377
4378     void addParam(Algorithm& algo, const char* name,
4379                   int& value, bool readOnly=false,
4380                   int (Algorithm::*getter)()=0,
4381                   void (Algorithm::*setter)(int)=0,
4382                   const string& help=string());
4383     void addParam(Algorithm& algo, const char* name,
4384                   bool& value, bool readOnly=false,
4385                   int (Algorithm::*getter)()=0,
4386                   void (Algorithm::*setter)(int)=0,
4387                   const string& help=string());
4388     void addParam(Algorithm& algo, const char* name,
4389                   double& value, bool readOnly=false,
4390                   double (Algorithm::*getter)()=0,
4391                   void (Algorithm::*setter)(double)=0,
4392                   const string& help=string());
4393     void addParam(Algorithm& algo, const char* name,
4394                   string& value, bool readOnly=false,
4395                   string (Algorithm::*getter)()=0,
4396                   void (Algorithm::*setter)(const string&)=0,
4397                   const string& help=string());
4398     void addParam(Algorithm& algo, const char* name,
4399                   Mat& value, bool readOnly=false,
4400                   Mat (Algorithm::*getter)()=0,
4401                   void (Algorithm::*setter)(const Mat&)=0,
4402                   const string& help=string());
4403     void addParam(Algorithm& algo, const char* name,
4404                   vector<Mat>& value, bool readOnly=false,
4405                   vector<Mat> (Algorithm::*getter)()=0,
4406                   void (Algorithm::*setter)(const vector<Mat>&)=0,
4407                   const string& help=string());
4408     void addParam(Algorithm& algo, const char* name,
4409                   Ptr<Algorithm>& value, bool readOnly=false,
4410                   Ptr<Algorithm> (Algorithm::*getter)()=0,
4411                   void (Algorithm::*setter)(const Ptr<Algorithm>&)=0,
4412                   const string& help=string());
4413     template<typename _Tp, typename _Base> void addParam(Algorithm& algo, const char* name,
4414                   Ptr<_Tp>& value, bool readOnly=false,
4415                   Ptr<_Tp> (Algorithm::*getter)()=0,
4416                   void (Algorithm::*setter)(const Ptr<_Tp>&)=0,
4417                   const string& help=string());
4418     template<typename _Tp> void addParam(Algorithm& algo, const char* name,
4419                   Ptr<_Tp>& value, bool readOnly=false,
4420                   Ptr<_Tp> (Algorithm::*getter)()=0,
4421                   void (Algorithm::*setter)(const Ptr<_Tp>&)=0,
4422                   const string& help=string());
4423 protected:
4424     AlgorithmInfoData* data;
4425     void set(Algorithm* algo, const char* name, int argType,
4426               const void* value, bool force=false) const;
4427 };
4428
4429
4430 struct CV_EXPORTS Param
4431 {
4432     enum { INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6 };
4433
4434     Param();
4435     Param(int _type, bool _readonly, int _offset,
4436           Algorithm::Getter _getter=0,
4437           Algorithm::Setter _setter=0,
4438           const string& _help=string());
4439     int type;
4440     int offset;
4441     bool readonly;
4442     Algorithm::Getter getter;
4443     Algorithm::Setter setter;
4444     string help;
4445 };
4446
4447 template<> struct ParamType<bool>
4448 {
4449     typedef bool const_param_type;
4450     typedef bool member_type;
4451
4452     enum { type = Param::BOOLEAN };
4453 };
4454
4455 template<> struct ParamType<int>
4456 {
4457     typedef int const_param_type;
4458     typedef int member_type;
4459
4460     enum { type = Param::INT };
4461 };
4462
4463 template<> struct ParamType<double>
4464 {
4465     typedef double const_param_type;
4466     typedef double member_type;
4467
4468     enum { type = Param::REAL };
4469 };
4470
4471 template<> struct ParamType<string>
4472 {
4473     typedef const string& const_param_type;
4474     typedef string member_type;
4475
4476     enum { type = Param::STRING };
4477 };
4478
4479 template<> struct ParamType<Mat>
4480 {
4481     typedef const Mat& const_param_type;
4482     typedef Mat member_type;
4483
4484     enum { type = Param::MAT };
4485 };
4486
4487 template<> struct ParamType<vector<Mat> >
4488 {
4489     typedef const vector<Mat>& const_param_type;
4490     typedef vector<Mat> member_type;
4491
4492     enum { type = Param::MAT_VECTOR };
4493 };
4494
4495 template<> struct ParamType<Algorithm>
4496 {
4497     typedef const Ptr<Algorithm>& const_param_type;
4498     typedef Ptr<Algorithm> member_type;
4499
4500     enum { type = Param::ALGORITHM };
4501 };
4502
4503
4504 /*!
4505 "\nThe CommandLineParser class is designed for command line arguments parsing\n"
4506            "Keys map: \n"
4507            "Before you start to work with CommandLineParser you have to create a map for keys.\n"
4508            "    It will look like this\n"
4509            "    const char* keys =\n"
4510            "    {\n"
4511            "        {    s|  string|  123asd |string parameter}\n"
4512            "        {    d|  digit |  100    |digit parameter }\n"
4513            "        {    c|noCamera|false    |without camera  }\n"
4514            "        {    1|        |some text|help            }\n"
4515            "        {    2|        |333      |another help    }\n"
4516            "    };\n"
4517            "Usage syntax: \n"
4518            "    \"{\" - start of parameter string.\n"
4519            "    \"}\" - end of parameter string\n"
4520            "    \"|\" - separator between short name, full name, default value and help\n"
4521            "Supported syntax: \n"
4522            "    --key1=arg1  <If a key with '--' must has an argument\n"
4523            "                  you have to assign it through '=' sign.> \n"
4524            "<If the key with '--' doesn't have any argument, it means that it is a bool key>\n"
4525            "    -key2=arg2   <If a key with '-' must has an argument \n"
4526            "                  you have to assign it through '=' sign.> \n"
4527            "If the key with '-' doesn't have any argument, it means that it is a bool key\n"
4528            "    key3                 <This key can't has any parameter> \n"
4529            "Usage: \n"
4530            "      Imagine that the input parameters are next:\n"
4531            "                -s=string_value --digit=250 --noCamera lena.jpg 10000\n"
4532            "    CommandLineParser parser(argc, argv, keys) - create a parser object\n"
4533            "    parser.get<string>(\"s\" or \"string\") will return you first parameter value\n"
4534            "    parser.get<string>(\"s\", false or \"string\", false) will return you first parameter value\n"
4535            "                                                                without spaces in end and begin\n"
4536            "    parser.get<int>(\"d\" or \"digit\") will return you second parameter value.\n"
4537            "                    It also works with 'unsigned int', 'double', and 'float' types>\n"
4538            "    parser.get<bool>(\"c\" or \"noCamera\") will return you true .\n"
4539            "                                If you enter this key in commandline>\n"
4540            "                                It return you false otherwise.\n"
4541            "    parser.get<string>(\"1\") will return you the first argument without parameter (lena.jpg) \n"
4542            "    parser.get<int>(\"2\") will return you the second argument without parameter (10000)\n"
4543            "                          It also works with 'unsigned int', 'double', and 'float' types \n"
4544 */
4545 class CV_EXPORTS CommandLineParser
4546 {
4547     public:
4548
4549     //! the default constructor
4550       CommandLineParser(int argc, const char* const argv[], const char* key_map);
4551
4552     //! get parameter, you can choose: delete spaces in end and begin or not
4553     template<typename _Tp>
4554     _Tp get(const std::string& name, bool space_delete=true)
4555     {
4556         if (!has(name))
4557         {
4558             return _Tp();
4559         }
4560         std::string str = getString(name);
4561         return analyzeValue<_Tp>(str, space_delete);
4562     }
4563
4564     //! print short name, full name, current value and help for all params
4565     void printParams();
4566
4567     protected:
4568     std::map<std::string, std::vector<std::string> > data;
4569     std::string getString(const std::string& name);
4570
4571     bool has(const std::string& keys);
4572
4573     template<typename _Tp>
4574     _Tp analyzeValue(const std::string& str, bool space_delete=false);
4575
4576     template<typename _Tp>
4577     static _Tp getData(const std::string& str)
4578     {
4579         _Tp res;
4580         std::stringstream s1(str);
4581         s1 >> res;
4582         return res;
4583     }
4584
4585     template<typename _Tp>
4586      _Tp fromStringNumber(const std::string& str);//the default conversion function for numbers
4587
4588     };
4589
4590 template<> CV_EXPORTS
4591 bool CommandLineParser::get<bool>(const std::string& name, bool space_delete);
4592
4593 template<> CV_EXPORTS
4594 std::string CommandLineParser::analyzeValue<std::string>(const std::string& str, bool space_delete);
4595
4596 template<> CV_EXPORTS
4597 int CommandLineParser::analyzeValue<int>(const std::string& str, bool space_delete);
4598
4599 template<> CV_EXPORTS
4600 unsigned int CommandLineParser::analyzeValue<unsigned int>(const std::string& str, bool space_delete);
4601
4602 template<> CV_EXPORTS
4603 uint64 CommandLineParser::analyzeValue<uint64>(const std::string& str, bool space_delete);
4604
4605 template<> CV_EXPORTS
4606 float CommandLineParser::analyzeValue<float>(const std::string& str, bool space_delete);
4607
4608 template<> CV_EXPORTS
4609 double CommandLineParser::analyzeValue<double>(const std::string& str, bool space_delete);
4610
4611 /////////////////////////////// Parallel Primitives //////////////////////////////////
4612
4613 // a base body class
4614 class CV_EXPORTS ParallelLoopBody
4615 {
4616 public:
4617     virtual void operator() (const Range& range) const = 0;
4618     virtual ~ParallelLoopBody();
4619 };
4620
4621 CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body);
4622
4623 /////////////////////////// Synchronization Primitives ///////////////////////////////
4624
4625 class CV_EXPORTS Mutex
4626 {
4627 public:
4628     Mutex();
4629     ~Mutex();
4630     Mutex(const Mutex& m);
4631     Mutex& operator = (const Mutex& m);
4632     
4633     void lock();
4634     bool trylock();
4635     void unlock();
4636     
4637     struct Impl;
4638 protected:
4639     Impl* impl;
4640 };
4641
4642 class CV_EXPORTS AutoLock
4643 {
4644 public:    
4645     AutoLock(Mutex& m) : mutex(&m) { mutex->lock(); }
4646     ~AutoLock() { mutex->unlock(); }
4647 protected:    
4648     Mutex* mutex;
4649 };
4650
4651 }
4652
4653 #endif // __cplusplus
4654
4655 #include "opencv2/core/operations.hpp"
4656 #include "opencv2/core/mat.hpp"
4657
4658 #endif /*__OPENCV_CORE_HPP__*/