Merge pull request #2835 from ilya-lavrenov:defects
[profile/ivi/opencv.git] / modules / core / include / opencv2 / core / mat.hpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                          License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15 // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
16 // Third party copyrights are property of their respective owners.
17 //
18 // Redistribution and use in source and binary forms, with or without modification,
19 // are permitted provided that the following conditions are met:
20 //
21 //   * Redistribution's of source code must retain the above copyright notice,
22 //     this list of conditions and the following disclaimer.
23 //
24 //   * Redistribution's in binary form must reproduce the above copyright notice,
25 //     this list of conditions and the following disclaimer in the documentation
26 //     and/or other materials provided with the distribution.
27 //
28 //   * The name of the copyright holders may not be used to endorse or promote products
29 //     derived from this software without specific prior written permission.
30 //
31 // This software is provided by the copyright holders and contributors "as is" and
32 // any express or implied warranties, including, but not limited to, the implied
33 // warranties of merchantability and fitness for a particular purpose are disclaimed.
34 // In no event shall the Intel Corporation or contributors be liable for any direct,
35 // indirect, incidental, special, exemplary, or consequential damages
36 // (including, but not limited to, procurement of substitute goods or services;
37 // loss of use, data, or profits; or business interruption) however caused
38 // and on any theory of liability, whether in contract, strict liability,
39 // or tort (including negligence or otherwise) arising in any way out of
40 // the use of this software, even if advised of the possibility of such damage.
41 //
42 //M*/
43
44 #ifndef __OPENCV_CORE_MAT_HPP__
45 #define __OPENCV_CORE_MAT_HPP__
46
47 #ifndef __cplusplus
48 #  error mat.hpp header must be compiled as C++
49 #endif
50
51 #include "opencv2/core/matx.hpp"
52 #include "opencv2/core/types.hpp"
53
54 #include "opencv2/core/bufferpool.hpp"
55
56 namespace cv
57 {
58
59 enum { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25,
60     ACCESS_RW=3<<24, ACCESS_MASK=ACCESS_RW, ACCESS_FAST=1<<26 };
61
62 class CV_EXPORTS _OutputArray;
63
64 //////////////////////// Input/Output Array Arguments /////////////////////////////////
65
66 /*!
67  Proxy datatype for passing Mat's and vector<>'s as input parameters
68  */
69 class CV_EXPORTS _InputArray
70 {
71 public:
72     enum {
73         KIND_SHIFT = 16,
74         FIXED_TYPE = 0x8000 << KIND_SHIFT,
75         FIXED_SIZE = 0x4000 << KIND_SHIFT,
76         KIND_MASK = 31 << KIND_SHIFT,
77
78         NONE              = 0 << KIND_SHIFT,
79         MAT               = 1 << KIND_SHIFT,
80         MATX              = 2 << KIND_SHIFT,
81         STD_VECTOR        = 3 << KIND_SHIFT,
82         STD_VECTOR_VECTOR = 4 << KIND_SHIFT,
83         STD_VECTOR_MAT    = 5 << KIND_SHIFT,
84         EXPR              = 6 << KIND_SHIFT,
85         OPENGL_BUFFER     = 7 << KIND_SHIFT,
86         CUDA_MEM          = 8 << KIND_SHIFT,
87         GPU_MAT           = 9 << KIND_SHIFT,
88         UMAT              =10 << KIND_SHIFT,
89         STD_VECTOR_UMAT   =11 << KIND_SHIFT
90     };
91
92     _InputArray();
93     _InputArray(int _flags, void* _obj);
94     _InputArray(const Mat& m);
95     _InputArray(const MatExpr& expr);
96     _InputArray(const std::vector<Mat>& vec);
97     template<typename _Tp> _InputArray(const Mat_<_Tp>& m);
98     template<typename _Tp> _InputArray(const std::vector<_Tp>& vec);
99     template<typename _Tp> _InputArray(const std::vector<std::vector<_Tp> >& vec);
100     template<typename _Tp> _InputArray(const std::vector<Mat_<_Tp> >& vec);
101     template<typename _Tp> _InputArray(const _Tp* vec, int n);
102     template<typename _Tp, int m, int n> _InputArray(const Matx<_Tp, m, n>& matx);
103     _InputArray(const double& val);
104     _InputArray(const cuda::GpuMat& d_mat);
105     _InputArray(const ogl::Buffer& buf);
106     _InputArray(const cuda::CudaMem& cuda_mem);
107     template<typename _Tp> _InputArray(const cudev::GpuMat_<_Tp>& m);
108     _InputArray(const UMat& um);
109     _InputArray(const std::vector<UMat>& umv);
110
111     virtual Mat getMat(int idx=-1) const;
112     virtual UMat getUMat(int idx=-1) const;
113     virtual void getMatVector(std::vector<Mat>& mv) const;
114     virtual void getUMatVector(std::vector<UMat>& umv) const;
115     virtual cuda::GpuMat getGpuMat() const;
116     virtual ogl::Buffer getOGlBuffer() const;
117     void* getObj() const;
118
119     virtual int kind() const;
120     virtual int dims(int i=-1) const;
121     virtual int cols(int i=-1) const;
122     virtual int rows(int i=-1) const;
123     virtual Size size(int i=-1) const;
124     virtual int sizend(int* sz, int i=-1) const;
125     virtual bool sameSize(const _InputArray& arr) const;
126     virtual size_t total(int i=-1) const;
127     virtual int type(int i=-1) const;
128     virtual int depth(int i=-1) const;
129     virtual int channels(int i=-1) const;
130     virtual bool isContinuous(int i=-1) const;
131     virtual bool isSubmatrix(int i=-1) const;
132     virtual bool empty() const;
133     virtual void copyTo(const _OutputArray& arr) const;
134     virtual void copyTo(const _OutputArray& arr, const _InputArray & mask) const;
135     virtual size_t offset(int i=-1) const;
136     virtual size_t step(int i=-1) const;
137     bool isMat() const;
138     bool isUMat() const;
139     bool isMatVector() const;
140     bool isUMatVector() const;
141     bool isMatx() const;
142
143     virtual ~_InputArray();
144
145 protected:
146     int flags;
147     void* obj;
148     Size sz;
149
150     void init(int _flags, const void* _obj);
151     void init(int _flags, const void* _obj, Size _sz);
152 };
153
154
155 /*!
156  Proxy datatype for passing Mat's and vector<>'s as input parameters
157  */
158 class CV_EXPORTS _OutputArray : public _InputArray
159 {
160 public:
161     enum
162     {
163         DEPTH_MASK_8U = 1 << CV_8U,
164         DEPTH_MASK_8S = 1 << CV_8S,
165         DEPTH_MASK_16U = 1 << CV_16U,
166         DEPTH_MASK_16S = 1 << CV_16S,
167         DEPTH_MASK_32S = 1 << CV_32S,
168         DEPTH_MASK_32F = 1 << CV_32F,
169         DEPTH_MASK_64F = 1 << CV_64F,
170         DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1,
171         DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S,
172         DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F
173     };
174
175     _OutputArray();
176     _OutputArray(int _flags, void* _obj);
177     _OutputArray(Mat& m);
178     _OutputArray(std::vector<Mat>& vec);
179     _OutputArray(cuda::GpuMat& d_mat);
180     _OutputArray(ogl::Buffer& buf);
181     _OutputArray(cuda::CudaMem& cuda_mem);
182     template<typename _Tp> _OutputArray(cudev::GpuMat_<_Tp>& m);
183     template<typename _Tp> _OutputArray(std::vector<_Tp>& vec);
184     template<typename _Tp> _OutputArray(std::vector<std::vector<_Tp> >& vec);
185     template<typename _Tp> _OutputArray(std::vector<Mat_<_Tp> >& vec);
186     template<typename _Tp> _OutputArray(Mat_<_Tp>& m);
187     template<typename _Tp> _OutputArray(_Tp* vec, int n);
188     template<typename _Tp, int m, int n> _OutputArray(Matx<_Tp, m, n>& matx);
189     _OutputArray(UMat& m);
190     _OutputArray(std::vector<UMat>& vec);
191
192     _OutputArray(const Mat& m);
193     _OutputArray(const std::vector<Mat>& vec);
194     _OutputArray(const cuda::GpuMat& d_mat);
195     _OutputArray(const ogl::Buffer& buf);
196     _OutputArray(const cuda::CudaMem& cuda_mem);
197     template<typename _Tp> _OutputArray(const cudev::GpuMat_<_Tp>& m);
198     template<typename _Tp> _OutputArray(const std::vector<_Tp>& vec);
199     template<typename _Tp> _OutputArray(const std::vector<std::vector<_Tp> >& vec);
200     template<typename _Tp> _OutputArray(const std::vector<Mat_<_Tp> >& vec);
201     template<typename _Tp> _OutputArray(const Mat_<_Tp>& m);
202     template<typename _Tp> _OutputArray(const _Tp* vec, int n);
203     template<typename _Tp, int m, int n> _OutputArray(const Matx<_Tp, m, n>& matx);
204     _OutputArray(const UMat& m);
205     _OutputArray(const std::vector<UMat>& vec);
206
207     virtual bool fixedSize() const;
208     virtual bool fixedType() const;
209     virtual bool needed() const;
210     virtual Mat& getMatRef(int i=-1) const;
211     virtual UMat& getUMatRef(int i=-1) const;
212     virtual cuda::GpuMat& getGpuMatRef() const;
213     virtual ogl::Buffer& getOGlBufferRef() const;
214     virtual cuda::CudaMem& getCudaMemRef() const;
215     virtual void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
216     virtual void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
217     virtual void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
218     virtual void createSameSize(const _InputArray& arr, int mtype) const;
219     virtual void release() const;
220     virtual void clear() const;
221     virtual void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const;
222
223     void assign(const UMat& u) const;
224     void assign(const Mat& m) const;
225 };
226
227
228 class CV_EXPORTS _InputOutputArray : public _OutputArray
229 {
230 public:
231     _InputOutputArray();
232     _InputOutputArray(int _flags, void* _obj);
233     _InputOutputArray(Mat& m);
234     _InputOutputArray(std::vector<Mat>& vec);
235     _InputOutputArray(cuda::GpuMat& d_mat);
236     _InputOutputArray(ogl::Buffer& buf);
237     _InputOutputArray(cuda::CudaMem& cuda_mem);
238     template<typename _Tp> _InputOutputArray(cudev::GpuMat_<_Tp>& m);
239     template<typename _Tp> _InputOutputArray(std::vector<_Tp>& vec);
240     template<typename _Tp> _InputOutputArray(std::vector<std::vector<_Tp> >& vec);
241     template<typename _Tp> _InputOutputArray(std::vector<Mat_<_Tp> >& vec);
242     template<typename _Tp> _InputOutputArray(Mat_<_Tp>& m);
243     template<typename _Tp> _InputOutputArray(_Tp* vec, int n);
244     template<typename _Tp, int m, int n> _InputOutputArray(Matx<_Tp, m, n>& matx);
245     _InputOutputArray(UMat& m);
246     _InputOutputArray(std::vector<UMat>& vec);
247
248     _InputOutputArray(const Mat& m);
249     _InputOutputArray(const std::vector<Mat>& vec);
250     _InputOutputArray(const cuda::GpuMat& d_mat);
251     _InputOutputArray(const ogl::Buffer& buf);
252     _InputOutputArray(const cuda::CudaMem& cuda_mem);
253     template<typename _Tp> _InputOutputArray(const cudev::GpuMat_<_Tp>& m);
254     template<typename _Tp> _InputOutputArray(const std::vector<_Tp>& vec);
255     template<typename _Tp> _InputOutputArray(const std::vector<std::vector<_Tp> >& vec);
256     template<typename _Tp> _InputOutputArray(const std::vector<Mat_<_Tp> >& vec);
257     template<typename _Tp> _InputOutputArray(const Mat_<_Tp>& m);
258     template<typename _Tp> _InputOutputArray(const _Tp* vec, int n);
259     template<typename _Tp, int m, int n> _InputOutputArray(const Matx<_Tp, m, n>& matx);
260     _InputOutputArray(const UMat& m);
261     _InputOutputArray(const std::vector<UMat>& vec);
262 };
263
264 typedef const _InputArray& InputArray;
265 typedef InputArray InputArrayOfArrays;
266 typedef const _OutputArray& OutputArray;
267 typedef OutputArray OutputArrayOfArrays;
268 typedef const _InputOutputArray& InputOutputArray;
269 typedef InputOutputArray InputOutputArrayOfArrays;
270
271 CV_EXPORTS InputOutputArray noArray();
272
273 /////////////////////////////////// MatAllocator //////////////////////////////////////
274
275 //! Usage flags for allocator
276 enum UMatUsageFlags
277 {
278     USAGE_DEFAULT = 0,
279
280     // default allocation policy is platform and usage specific
281     USAGE_ALLOCATE_HOST_MEMORY = 1 << 0,
282     USAGE_ALLOCATE_DEVICE_MEMORY = 1 << 1,
283
284     __UMAT_USAGE_FLAGS_32BIT = 0x7fffffff // Binary compatibility hint
285 };
286
287 struct CV_EXPORTS UMatData;
288
289 /*!
290    Custom array allocator
291
292 */
293 class CV_EXPORTS MatAllocator
294 {
295 public:
296     MatAllocator() {}
297     virtual ~MatAllocator() {}
298
299     // let's comment it off for now to detect and fix all the uses of allocator
300     //virtual void allocate(int dims, const int* sizes, int type, int*& refcount,
301     //                      uchar*& datastart, uchar*& data, size_t* step) = 0;
302     //virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0;
303     virtual UMatData* allocate(int dims, const int* sizes, int type,
304                                void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const = 0;
305     virtual bool allocate(UMatData* data, int accessflags, UMatUsageFlags usageFlags) const = 0;
306     virtual void deallocate(UMatData* data) const = 0;
307     virtual void map(UMatData* data, int accessflags) const;
308     virtual void unmap(UMatData* data) const;
309     virtual void download(UMatData* data, void* dst, int dims, const size_t sz[],
310                           const size_t srcofs[], const size_t srcstep[],
311                           const size_t dststep[]) const;
312     virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[],
313                         const size_t dstofs[], const size_t dststep[],
314                         const size_t srcstep[]) const;
315     virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[],
316                       const size_t srcofs[], const size_t srcstep[],
317                       const size_t dstofs[], const size_t dststep[], bool sync) const;
318
319     // default implementation returns DummyBufferPoolController
320     virtual BufferPoolController* getBufferPoolController() const;
321 };
322
323
324 //////////////////////////////// MatCommaInitializer //////////////////////////////////
325
326 /*!
327  Comma-separated Matrix Initializer
328
329  The class instances are usually not created explicitly.
330  Instead, they are created on "matrix << firstValue" operator.
331
332  The sample below initializes 2x2 rotation matrix:
333
334  \code
335  double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180);
336  Mat R = (Mat_<double>(2,2) << a, -b, b, a);
337  \endcode
338 */
339 template<typename _Tp> class MatCommaInitializer_
340 {
341 public:
342     //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat
343     MatCommaInitializer_(Mat_<_Tp>* _m);
344     //! the operator that takes the next value and put it to the matrix
345     template<typename T2> MatCommaInitializer_<_Tp>& operator , (T2 v);
346     //! another form of conversion operator
347     operator Mat_<_Tp>() const;
348 protected:
349     MatIterator_<_Tp> it;
350 };
351
352
353 /////////////////////////////////////// Mat ///////////////////////////////////////////
354
355 // note that umatdata might be allocated together
356 // with the matrix data, not as a separate object.
357 // therefore, it does not have constructor or destructor;
358 // it should be explicitly initialized using init().
359 struct CV_EXPORTS UMatData
360 {
361     enum { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2,
362         DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24,
363         USER_ALLOCATED=32 };
364     UMatData(const MatAllocator* allocator);
365     ~UMatData();
366
367     // provide atomic access to the structure
368     void lock();
369     void unlock();
370
371     bool hostCopyObsolete() const;
372     bool deviceCopyObsolete() const;
373     bool copyOnMap() const;
374     bool tempUMat() const;
375     bool tempCopiedUMat() const;
376     void markHostCopyObsolete(bool flag);
377     void markDeviceCopyObsolete(bool flag);
378
379     const MatAllocator* prevAllocator;
380     const MatAllocator* currAllocator;
381     int urefcount;
382     int refcount;
383     uchar* data;
384     uchar* origdata;
385     size_t size, capacity;
386
387     int flags;
388     void* handle;
389     void* userdata;
390     int allocatorFlags_;
391 };
392
393
394 struct CV_EXPORTS UMatDataAutoLock
395 {
396     UMatDataAutoLock(UMatData* u);
397     ~UMatDataAutoLock();
398     UMatData* u;
399 };
400
401
402 struct CV_EXPORTS MatSize
403 {
404     MatSize(int* _p);
405     Size operator()() const;
406     const int& operator[](int i) const;
407     int& operator[](int i);
408     operator const int*() const;
409     bool operator == (const MatSize& sz) const;
410     bool operator != (const MatSize& sz) const;
411
412     int* p;
413 };
414
415 struct CV_EXPORTS MatStep
416 {
417     MatStep();
418     MatStep(size_t s);
419     const size_t& operator[](int i) const;
420     size_t& operator[](int i);
421     operator size_t() const;
422     MatStep& operator = (size_t s);
423
424     size_t* p;
425     size_t buf[2];
426 protected:
427     MatStep& operator = (const MatStep&);
428 };
429
430  /*!
431    The n-dimensional matrix class.
432
433    The class represents an n-dimensional dense numerical array that can act as
434    a matrix, image, optical flow map, 3-focal tensor etc.
435    It is very similar to CvMat and CvMatND types from earlier versions of OpenCV,
436    and similarly to those types, the matrix can be multi-channel. It also fully supports ROI mechanism.
437
438    There are many different ways to create cv::Mat object. Here are the some popular ones:
439    <ul>
440    <li> using cv::Mat::create(nrows, ncols, type) method or
441      the similar constructor cv::Mat::Mat(nrows, ncols, type[, fill_value]) constructor.
442      A new matrix of the specified size and specifed type will be allocated.
443      "type" has the same meaning as in cvCreateMat function,
444      e.g. CV_8UC1 means 8-bit single-channel matrix, CV_32FC2 means 2-channel (i.e. complex)
445      floating-point matrix etc:
446
447      \code
448      // make 7x7 complex matrix filled with 1+3j.
449      cv::Mat M(7,7,CV_32FC2,Scalar(1,3));
450      // and now turn M to 100x60 15-channel 8-bit matrix.
451      // The old content will be deallocated
452      M.create(100,60,CV_8UC(15));
453      \endcode
454
455      As noted in the introduction of this chapter, Mat::create()
456      will only allocate a new matrix when the current matrix dimensionality
457      or type are different from the specified.
458
459    <li> by using a copy constructor or assignment operator, where on the right side it can
460      be a matrix or expression, see below. Again, as noted in the introduction,
461      matrix assignment is O(1) operation because it only copies the header
462      and increases the reference counter. cv::Mat::clone() method can be used to get a full
463      (a.k.a. deep) copy of the matrix when you need it.
464
465    <li> by constructing a header for a part of another matrix. It can be a single row, single column,
466      several rows, several columns, rectangular region in the matrix (called a minor in algebra) or
467      a diagonal. Such operations are also O(1), because the new header will reference the same data.
468      You can actually modify a part of the matrix using this feature, e.g.
469
470      \code
471      // add 5-th row, multiplied by 3 to the 3rd row
472      M.row(3) = M.row(3) + M.row(5)*3;
473
474      // now copy 7-th column to the 1-st column
475      // M.col(1) = M.col(7); // this will not work
476      Mat M1 = M.col(1);
477      M.col(7).copyTo(M1);
478
479      // create new 320x240 image
480      cv::Mat img(Size(320,240),CV_8UC3);
481      // select a roi
482      cv::Mat roi(img, Rect(10,10,100,100));
483      // fill the ROI with (0,255,0) (which is green in RGB space);
484      // the original 320x240 image will be modified
485      roi = Scalar(0,255,0);
486      \endcode
487
488      Thanks to the additional cv::Mat::datastart and cv::Mat::dataend members, it is possible to
489      compute the relative sub-matrix position in the main "container" matrix using cv::Mat::locateROI():
490
491      \code
492      Mat A = Mat::eye(10, 10, CV_32S);
493      // extracts A columns, 1 (inclusive) to 3 (exclusive).
494      Mat B = A(Range::all(), Range(1, 3));
495      // extracts B rows, 5 (inclusive) to 9 (exclusive).
496      // that is, C ~ A(Range(5, 9), Range(1, 3))
497      Mat C = B(Range(5, 9), Range::all());
498      Size size; Point ofs;
499      C.locateROI(size, ofs);
500      // size will be (width=10,height=10) and the ofs will be (x=1, y=5)
501      \endcode
502
503      As in the case of whole matrices, if you need a deep copy, use cv::Mat::clone() method
504      of the extracted sub-matrices.
505
506    <li> by making a header for user-allocated-data. It can be useful for
507       <ol>
508       <li> processing "foreign" data using OpenCV (e.g. when you implement
509          a DirectShow filter or a processing module for gstreamer etc.), e.g.
510
511          \code
512          void process_video_frame(const unsigned char* pixels,
513                                   int width, int height, int step)
514          {
515             cv::Mat img(height, width, CV_8UC3, pixels, step);
516             cv::GaussianBlur(img, img, cv::Size(7,7), 1.5, 1.5);
517          }
518          \endcode
519
520       <li> for quick initialization of small matrices and/or super-fast element access
521
522          \code
523          double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
524          cv::Mat M = cv::Mat(3, 3, CV_64F, m).inv();
525          \endcode
526       </ol>
527
528        partial yet very common cases of this "user-allocated data" case are conversions
529        from CvMat and IplImage to cv::Mat. For this purpose there are special constructors
530        taking pointers to CvMat or IplImage and the optional
531        flag indicating whether to copy the data or not.
532
533        Backward conversion from cv::Mat to CvMat or IplImage is provided via cast operators
534        cv::Mat::operator CvMat() an cv::Mat::operator IplImage().
535        The operators do not copy the data.
536
537
538        \code
539        IplImage* img = cvLoadImage("greatwave.jpg", 1);
540        Mat mtx(img); // convert IplImage* -> cv::Mat
541        CvMat oldmat = mtx; // convert cv::Mat -> CvMat
542        CV_Assert(oldmat.cols == img->width && oldmat.rows == img->height &&
543            oldmat.data.ptr == (uchar*)img->imageData && oldmat.step == img->widthStep);
544        \endcode
545
546    <li> by using MATLAB-style matrix initializers, cv::Mat::zeros(), cv::Mat::ones(), cv::Mat::eye(), e.g.:
547
548    \code
549    // create a double-precision identity martix and add it to M.
550    M += Mat::eye(M.rows, M.cols, CV_64F);
551    \endcode
552
553    <li> by using comma-separated initializer:
554
555    \code
556    // create 3x3 double-precision identity matrix
557    Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
558    \endcode
559
560    here we first call constructor of cv::Mat_ class (that we describe further) with the proper matrix,
561    and then we just put "<<" operator followed by comma-separated values that can be constants,
562    variables, expressions etc. Also, note the extra parentheses that are needed to avoid compiler errors.
563
564    </ul>
565
566    Once matrix is created, it will be automatically managed by using reference-counting mechanism
567    (unless the matrix header is built on top of user-allocated data,
568    in which case you should handle the data by yourself).
569    The matrix data will be deallocated when no one points to it;
570    if you want to release the data pointed by a matrix header before the matrix destructor is called,
571    use cv::Mat::release().
572
573    The next important thing to learn about the matrix class is element access. Here is how the matrix is stored.
574    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,
575    cv::Mat::rows contains the number of matrix rows and cv::Mat::cols - the number of matrix columns. There is yet another member,
576    cv::Mat::step that is used to actually compute address of a matrix element. cv::Mat::step is needed because the matrix can be
577    a part of another matrix or because there can some padding space in the end of each row for a proper alignment.
578
579    \image html roi.png
580
581    Given these parameters, address of the matrix element M_{ij} is computed as following:
582
583    addr(M_{ij})=M.data + M.step*i + j*M.elemSize()
584
585    if you know the matrix element type, e.g. it is float, then you can use cv::Mat::at() method:
586
587    addr(M_{ij})=&M.at<float>(i,j)
588
589    (where & is used to convert the reference returned by cv::Mat::at() to a pointer).
590    if you need to process a whole row of matrix, the most efficient way is to get
591    the pointer to the row first, and then just use plain C operator []:
592
593    \code
594    // compute sum of positive matrix elements
595    // (assuming that M is double-precision matrix)
596    double sum=0;
597    for(int i = 0; i < M.rows; i++)
598    {
599        const double* Mi = M.ptr<double>(i);
600        for(int j = 0; j < M.cols; j++)
601            sum += std::max(Mi[j], 0.);
602    }
603    \endcode
604
605    Some operations, like the above one, do not actually depend on the matrix shape,
606    they just process elements of a matrix one by one (or elements from multiple matrices
607    that are sitting in the same place, e.g. matrix addition). Such operations are called
608    element-wise and it makes sense to check whether all the input/output matrices are continuous,
609    i.e. have no gaps in the end of each row, and if yes, process them as a single long row:
610
611    \code
612    // compute sum of positive matrix elements, optimized variant
613    double sum=0;
614    int cols = M.cols, rows = M.rows;
615    if(M.isContinuous())
616    {
617        cols *= rows;
618        rows = 1;
619    }
620    for(int i = 0; i < rows; i++)
621    {
622        const double* Mi = M.ptr<double>(i);
623        for(int j = 0; j < cols; j++)
624            sum += std::max(Mi[j], 0.);
625    }
626    \endcode
627    in the case of continuous matrix the outer loop body will be executed just once,
628    so the overhead will be smaller, which will be especially noticeable in the case of small matrices.
629
630    Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:
631    \code
632    // compute sum of positive matrix elements, iterator-based variant
633    double sum=0;
634    MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
635    for(; it != it_end; ++it)
636        sum += std::max(*it, 0.);
637    \endcode
638
639    The matrix iterators are random-access iterators, so they can be passed
640    to any STL algorithm, including std::sort().
641 */
642 class CV_EXPORTS Mat
643 {
644 public:
645     //! default constructor
646     Mat();
647     //! constructs 2D matrix of the specified size and type
648     // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
649     Mat(int rows, int cols, int type);
650     Mat(Size size, int type);
651     //! constucts 2D matrix and fills it with the specified value _s.
652     Mat(int rows, int cols, int type, const Scalar& s);
653     Mat(Size size, int type, const Scalar& s);
654
655     //! constructs n-dimensional matrix
656     Mat(int ndims, const int* sizes, int type);
657     Mat(int ndims, const int* sizes, int type, const Scalar& s);
658
659     //! copy constructor
660     Mat(const Mat& m);
661     //! constructor for matrix headers pointing to user-allocated data
662     Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP);
663     Mat(Size size, int type, void* data, size_t step=AUTO_STEP);
664     Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0);
665
666     //! creates a matrix header for a part of the bigger matrix
667     Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all());
668     Mat(const Mat& m, const Rect& roi);
669     Mat(const Mat& m, const Range* ranges);
670     //! builds matrix from std::vector with or without copying the data
671     template<typename _Tp> explicit Mat(const std::vector<_Tp>& vec, bool copyData=false);
672     //! builds matrix from cv::Vec; the data is copied by default
673     template<typename _Tp, int n> explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true);
674     //! builds matrix from cv::Matx; the data is copied by default
675     template<typename _Tp, int m, int n> explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
676     //! builds matrix from a 2D point
677     template<typename _Tp> explicit Mat(const Point_<_Tp>& pt, bool copyData=true);
678     //! builds matrix from a 3D point
679     template<typename _Tp> explicit Mat(const Point3_<_Tp>& pt, bool copyData=true);
680     //! builds matrix from comma initializer
681     template<typename _Tp> explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer);
682
683     //! download data from GpuMat
684     explicit Mat(const cuda::GpuMat& m);
685
686     //! destructor - calls release()
687     ~Mat();
688     //! assignment operators
689     Mat& operator = (const Mat& m);
690     Mat& operator = (const MatExpr& expr);
691
692     //! retrieve UMat from Mat
693     UMat getUMat(int accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const;
694
695     //! returns a new matrix header for the specified row
696     Mat row(int y) const;
697     //! returns a new matrix header for the specified column
698     Mat col(int x) const;
699     //! ... for the specified row span
700     Mat rowRange(int startrow, int endrow) const;
701     Mat rowRange(const Range& r) const;
702     //! ... for the specified column span
703     Mat colRange(int startcol, int endcol) const;
704     Mat colRange(const Range& r) const;
705     //! ... for the specified diagonal
706     // (d=0 - the main diagonal,
707     //  >0 - a diagonal from the lower half,
708     //  <0 - a diagonal from the upper half)
709     Mat diag(int d=0) const;
710     //! constructs a square diagonal matrix which main diagonal is vector "d"
711     static Mat diag(const Mat& d);
712
713     //! returns deep copy of the matrix, i.e. the data is copied
714     Mat clone() const;
715     //! copies the matrix content to "m".
716     // It calls m.create(this->size(), this->type()).
717     void copyTo( OutputArray m ) const;
718     //! copies those matrix elements to "m" that are marked with non-zero mask elements.
719     void copyTo( OutputArray m, InputArray mask ) const;
720     //! converts matrix to another datatype with optional scalng. See cvConvertScale.
721     void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
722
723     void assignTo( Mat& m, int type=-1 ) const;
724
725     //! sets every matrix element to s
726     Mat& operator = (const Scalar& s);
727     //! sets some of the matrix elements to s, according to the mask
728     Mat& setTo(InputArray value, InputArray mask=noArray());
729     //! creates alternative matrix header for the same data, with different
730     // number of channels and/or different number of rows. see cvReshape.
731     Mat reshape(int cn, int rows=0) const;
732     Mat reshape(int cn, int newndims, const int* newsz) const;
733
734     //! matrix transposition by means of matrix expressions
735     MatExpr t() const;
736     //! matrix inversion by means of matrix expressions
737     MatExpr inv(int method=DECOMP_LU) const;
738     //! per-element matrix multiplication by means of matrix expressions
739     MatExpr mul(InputArray m, double scale=1) const;
740
741     //! computes cross-product of 2 3D vectors
742     Mat cross(InputArray m) const;
743     //! computes dot-product
744     double dot(InputArray m) const;
745
746     //! Matlab-style matrix initialization
747     static MatExpr zeros(int rows, int cols, int type);
748     static MatExpr zeros(Size size, int type);
749     static MatExpr zeros(int ndims, const int* sz, int type);
750     static MatExpr ones(int rows, int cols, int type);
751     static MatExpr ones(Size size, int type);
752     static MatExpr ones(int ndims, const int* sz, int type);
753     static MatExpr eye(int rows, int cols, int type);
754     static MatExpr eye(Size size, int type);
755
756     //! allocates new matrix data unless the matrix already has specified size and type.
757     // previous data is unreferenced if needed.
758     void create(int rows, int cols, int type);
759     void create(Size size, int type);
760     void create(int ndims, const int* sizes, int type);
761
762     //! increases the reference counter; use with care to avoid memleaks
763     void addref();
764     //! decreases reference counter;
765     // deallocates the data when reference counter reaches 0.
766     void release();
767
768     //! deallocates the matrix data
769     void deallocate();
770     //! internal use function; properly re-allocates _size, _step arrays
771     void copySize(const Mat& m);
772
773     //! reserves enough space to fit sz hyper-planes
774     void reserve(size_t sz);
775     //! resizes matrix to the specified number of hyper-planes
776     void resize(size_t sz);
777     //! resizes matrix to the specified number of hyper-planes; initializes the newly added elements
778     void resize(size_t sz, const Scalar& s);
779     //! internal function
780     void push_back_(const void* elem);
781     //! adds element to the end of 1d matrix (or possibly multiple elements when _Tp=Mat)
782     template<typename _Tp> void push_back(const _Tp& elem);
783     template<typename _Tp> void push_back(const Mat_<_Tp>& elem);
784     void push_back(const Mat& m);
785     //! removes several hyper-planes from bottom of the matrix
786     void pop_back(size_t nelems=1);
787
788     //! locates matrix header within a parent matrix. See below
789     void locateROI( Size& wholeSize, Point& ofs ) const;
790     //! moves/resizes the current matrix ROI inside the parent matrix.
791     Mat& adjustROI( int dtop, int dbottom, int dleft, int dright );
792     //! extracts a rectangular sub-matrix
793     // (this is a generalized form of row, rowRange etc.)
794     Mat operator()( Range rowRange, Range colRange ) const;
795     Mat operator()( const Rect& roi ) const;
796     Mat operator()( const Range* ranges ) const;
797
798     // //! converts header to CvMat; no data is copied
799     // operator CvMat() const;
800     // //! converts header to CvMatND; no data is copied
801     // operator CvMatND() const;
802     // //! converts header to IplImage; no data is copied
803     // operator IplImage() const;
804
805     template<typename _Tp> operator std::vector<_Tp>() const;
806     template<typename _Tp, int n> operator Vec<_Tp, n>() const;
807     template<typename _Tp, int m, int n> operator Matx<_Tp, m, n>() const;
808
809     //! returns true iff the matrix data is continuous
810     // (i.e. when there are no gaps between successive rows).
811     // similar to CV_IS_MAT_CONT(cvmat->type)
812     bool isContinuous() const;
813
814     //! returns true if the matrix is a submatrix of another matrix
815     bool isSubmatrix() const;
816
817     //! returns element size in bytes,
818     // similar to CV_ELEM_SIZE(cvmat->type)
819     size_t elemSize() const;
820     //! returns the size of element channel in bytes.
821     size_t elemSize1() const;
822     //! returns element type, similar to CV_MAT_TYPE(cvmat->type)
823     int type() const;
824     //! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
825     int depth() const;
826     //! returns element type, similar to CV_MAT_CN(cvmat->type)
827     int channels() const;
828     //! returns step/elemSize1()
829     size_t step1(int i=0) const;
830     //! returns true if matrix data is NULL
831     bool empty() const;
832     //! returns the total number of matrix elements
833     size_t total() const;
834
835     //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
836     int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
837
838     //! returns pointer to i0-th submatrix along the dimension #0
839     uchar* ptr(int i0=0);
840     const uchar* ptr(int i0=0) const;
841
842     //! returns pointer to (i0,i1) submatrix along the dimensions #0 and #1
843     uchar* ptr(int i0, int i1);
844     const uchar* ptr(int i0, int i1) const;
845
846     //! returns pointer to (i0,i1,i3) submatrix along the dimensions #0, #1, #2
847     uchar* ptr(int i0, int i1, int i2);
848     const uchar* ptr(int i0, int i1, int i2) const;
849
850     //! returns pointer to the matrix element
851     uchar* ptr(const int* idx);
852     //! returns read-only pointer to the matrix element
853     const uchar* ptr(const int* idx) const;
854
855     template<int n> uchar* ptr(const Vec<int, n>& idx);
856     template<int n> const uchar* ptr(const Vec<int, n>& idx) const;
857
858     //! template version of the above method
859     template<typename _Tp> _Tp* ptr(int i0=0);
860     template<typename _Tp> const _Tp* ptr(int i0=0) const;
861
862     template<typename _Tp> _Tp* ptr(int i0, int i1);
863     template<typename _Tp> const _Tp* ptr(int i0, int i1) const;
864
865     template<typename _Tp> _Tp* ptr(int i0, int i1, int i2);
866     template<typename _Tp> const _Tp* ptr(int i0, int i1, int i2) const;
867
868     template<typename _Tp> _Tp* ptr(const int* idx);
869     template<typename _Tp> const _Tp* ptr(const int* idx) const;
870
871     template<typename _Tp, int n> _Tp* ptr(const Vec<int, n>& idx);
872     template<typename _Tp, int n> const _Tp* ptr(const Vec<int, n>& idx) const;
873
874     //! the same as above, with the pointer dereferencing
875     template<typename _Tp> _Tp& at(int i0=0);
876     template<typename _Tp> const _Tp& at(int i0=0) const;
877
878     template<typename _Tp> _Tp& at(int i0, int i1);
879     template<typename _Tp> const _Tp& at(int i0, int i1) const;
880
881     template<typename _Tp> _Tp& at(int i0, int i1, int i2);
882     template<typename _Tp> const _Tp& at(int i0, int i1, int i2) const;
883
884     template<typename _Tp> _Tp& at(const int* idx);
885     template<typename _Tp> const _Tp& at(const int* idx) const;
886
887     template<typename _Tp, int n> _Tp& at(const Vec<int, n>& idx);
888     template<typename _Tp, int n> const _Tp& at(const Vec<int, n>& idx) const;
889
890     //! special versions for 2D arrays (especially convenient for referencing image pixels)
891     template<typename _Tp> _Tp& at(Point pt);
892     template<typename _Tp> const _Tp& at(Point pt) const;
893
894     //! template methods for iteration over matrix elements.
895     // the iterators take care of skipping gaps in the end of rows (if any)
896     template<typename _Tp> MatIterator_<_Tp> begin();
897     template<typename _Tp> MatIterator_<_Tp> end();
898     template<typename _Tp> MatConstIterator_<_Tp> begin() const;
899     template<typename _Tp> MatConstIterator_<_Tp> end() const;
900
901     enum { MAGIC_VAL  = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
902     enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
903
904     /*! includes several bit-fields:
905          - the magic signature
906          - continuity flag
907          - depth
908          - number of channels
909      */
910     int flags;
911     //! the matrix dimensionality, >= 2
912     int dims;
913     //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
914     int rows, cols;
915     //! pointer to the data
916     uchar* data;
917
918     //! helper fields used in locateROI and adjustROI
919     uchar* datastart;
920     uchar* dataend;
921     uchar* datalimit;
922
923     //! custom allocator
924     MatAllocator* allocator;
925     //! and the standard allocator
926     static MatAllocator* getStdAllocator();
927
928     //! interaction with UMat
929     UMatData* u;
930
931     MatSize size;
932     MatStep step;
933
934 protected:
935 };
936
937
938 ///////////////////////////////// Mat_<_Tp> ////////////////////////////////////
939
940 /*!
941  Template matrix class derived from Mat
942
943  The class Mat_ is a "thin" template wrapper on top of cv::Mat. It does not have any extra data fields,
944  nor it or cv::Mat have any virtual methods and thus references or pointers to these two classes
945  can be safely converted one to another. But do it with care, for example:
946
947  \code
948  // create 100x100 8-bit matrix
949  Mat M(100,100,CV_8U);
950  // this will compile fine. no any data conversion will be done.
951  Mat_<float>& M1 = (Mat_<float>&)M;
952  // the program will likely crash at the statement below
953  M1(99,99) = 1.f;
954  \endcode
955
956  While cv::Mat is sufficient in most cases, cv::Mat_ can be more convenient if you use a lot of element
957  access operations and if you know matrix type at compile time.
958  Note that cv::Mat::at<_Tp>(int y, int x) and cv::Mat_<_Tp>::operator ()(int y, int x) do absolutely the
959  same thing and run at the same speed, but the latter is certainly shorter:
960
961  \code
962  Mat_<double> M(20,20);
963  for(int i = 0; i < M.rows; i++)
964     for(int j = 0; j < M.cols; j++)
965        M(i,j) = 1./(i+j+1);
966  Mat E, V;
967  eigen(M,E,V);
968  cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
969  \endcode
970
971  It is easy to use Mat_ for multi-channel images/matrices - just pass cv::Vec as cv::Mat_ template parameter:
972
973  \code
974  // allocate 320x240 color image and fill it with green (in RGB space)
975  Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
976  // now draw a diagonal white line
977  for(int i = 0; i < 100; i++)
978      img(i,i)=Vec3b(255,255,255);
979  // and now modify the 2nd (red) channel of each pixel
980  for(int i = 0; i < img.rows; i++)
981     for(int j = 0; j < img.cols; j++)
982        img(i,j)[2] ^= (uchar)(i ^ j); // img(y,x)[c] accesses c-th channel of the pixel (x,y)
983  \endcode
984 */
985 template<typename _Tp> class Mat_ : public Mat
986 {
987 public:
988     typedef _Tp value_type;
989     typedef typename DataType<_Tp>::channel_type channel_type;
990     typedef MatIterator_<_Tp> iterator;
991     typedef MatConstIterator_<_Tp> const_iterator;
992
993     //! default constructor
994     Mat_();
995     //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type)
996     Mat_(int _rows, int _cols);
997     //! constructor that sets each matrix element to specified value
998     Mat_(int _rows, int _cols, const _Tp& value);
999     //! equivalent to Mat(_size, DataType<_Tp>::type)
1000     explicit Mat_(Size _size);
1001     //! constructor that sets each matrix element to specified value
1002     Mat_(Size _size, const _Tp& value);
1003     //! n-dim array constructor
1004     Mat_(int _ndims, const int* _sizes);
1005     //! n-dim array constructor that sets each matrix element to specified value
1006     Mat_(int _ndims, const int* _sizes, const _Tp& value);
1007     //! copy/conversion contructor. If m is of different type, it's converted
1008     Mat_(const Mat& m);
1009     //! copy constructor
1010     Mat_(const Mat_& m);
1011     //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type
1012     Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP);
1013     //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type
1014     Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0);
1015     //! selects a submatrix
1016     Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all());
1017     //! selects a submatrix
1018     Mat_(const Mat_& m, const Rect& roi);
1019     //! selects a submatrix, n-dim version
1020     Mat_(const Mat_& m, const Range* ranges);
1021     //! from a matrix expression
1022     explicit Mat_(const MatExpr& e);
1023     //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column
1024     explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false);
1025     template<int n> explicit Mat_(const Vec<typename DataType<_Tp>::channel_type, n>& vec, bool copyData=true);
1026     template<int m, int n> explicit Mat_(const Matx<typename DataType<_Tp>::channel_type, m, n>& mtx, bool copyData=true);
1027     explicit Mat_(const Point_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
1028     explicit Mat_(const Point3_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
1029     explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer);
1030
1031     Mat_& operator = (const Mat& m);
1032     Mat_& operator = (const Mat_& m);
1033     //! set all the elements to s.
1034     Mat_& operator = (const _Tp& s);
1035     //! assign a matrix expression
1036     Mat_& operator = (const MatExpr& e);
1037
1038     //! iterators; they are smart enough to skip gaps in the end of rows
1039     iterator begin();
1040     iterator end();
1041     const_iterator begin() const;
1042     const_iterator end() const;
1043
1044     //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type)
1045     void create(int _rows, int _cols);
1046     //! equivalent to Mat::create(_size, DataType<_Tp>::type)
1047     void create(Size _size);
1048     //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type)
1049     void create(int _ndims, const int* _sizes);
1050     //! cross-product
1051     Mat_ cross(const Mat_& m) const;
1052     //! data type conversion
1053     template<typename T2> operator Mat_<T2>() const;
1054     //! overridden forms of Mat::row() etc.
1055     Mat_ row(int y) const;
1056     Mat_ col(int x) const;
1057     Mat_ diag(int d=0) const;
1058     Mat_ clone() const;
1059
1060     //! overridden forms of Mat::elemSize() etc.
1061     size_t elemSize() const;
1062     size_t elemSize1() const;
1063     int type() const;
1064     int depth() const;
1065     int channels() const;
1066     size_t step1(int i=0) const;
1067     //! returns step()/sizeof(_Tp)
1068     size_t stepT(int i=0) const;
1069
1070     //! overridden forms of Mat::zeros() etc. Data type is omitted, of course
1071     static MatExpr zeros(int rows, int cols);
1072     static MatExpr zeros(Size size);
1073     static MatExpr zeros(int _ndims, const int* _sizes);
1074     static MatExpr ones(int rows, int cols);
1075     static MatExpr ones(Size size);
1076     static MatExpr ones(int _ndims, const int* _sizes);
1077     static MatExpr eye(int rows, int cols);
1078     static MatExpr eye(Size size);
1079
1080     //! some more overriden methods
1081     Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright );
1082     Mat_ operator()( const Range& rowRange, const Range& colRange ) const;
1083     Mat_ operator()( const Rect& roi ) const;
1084     Mat_ operator()( const Range* ranges ) const;
1085
1086     //! more convenient forms of row and element access operators
1087     _Tp* operator [](int y);
1088     const _Tp* operator [](int y) const;
1089
1090     //! returns reference to the specified element
1091     _Tp& operator ()(const int* idx);
1092     //! returns read-only reference to the specified element
1093     const _Tp& operator ()(const int* idx) const;
1094
1095     //! returns reference to the specified element
1096     template<int n> _Tp& operator ()(const Vec<int, n>& idx);
1097     //! returns read-only reference to the specified element
1098     template<int n> const _Tp& operator ()(const Vec<int, n>& idx) const;
1099
1100     //! returns reference to the specified element (1D case)
1101     _Tp& operator ()(int idx0);
1102     //! returns read-only reference to the specified element (1D case)
1103     const _Tp& operator ()(int idx0) const;
1104     //! returns reference to the specified element (2D case)
1105     _Tp& operator ()(int idx0, int idx1);
1106     //! returns read-only reference to the specified element (2D case)
1107     const _Tp& operator ()(int idx0, int idx1) const;
1108     //! returns reference to the specified element (3D case)
1109     _Tp& operator ()(int idx0, int idx1, int idx2);
1110     //! returns read-only reference to the specified element (3D case)
1111     const _Tp& operator ()(int idx0, int idx1, int idx2) const;
1112
1113     _Tp& operator ()(Point pt);
1114     const _Tp& operator ()(Point pt) const;
1115
1116     //! conversion to vector.
1117     operator std::vector<_Tp>() const;
1118     //! conversion to Vec
1119     template<int n> operator Vec<typename DataType<_Tp>::channel_type, n>() const;
1120     //! conversion to Matx
1121     template<int m, int n> operator Matx<typename DataType<_Tp>::channel_type, m, n>() const;
1122 };
1123
1124 typedef Mat_<uchar> Mat1b;
1125 typedef Mat_<Vec2b> Mat2b;
1126 typedef Mat_<Vec3b> Mat3b;
1127 typedef Mat_<Vec4b> Mat4b;
1128
1129 typedef Mat_<short> Mat1s;
1130 typedef Mat_<Vec2s> Mat2s;
1131 typedef Mat_<Vec3s> Mat3s;
1132 typedef Mat_<Vec4s> Mat4s;
1133
1134 typedef Mat_<ushort> Mat1w;
1135 typedef Mat_<Vec2w> Mat2w;
1136 typedef Mat_<Vec3w> Mat3w;
1137 typedef Mat_<Vec4w> Mat4w;
1138
1139 typedef Mat_<int>   Mat1i;
1140 typedef Mat_<Vec2i> Mat2i;
1141 typedef Mat_<Vec3i> Mat3i;
1142 typedef Mat_<Vec4i> Mat4i;
1143
1144 typedef Mat_<float> Mat1f;
1145 typedef Mat_<Vec2f> Mat2f;
1146 typedef Mat_<Vec3f> Mat3f;
1147 typedef Mat_<Vec4f> Mat4f;
1148
1149 typedef Mat_<double> Mat1d;
1150 typedef Mat_<Vec2d> Mat2d;
1151 typedef Mat_<Vec3d> Mat3d;
1152 typedef Mat_<Vec4d> Mat4d;
1153
1154 class CV_EXPORTS UMat
1155 {
1156 public:
1157     //! default constructor
1158     UMat(UMatUsageFlags usageFlags = USAGE_DEFAULT);
1159     //! constructs 2D matrix of the specified size and type
1160     // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
1161     UMat(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1162     UMat(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1163     //! constucts 2D matrix and fills it with the specified value _s.
1164     UMat(int rows, int cols, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1165     UMat(Size size, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1166
1167     //! constructs n-dimensional matrix
1168     UMat(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1169     UMat(int ndims, const int* sizes, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1170
1171     //! copy constructor
1172     UMat(const UMat& m);
1173
1174     //! creates a matrix header for a part of the bigger matrix
1175     UMat(const UMat& m, const Range& rowRange, const Range& colRange=Range::all());
1176     UMat(const UMat& m, const Rect& roi);
1177     UMat(const UMat& m, const Range* ranges);
1178     //! builds matrix from std::vector with or without copying the data
1179     template<typename _Tp> explicit UMat(const std::vector<_Tp>& vec, bool copyData=false);
1180     //! builds matrix from cv::Vec; the data is copied by default
1181     template<typename _Tp, int n> explicit UMat(const Vec<_Tp, n>& vec, bool copyData=true);
1182     //! builds matrix from cv::Matx; the data is copied by default
1183     template<typename _Tp, int m, int n> explicit UMat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
1184     //! builds matrix from a 2D point
1185     template<typename _Tp> explicit UMat(const Point_<_Tp>& pt, bool copyData=true);
1186     //! builds matrix from a 3D point
1187     template<typename _Tp> explicit UMat(const Point3_<_Tp>& pt, bool copyData=true);
1188     //! builds matrix from comma initializer
1189     template<typename _Tp> explicit UMat(const MatCommaInitializer_<_Tp>& commaInitializer);
1190
1191     //! destructor - calls release()
1192     ~UMat();
1193     //! assignment operators
1194     UMat& operator = (const UMat& m);
1195
1196     Mat getMat(int flags) const;
1197
1198     //! returns a new matrix header for the specified row
1199     UMat row(int y) const;
1200     //! returns a new matrix header for the specified column
1201     UMat col(int x) const;
1202     //! ... for the specified row span
1203     UMat rowRange(int startrow, int endrow) const;
1204     UMat rowRange(const Range& r) const;
1205     //! ... for the specified column span
1206     UMat colRange(int startcol, int endcol) const;
1207     UMat colRange(const Range& r) const;
1208     //! ... for the specified diagonal
1209     // (d=0 - the main diagonal,
1210     //  >0 - a diagonal from the lower half,
1211     //  <0 - a diagonal from the upper half)
1212     UMat diag(int d=0) const;
1213     //! constructs a square diagonal matrix which main diagonal is vector "d"
1214     static UMat diag(const UMat& d);
1215
1216     //! returns deep copy of the matrix, i.e. the data is copied
1217     UMat clone() const;
1218     //! copies the matrix content to "m".
1219     // It calls m.create(this->size(), this->type()).
1220     void copyTo( OutputArray m ) const;
1221     //! copies those matrix elements to "m" that are marked with non-zero mask elements.
1222     void copyTo( OutputArray m, InputArray mask ) const;
1223     //! converts matrix to another datatype with optional scalng. See cvConvertScale.
1224     void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
1225
1226     void assignTo( UMat& m, int type=-1 ) const;
1227
1228     //! sets every matrix element to s
1229     UMat& operator = (const Scalar& s);
1230     //! sets some of the matrix elements to s, according to the mask
1231     UMat& setTo(InputArray value, InputArray mask=noArray());
1232     //! creates alternative matrix header for the same data, with different
1233     // number of channels and/or different number of rows. see cvReshape.
1234     UMat reshape(int cn, int rows=0) const;
1235     UMat reshape(int cn, int newndims, const int* newsz) const;
1236
1237     //! matrix transposition by means of matrix expressions
1238     UMat t() const;
1239     //! matrix inversion by means of matrix expressions
1240     UMat inv(int method=DECOMP_LU) const;
1241     //! per-element matrix multiplication by means of matrix expressions
1242     UMat mul(InputArray m, double scale=1) const;
1243
1244     //! computes dot-product
1245     double dot(InputArray m) const;
1246
1247     //! Matlab-style matrix initialization
1248     static UMat zeros(int rows, int cols, int type);
1249     static UMat zeros(Size size, int type);
1250     static UMat zeros(int ndims, const int* sz, int type);
1251     static UMat ones(int rows, int cols, int type);
1252     static UMat ones(Size size, int type);
1253     static UMat ones(int ndims, const int* sz, int type);
1254     static UMat eye(int rows, int cols, int type);
1255     static UMat eye(Size size, int type);
1256
1257     //! allocates new matrix data unless the matrix already has specified size and type.
1258     // previous data is unreferenced if needed.
1259     void create(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1260     void create(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1261     void create(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1262
1263     //! increases the reference counter; use with care to avoid memleaks
1264     void addref();
1265     //! decreases reference counter;
1266     // deallocates the data when reference counter reaches 0.
1267     void release();
1268
1269     //! deallocates the matrix data
1270     void deallocate();
1271     //! internal use function; properly re-allocates _size, _step arrays
1272     void copySize(const UMat& m);
1273
1274     //! locates matrix header within a parent matrix. See below
1275     void locateROI( Size& wholeSize, Point& ofs ) const;
1276     //! moves/resizes the current matrix ROI inside the parent matrix.
1277     UMat& adjustROI( int dtop, int dbottom, int dleft, int dright );
1278     //! extracts a rectangular sub-matrix
1279     // (this is a generalized form of row, rowRange etc.)
1280     UMat operator()( Range rowRange, Range colRange ) const;
1281     UMat operator()( const Rect& roi ) const;
1282     UMat operator()( const Range* ranges ) const;
1283
1284     //! returns true iff the matrix data is continuous
1285     // (i.e. when there are no gaps between successive rows).
1286     // similar to CV_IS_MAT_CONT(cvmat->type)
1287     bool isContinuous() const;
1288
1289     //! returns true if the matrix is a submatrix of another matrix
1290     bool isSubmatrix() const;
1291
1292     //! returns element size in bytes,
1293     // similar to CV_ELEM_SIZE(cvmat->type)
1294     size_t elemSize() const;
1295     //! returns the size of element channel in bytes.
1296     size_t elemSize1() const;
1297     //! returns element type, similar to CV_MAT_TYPE(cvmat->type)
1298     int type() const;
1299     //! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
1300     int depth() const;
1301     //! returns element type, similar to CV_MAT_CN(cvmat->type)
1302     int channels() const;
1303     //! returns step/elemSize1()
1304     size_t step1(int i=0) const;
1305     //! returns true if matrix data is NULL
1306     bool empty() const;
1307     //! returns the total number of matrix elements
1308     size_t total() const;
1309
1310     //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
1311     int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
1312
1313     void* handle(int accessFlags) const;
1314     void ndoffset(size_t* ofs) const;
1315
1316     enum { MAGIC_VAL  = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
1317     enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
1318
1319     /*! includes several bit-fields:
1320          - the magic signature
1321          - continuity flag
1322          - depth
1323          - number of channels
1324      */
1325     int flags;
1326     //! the matrix dimensionality, >= 2
1327     int dims;
1328     //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
1329     int rows, cols;
1330
1331     //! custom allocator
1332     MatAllocator* allocator;
1333     UMatUsageFlags usageFlags; // usage flags for allocator
1334     //! and the standard allocator
1335     static MatAllocator* getStdAllocator();
1336
1337     // black-box container of UMat data
1338     UMatData* u;
1339
1340     // offset of the submatrix (or 0)
1341     size_t offset;
1342
1343     MatSize size;
1344     MatStep step;
1345
1346 protected:
1347 };
1348
1349
1350 /////////////////////////// multi-dimensional sparse matrix //////////////////////////
1351
1352 /*!
1353  Sparse matrix class.
1354
1355  The class represents multi-dimensional sparse numerical arrays. Such a sparse array can store elements
1356  of any type that cv::Mat is able to store. "Sparse" means that only non-zero elements
1357  are stored (though, as a result of some operations on a sparse matrix, some of its stored elements
1358  can actually become 0. It's user responsibility to detect such elements and delete them using cv::SparseMat::erase().
1359  The non-zero elements are stored in a hash table that grows when it's filled enough,
1360  so that the search time remains O(1) in average. Elements can be accessed using the following methods:
1361
1362  <ol>
1363  <li>Query operations: cv::SparseMat::ptr() and the higher-level cv::SparseMat::ref(),
1364       cv::SparseMat::value() and cv::SparseMat::find, for example:
1365  \code
1366  const int dims = 5;
1367  int size[] = {10, 10, 10, 10, 10};
1368  SparseMat sparse_mat(dims, size, CV_32F);
1369  for(int i = 0; i < 1000; i++)
1370  {
1371      int idx[dims];
1372      for(int k = 0; k < dims; k++)
1373         idx[k] = rand()%sparse_mat.size(k);
1374      sparse_mat.ref<float>(idx) += 1.f;
1375  }
1376  \endcode
1377
1378  <li>Sparse matrix iterators. Like cv::Mat iterators and unlike cv::Mat iterators, the sparse matrix iterators are STL-style,
1379  that is, the iteration is done as following:
1380  \code
1381  // prints elements of a sparse floating-point matrix and the sum of elements.
1382  SparseMatConstIterator_<float>
1383         it = sparse_mat.begin<float>(),
1384         it_end = sparse_mat.end<float>();
1385  double s = 0;
1386  int dims = sparse_mat.dims();
1387  for(; it != it_end; ++it)
1388  {
1389      // print element indices and the element value
1390      const Node* n = it.node();
1391      printf("(")
1392      for(int i = 0; i < dims; i++)
1393         printf("%3d%c", n->idx[i], i < dims-1 ? ',' : ')');
1394      printf(": %f\n", *it);
1395      s += *it;
1396  }
1397  printf("Element sum is %g\n", s);
1398  \endcode
1399  If you run this loop, you will notice that elements are enumerated
1400  in no any logical order (lexicographical etc.),
1401  they come in the same order as they stored in the hash table, i.e. semi-randomly.
1402
1403  You may collect pointers to the nodes and sort them to get the proper ordering.
1404  Note, however, that pointers to the nodes may become invalid when you add more
1405  elements to the matrix; this is because of possible buffer reallocation.
1406
1407  <li>A combination of the above 2 methods when you need to process 2 or more sparse
1408  matrices simultaneously, e.g. this is how you can compute unnormalized
1409  cross-correlation of the 2 floating-point sparse matrices:
1410  \code
1411  double crossCorr(const SparseMat& a, const SparseMat& b)
1412  {
1413      const SparseMat *_a = &a, *_b = &b;
1414      // if b contains less elements than a,
1415      // it's faster to iterate through b
1416      if(_a->nzcount() > _b->nzcount())
1417         std::swap(_a, _b);
1418      SparseMatConstIterator_<float> it = _a->begin<float>(),
1419                                     it_end = _a->end<float>();
1420      double ccorr = 0;
1421      for(; it != it_end; ++it)
1422      {
1423          // take the next element from the first matrix
1424          float avalue = *it;
1425          const Node* anode = it.node();
1426          // and try to find element with the same index in the second matrix.
1427          // since the hash value depends only on the element index,
1428          // we reuse hashvalue stored in the node
1429          float bvalue = _b->value<float>(anode->idx,&anode->hashval);
1430          ccorr += avalue*bvalue;
1431      }
1432      return ccorr;
1433  }
1434  \endcode
1435  </ol>
1436 */
1437 class CV_EXPORTS SparseMat
1438 {
1439 public:
1440     typedef SparseMatIterator iterator;
1441     typedef SparseMatConstIterator const_iterator;
1442
1443     enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 };
1444
1445     //! the sparse matrix header
1446     struct CV_EXPORTS Hdr
1447     {
1448         Hdr(int _dims, const int* _sizes, int _type);
1449         void clear();
1450         int refcount;
1451         int dims;
1452         int valueOffset;
1453         size_t nodeSize;
1454         size_t nodeCount;
1455         size_t freeList;
1456         std::vector<uchar> pool;
1457         std::vector<size_t> hashtab;
1458         int size[MAX_DIM];
1459     };
1460
1461     //! sparse matrix node - element of a hash table
1462     struct CV_EXPORTS Node
1463     {
1464         //! hash value
1465         size_t hashval;
1466         //! index of the next node in the same hash table entry
1467         size_t next;
1468         //! index of the matrix element
1469         int idx[MAX_DIM];
1470     };
1471
1472     //! default constructor
1473     SparseMat();
1474     //! creates matrix of the specified size and type
1475     SparseMat(int dims, const int* _sizes, int _type);
1476     //! copy constructor
1477     SparseMat(const SparseMat& m);
1478     //! converts dense 2d matrix to the sparse form
1479     /*!
1480      \param m the input matrix
1481     */
1482     explicit SparseMat(const Mat& m);
1483     //! converts old-style sparse matrix to the new-style. All the data is copied
1484     //SparseMat(const CvSparseMat* m);
1485     //! the destructor
1486     ~SparseMat();
1487
1488     //! assignment operator. This is O(1) operation, i.e. no data is copied
1489     SparseMat& operator = (const SparseMat& m);
1490     //! equivalent to the corresponding constructor
1491     SparseMat& operator = (const Mat& m);
1492
1493     //! creates full copy of the matrix
1494     SparseMat clone() const;
1495
1496     //! copies all the data to the destination matrix. All the previous content of m is erased
1497     void copyTo( SparseMat& m ) const;
1498     //! converts sparse matrix to dense matrix.
1499     void copyTo( Mat& m ) const;
1500     //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type
1501     void convertTo( SparseMat& m, int rtype, double alpha=1 ) const;
1502     //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling.
1503     /*!
1504       \param rtype The output matrix data type. When it is =-1, the output array will have the same data type as (*this)
1505       \param alpha The scale factor
1506       \param beta The optional delta added to the scaled values before the conversion
1507     */
1508     void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
1509
1510     // not used now
1511     void assignTo( SparseMat& m, int type=-1 ) const;
1512
1513     //! reallocates sparse matrix.
1514     /*!
1515         If the matrix already had the proper size and type,
1516         it is simply cleared with clear(), otherwise,
1517         the old matrix is released (using release()) and the new one is allocated.
1518     */
1519     void create(int dims, const int* _sizes, int _type);
1520     //! sets all the sparse matrix elements to 0, which means clearing the hash table.
1521     void clear();
1522     //! manually increments the reference counter to the header.
1523     void addref();
1524     // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated.
1525     void release();
1526
1527     //! converts sparse matrix to the old-style representation; all the elements are copied.
1528     //operator CvSparseMat*() const;
1529     //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements)
1530     size_t elemSize() const;
1531     //! returns elemSize()/channels()
1532     size_t elemSize1() const;
1533
1534     //! returns type of sparse matrix elements
1535     int type() const;
1536     //! returns the depth of sparse matrix elements
1537     int depth() const;
1538     //! returns the number of channels
1539     int channels() const;
1540
1541     //! returns the array of sizes, or NULL if the matrix is not allocated
1542     const int* size() const;
1543     //! returns the size of i-th matrix dimension (or 0)
1544     int size(int i) const;
1545     //! returns the matrix dimensionality
1546     int dims() const;
1547     //! returns the number of non-zero elements (=the number of hash table nodes)
1548     size_t nzcount() const;
1549
1550     //! computes the element hash value (1D case)
1551     size_t hash(int i0) const;
1552     //! computes the element hash value (2D case)
1553     size_t hash(int i0, int i1) const;
1554     //! computes the element hash value (3D case)
1555     size_t hash(int i0, int i1, int i2) const;
1556     //! computes the element hash value (nD case)
1557     size_t hash(const int* idx) const;
1558
1559     //@{
1560     /*!
1561      specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case.
1562
1563      return pointer to the matrix element.
1564      <ul>
1565       <li>if the element is there (it's non-zero), the pointer to it is returned
1566       <li>if it's not there and createMissing=false, NULL pointer is returned
1567       <li>if it's not there and createMissing=true, then the new element
1568         is created and initialized with 0. Pointer to it is returned
1569       <li>if the optional hashval pointer is not NULL, the element hash value is
1570       not computed, but *hashval is taken instead.
1571      </ul>
1572     */
1573     //! returns pointer to the specified element (1D case)
1574     uchar* ptr(int i0, bool createMissing, size_t* hashval=0);
1575     //! returns pointer to the specified element (2D case)
1576     uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0);
1577     //! returns pointer to the specified element (3D case)
1578     uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0);
1579     //! returns pointer to the specified element (nD case)
1580     uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0);
1581     //@}
1582
1583     //@{
1584     /*!
1585      return read-write reference to the specified sparse matrix element.
1586
1587      ref<_Tp>(i0,...[,hashval]) is equivalent to *(_Tp*)ptr(i0,...,true[,hashval]).
1588      The methods always return a valid reference.
1589      If the element did not exist, it is created and initialiazed with 0.
1590     */
1591     //! returns reference to the specified element (1D case)
1592     template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0);
1593     //! returns reference to the specified element (2D case)
1594     template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0);
1595     //! returns reference to the specified element (3D case)
1596     template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
1597     //! returns reference to the specified element (nD case)
1598     template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0);
1599     //@}
1600
1601     //@{
1602     /*!
1603      return value of the specified sparse matrix element.
1604
1605      value<_Tp>(i0,...[,hashval]) is equivalent
1606
1607      \code
1608      { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); }
1609      \endcode
1610
1611      That is, if the element did not exist, the methods return 0.
1612      */
1613     //! returns value of the specified element (1D case)
1614     template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const;
1615     //! returns value of the specified element (2D case)
1616     template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const;
1617     //! returns value of the specified element (3D case)
1618     template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0) const;
1619     //! returns value of the specified element (nD case)
1620     template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const;
1621     //@}
1622
1623     //@{
1624     /*!
1625      Return pointer to the specified sparse matrix element if it exists
1626
1627      find<_Tp>(i0,...[,hashval]) is equivalent to (_const Tp*)ptr(i0,...false[,hashval]).
1628
1629      If the specified element does not exist, the methods return NULL.
1630     */
1631     //! returns pointer to the specified element (1D case)
1632     template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const;
1633     //! returns pointer to the specified element (2D case)
1634     template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0) const;
1635     //! returns pointer to the specified element (3D case)
1636     template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const;
1637     //! returns pointer to the specified element (nD case)
1638     template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0) const;
1639
1640     //! erases the specified element (2D case)
1641     void erase(int i0, int i1, size_t* hashval=0);
1642     //! erases the specified element (3D case)
1643     void erase(int i0, int i1, int i2, size_t* hashval=0);
1644     //! erases the specified element (nD case)
1645     void erase(const int* idx, size_t* hashval=0);
1646
1647     //@{
1648     /*!
1649        return the sparse matrix iterator pointing to the first sparse matrix element
1650     */
1651     //! returns the sparse matrix iterator at the matrix beginning
1652     SparseMatIterator begin();
1653     //! returns the sparse matrix iterator at the matrix beginning
1654     template<typename _Tp> SparseMatIterator_<_Tp> begin();
1655     //! returns the read-only sparse matrix iterator at the matrix beginning
1656     SparseMatConstIterator begin() const;
1657     //! returns the read-only sparse matrix iterator at the matrix beginning
1658     template<typename _Tp> SparseMatConstIterator_<_Tp> begin() const;
1659     //@}
1660     /*!
1661        return the sparse matrix iterator pointing to the element following the last sparse matrix element
1662     */
1663     //! returns the sparse matrix iterator at the matrix end
1664     SparseMatIterator end();
1665     //! returns the read-only sparse matrix iterator at the matrix end
1666     SparseMatConstIterator end() const;
1667     //! returns the typed sparse matrix iterator at the matrix end
1668     template<typename _Tp> SparseMatIterator_<_Tp> end();
1669     //! returns the typed read-only sparse matrix iterator at the matrix end
1670     template<typename _Tp> SparseMatConstIterator_<_Tp> end() const;
1671
1672     //! returns the value stored in the sparse martix node
1673     template<typename _Tp> _Tp& value(Node* n);
1674     //! returns the value stored in the sparse martix node
1675     template<typename _Tp> const _Tp& value(const Node* n) const;
1676
1677     ////////////// some internal-use methods ///////////////
1678     Node* node(size_t nidx);
1679     const Node* node(size_t nidx) const;
1680
1681     uchar* newNode(const int* idx, size_t hashval);
1682     void removeNode(size_t hidx, size_t nidx, size_t previdx);
1683     void resizeHashTab(size_t newsize);
1684
1685     int flags;
1686     Hdr* hdr;
1687 };
1688
1689
1690
1691 ///////////////////////////////// SparseMat_<_Tp> ////////////////////////////////////
1692
1693 /*!
1694  The Template Sparse Matrix class derived from cv::SparseMat
1695
1696  The class provides slightly more convenient operations for accessing elements.
1697
1698  \code
1699  SparseMat m;
1700  ...
1701  SparseMat_<int> m_ = (SparseMat_<int>&)m;
1702  m_.ref(1)++; // equivalent to m.ref<int>(1)++;
1703  m_.ref(2) += m_(3); // equivalent to m.ref<int>(2) += m.value<int>(3);
1704  \endcode
1705 */
1706 template<typename _Tp> class SparseMat_ : public SparseMat
1707 {
1708 public:
1709     typedef SparseMatIterator_<_Tp> iterator;
1710     typedef SparseMatConstIterator_<_Tp> const_iterator;
1711
1712     //! the default constructor
1713     SparseMat_();
1714     //! the full constructor equivelent to SparseMat(dims, _sizes, DataType<_Tp>::type)
1715     SparseMat_(int dims, const int* _sizes);
1716     //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted
1717     SparseMat_(const SparseMat& m);
1718     //! the copy constructor. This is O(1) operation - no data is copied
1719     SparseMat_(const SparseMat_& m);
1720     //! converts dense matrix to the sparse form
1721     SparseMat_(const Mat& m);
1722     //! converts the old-style sparse matrix to the C++ class. All the elements are copied
1723     //SparseMat_(const CvSparseMat* m);
1724     //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted
1725     SparseMat_& operator = (const SparseMat& m);
1726     //! the assignment operator. This is O(1) operation - no data is copied
1727     SparseMat_& operator = (const SparseMat_& m);
1728     //! converts dense matrix to the sparse form
1729     SparseMat_& operator = (const Mat& m);
1730
1731     //! makes full copy of the matrix. All the elements are duplicated
1732     SparseMat_ clone() const;
1733     //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type)
1734     void create(int dims, const int* _sizes);
1735     //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied
1736     //operator CvSparseMat*() const;
1737
1738     //! returns type of the matrix elements
1739     int type() const;
1740     //! returns depth of the matrix elements
1741     int depth() const;
1742     //! returns the number of channels in each matrix element
1743     int channels() const;
1744
1745     //! equivalent to SparseMat::ref<_Tp>(i0, hashval)
1746     _Tp& ref(int i0, size_t* hashval=0);
1747     //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval)
1748     _Tp& ref(int i0, int i1, size_t* hashval=0);
1749     //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval)
1750     _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
1751     //! equivalent to SparseMat::ref<_Tp>(idx, hashval)
1752     _Tp& ref(const int* idx, size_t* hashval=0);
1753
1754     //! equivalent to SparseMat::value<_Tp>(i0, hashval)
1755     _Tp operator()(int i0, size_t* hashval=0) const;
1756     //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval)
1757     _Tp operator()(int i0, int i1, size_t* hashval=0) const;
1758     //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval)
1759     _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const;
1760     //! equivalent to SparseMat::value<_Tp>(idx, hashval)
1761     _Tp operator()(const int* idx, size_t* hashval=0) const;
1762
1763     //! returns sparse matrix iterator pointing to the first sparse matrix element
1764     SparseMatIterator_<_Tp> begin();
1765     //! returns read-only sparse matrix iterator pointing to the first sparse matrix element
1766     SparseMatConstIterator_<_Tp> begin() const;
1767     //! returns sparse matrix iterator pointing to the element following the last sparse matrix element
1768     SparseMatIterator_<_Tp> end();
1769     //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element
1770     SparseMatConstIterator_<_Tp> end() const;
1771 };
1772
1773
1774
1775 ////////////////////////////////// MatConstIterator //////////////////////////////////
1776
1777 class CV_EXPORTS MatConstIterator
1778 {
1779 public:
1780     typedef uchar* value_type;
1781     typedef ptrdiff_t difference_type;
1782     typedef const uchar** pointer;
1783     typedef uchar* reference;
1784
1785 #ifndef OPENCV_NOSTL
1786     typedef std::random_access_iterator_tag iterator_category;
1787 #endif
1788
1789     //! default constructor
1790     MatConstIterator();
1791     //! constructor that sets the iterator to the beginning of the matrix
1792     MatConstIterator(const Mat* _m);
1793     //! constructor that sets the iterator to the specified element of the matrix
1794     MatConstIterator(const Mat* _m, int _row, int _col=0);
1795     //! constructor that sets the iterator to the specified element of the matrix
1796     MatConstIterator(const Mat* _m, Point _pt);
1797     //! constructor that sets the iterator to the specified element of the matrix
1798     MatConstIterator(const Mat* _m, const int* _idx);
1799     //! copy constructor
1800     MatConstIterator(const MatConstIterator& it);
1801
1802     //! copy operator
1803     MatConstIterator& operator = (const MatConstIterator& it);
1804     //! returns the current matrix element
1805     uchar* operator *() const;
1806     //! returns the i-th matrix element, relative to the current
1807     uchar* operator [](ptrdiff_t i) const;
1808
1809     //! shifts the iterator forward by the specified number of elements
1810     MatConstIterator& operator += (ptrdiff_t ofs);
1811     //! shifts the iterator backward by the specified number of elements
1812     MatConstIterator& operator -= (ptrdiff_t ofs);
1813     //! decrements the iterator
1814     MatConstIterator& operator --();
1815     //! decrements the iterator
1816     MatConstIterator operator --(int);
1817     //! increments the iterator
1818     MatConstIterator& operator ++();
1819     //! increments the iterator
1820     MatConstIterator operator ++(int);
1821     //! returns the current iterator position
1822     Point pos() const;
1823     //! returns the current iterator position
1824     void pos(int* _idx) const;
1825
1826     ptrdiff_t lpos() const;
1827     void seek(ptrdiff_t ofs, bool relative = false);
1828     void seek(const int* _idx, bool relative = false);
1829
1830     const Mat* m;
1831     size_t elemSize;
1832     uchar* ptr;
1833     uchar* sliceStart;
1834     uchar* sliceEnd;
1835 };
1836
1837
1838
1839 ////////////////////////////////// MatConstIterator_ /////////////////////////////////
1840
1841 /*!
1842  Matrix read-only iterator
1843  */
1844 template<typename _Tp>
1845 class MatConstIterator_ : public MatConstIterator
1846 {
1847 public:
1848     typedef _Tp value_type;
1849     typedef ptrdiff_t difference_type;
1850     typedef const _Tp* pointer;
1851     typedef const _Tp& reference;
1852
1853 #ifndef OPENCV_NOSTL
1854     typedef std::random_access_iterator_tag iterator_category;
1855 #endif
1856
1857     //! default constructor
1858     MatConstIterator_();
1859     //! constructor that sets the iterator to the beginning of the matrix
1860     MatConstIterator_(const Mat_<_Tp>* _m);
1861     //! constructor that sets the iterator to the specified element of the matrix
1862     MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0);
1863     //! constructor that sets the iterator to the specified element of the matrix
1864     MatConstIterator_(const Mat_<_Tp>* _m, Point _pt);
1865     //! constructor that sets the iterator to the specified element of the matrix
1866     MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx);
1867     //! copy constructor
1868     MatConstIterator_(const MatConstIterator_& it);
1869
1870     //! copy operator
1871     MatConstIterator_& operator = (const MatConstIterator_& it);
1872     //! returns the current matrix element
1873     _Tp operator *() const;
1874     //! returns the i-th matrix element, relative to the current
1875     _Tp operator [](ptrdiff_t i) const;
1876
1877     //! shifts the iterator forward by the specified number of elements
1878     MatConstIterator_& operator += (ptrdiff_t ofs);
1879     //! shifts the iterator backward by the specified number of elements
1880     MatConstIterator_& operator -= (ptrdiff_t ofs);
1881     //! decrements the iterator
1882     MatConstIterator_& operator --();
1883     //! decrements the iterator
1884     MatConstIterator_ operator --(int);
1885     //! increments the iterator
1886     MatConstIterator_& operator ++();
1887     //! increments the iterator
1888     MatConstIterator_ operator ++(int);
1889     //! returns the current iterator position
1890     Point pos() const;
1891 };
1892
1893
1894
1895 //////////////////////////////////// MatIterator_ ////////////////////////////////////
1896
1897 /*!
1898  Matrix read-write iterator
1899 */
1900 template<typename _Tp>
1901 class MatIterator_ : public MatConstIterator_<_Tp>
1902 {
1903 public:
1904     typedef _Tp* pointer;
1905     typedef _Tp& reference;
1906
1907 #ifndef OPENCV_NOSTL
1908     typedef std::random_access_iterator_tag iterator_category;
1909 #endif
1910
1911     //! the default constructor
1912     MatIterator_();
1913     //! constructor that sets the iterator to the beginning of the matrix
1914     MatIterator_(Mat_<_Tp>* _m);
1915     //! constructor that sets the iterator to the specified element of the matrix
1916     MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0);
1917     //! constructor that sets the iterator to the specified element of the matrix
1918     MatIterator_(const Mat_<_Tp>* _m, Point _pt);
1919     //! constructor that sets the iterator to the specified element of the matrix
1920     MatIterator_(const Mat_<_Tp>* _m, const int* _idx);
1921     //! copy constructor
1922     MatIterator_(const MatIterator_& it);
1923     //! copy operator
1924     MatIterator_& operator = (const MatIterator_<_Tp>& it );
1925
1926     //! returns the current matrix element
1927     _Tp& operator *() const;
1928     //! returns the i-th matrix element, relative to the current
1929     _Tp& operator [](ptrdiff_t i) const;
1930
1931     //! shifts the iterator forward by the specified number of elements
1932     MatIterator_& operator += (ptrdiff_t ofs);
1933     //! shifts the iterator backward by the specified number of elements
1934     MatIterator_& operator -= (ptrdiff_t ofs);
1935     //! decrements the iterator
1936     MatIterator_& operator --();
1937     //! decrements the iterator
1938     MatIterator_ operator --(int);
1939     //! increments the iterator
1940     MatIterator_& operator ++();
1941     //! increments the iterator
1942     MatIterator_ operator ++(int);
1943 };
1944
1945
1946
1947 /////////////////////////////// SparseMatConstIterator ///////////////////////////////
1948
1949 /*!
1950  Read-Only Sparse Matrix Iterator.
1951  Here is how to use the iterator to compute the sum of floating-point sparse matrix elements:
1952
1953  \code
1954  SparseMatConstIterator it = m.begin(), it_end = m.end();
1955  double s = 0;
1956  CV_Assert( m.type() == CV_32F );
1957  for( ; it != it_end; ++it )
1958     s += it.value<float>();
1959  \endcode
1960 */
1961 class CV_EXPORTS SparseMatConstIterator
1962 {
1963 public:
1964     //! the default constructor
1965     SparseMatConstIterator();
1966     //! the full constructor setting the iterator to the first sparse matrix element
1967     SparseMatConstIterator(const SparseMat* _m);
1968     //! the copy constructor
1969     SparseMatConstIterator(const SparseMatConstIterator& it);
1970
1971     //! the assignment operator
1972     SparseMatConstIterator& operator = (const SparseMatConstIterator& it);
1973
1974     //! template method returning the current matrix element
1975     template<typename _Tp> const _Tp& value() const;
1976     //! returns the current node of the sparse matrix. it.node->idx is the current element index
1977     const SparseMat::Node* node() const;
1978
1979     //! moves iterator to the previous element
1980     SparseMatConstIterator& operator --();
1981     //! moves iterator to the previous element
1982     SparseMatConstIterator operator --(int);
1983     //! moves iterator to the next element
1984     SparseMatConstIterator& operator ++();
1985     //! moves iterator to the next element
1986     SparseMatConstIterator operator ++(int);
1987
1988     //! moves iterator to the element after the last element
1989     void seekEnd();
1990
1991     const SparseMat* m;
1992     size_t hashidx;
1993     uchar* ptr;
1994 };
1995
1996
1997
1998 ////////////////////////////////// SparseMatIterator /////////////////////////////////
1999
2000 /*!
2001  Read-write Sparse Matrix Iterator
2002
2003  The class is similar to cv::SparseMatConstIterator,
2004  but can be used for in-place modification of the matrix elements.
2005 */
2006 class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator
2007 {
2008 public:
2009     //! the default constructor
2010     SparseMatIterator();
2011     //! the full constructor setting the iterator to the first sparse matrix element
2012     SparseMatIterator(SparseMat* _m);
2013     //! the full constructor setting the iterator to the specified sparse matrix element
2014     SparseMatIterator(SparseMat* _m, const int* idx);
2015     //! the copy constructor
2016     SparseMatIterator(const SparseMatIterator& it);
2017
2018     //! the assignment operator
2019     SparseMatIterator& operator = (const SparseMatIterator& it);
2020     //! returns read-write reference to the current sparse matrix element
2021     template<typename _Tp> _Tp& value() const;
2022     //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!)
2023     SparseMat::Node* node() const;
2024
2025     //! moves iterator to the next element
2026     SparseMatIterator& operator ++();
2027     //! moves iterator to the next element
2028     SparseMatIterator operator ++(int);
2029 };
2030
2031
2032
2033 /////////////////////////////// SparseMatConstIterator_ //////////////////////////////
2034
2035 /*!
2036  Template Read-Only Sparse Matrix Iterator Class.
2037
2038  This is the derived from SparseMatConstIterator class that
2039  introduces more convenient operator *() for accessing the current element.
2040 */
2041 template<typename _Tp> class SparseMatConstIterator_ : public SparseMatConstIterator
2042 {
2043 public:
2044
2045 #ifndef OPENCV_NOSTL
2046     typedef std::forward_iterator_tag iterator_category;
2047 #endif
2048
2049     //! the default constructor
2050     SparseMatConstIterator_();
2051     //! the full constructor setting the iterator to the first sparse matrix element
2052     SparseMatConstIterator_(const SparseMat_<_Tp>* _m);
2053     SparseMatConstIterator_(const SparseMat* _m);
2054     //! the copy constructor
2055     SparseMatConstIterator_(const SparseMatConstIterator_& it);
2056
2057     //! the assignment operator
2058     SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it);
2059     //! the element access operator
2060     const _Tp& operator *() const;
2061
2062     //! moves iterator to the next element
2063     SparseMatConstIterator_& operator ++();
2064     //! moves iterator to the next element
2065     SparseMatConstIterator_ operator ++(int);
2066 };
2067
2068
2069
2070 ///////////////////////////////// SparseMatIterator_ /////////////////////////////////
2071
2072 /*!
2073  Template Read-Write Sparse Matrix Iterator Class.
2074
2075  This is the derived from cv::SparseMatConstIterator_ class that
2076  introduces more convenient operator *() for accessing the current element.
2077 */
2078 template<typename _Tp> class SparseMatIterator_ : public SparseMatConstIterator_<_Tp>
2079 {
2080 public:
2081
2082 #ifndef OPENCV_NOSTL
2083     typedef std::forward_iterator_tag iterator_category;
2084 #endif
2085
2086     //! the default constructor
2087     SparseMatIterator_();
2088     //! the full constructor setting the iterator to the first sparse matrix element
2089     SparseMatIterator_(SparseMat_<_Tp>* _m);
2090     SparseMatIterator_(SparseMat* _m);
2091     //! the copy constructor
2092     SparseMatIterator_(const SparseMatIterator_& it);
2093
2094     //! the assignment operator
2095     SparseMatIterator_& operator = (const SparseMatIterator_& it);
2096     //! returns the reference to the current element
2097     _Tp& operator *() const;
2098
2099     //! moves the iterator to the next element
2100     SparseMatIterator_& operator ++();
2101     //! moves the iterator to the next element
2102     SparseMatIterator_ operator ++(int);
2103 };
2104
2105
2106
2107 /////////////////////////////////// NAryMatIterator //////////////////////////////////
2108
2109 /*!
2110  n-Dimensional Dense Matrix Iterator Class.
2111
2112  The class cv::NAryMatIterator is used for iterating over one or more n-dimensional dense arrays (cv::Mat's).
2113
2114  The iterator is completely different from cv::Mat_ and cv::SparseMat_ iterators.
2115  It iterates through the slices (or planes), not the elements, where "slice" is a continuous part of the arrays.
2116
2117  Here is the example on how the iterator can be used to normalize 3D histogram:
2118
2119  \code
2120  void normalizeColorHist(Mat& hist)
2121  {
2122  #if 1
2123      // intialize iterator (the style is different from STL).
2124      // after initialization the iterator will contain
2125      // the number of slices or planes
2126      // the iterator will go through
2127      Mat* arrays[] = { &hist, 0 };
2128      Mat planes[1];
2129      NAryMatIterator it(arrays, planes);
2130      double s = 0;
2131      // iterate through the matrix. on each iteration
2132      // it.planes[i] (of type Mat) will be set to the current plane of
2133      // i-th n-dim matrix passed to the iterator constructor.
2134      for(int p = 0; p < it.nplanes; p++, ++it)
2135         s += sum(it.planes[0])[0];
2136      it = NAryMatIterator(hist);
2137      s = 1./s;
2138      for(int p = 0; p < it.nplanes; p++, ++it)
2139         it.planes[0] *= s;
2140  #elif 1
2141      // this is a shorter implementation of the above
2142      // using built-in operations on Mat
2143      double s = sum(hist)[0];
2144      hist.convertTo(hist, hist.type(), 1./s, 0);
2145  #else
2146      // and this is even shorter one
2147      // (assuming that the histogram elements are non-negative)
2148      normalize(hist, hist, 1, 0, NORM_L1);
2149  #endif
2150  }
2151  \endcode
2152
2153  You can iterate through several matrices simultaneously as long as they have the same geometry
2154  (dimensionality and all the dimension sizes are the same), which is useful for binary
2155  and n-ary operations on such matrices. Just pass those matrices to cv::MatNDIterator.
2156  Then, during the iteration it.planes[0], it.planes[1], ... will
2157  be the slices of the corresponding matrices
2158 */
2159 class CV_EXPORTS NAryMatIterator
2160 {
2161 public:
2162     //! the default constructor
2163     NAryMatIterator();
2164     //! the full constructor taking arbitrary number of n-dim matrices
2165     NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1);
2166     //! the full constructor taking arbitrary number of n-dim matrices
2167     NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1);
2168     //! the separate iterator initialization method
2169     void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1);
2170
2171     //! proceeds to the next plane of every iterated matrix
2172     NAryMatIterator& operator ++();
2173     //! proceeds to the next plane of every iterated matrix (postfix increment operator)
2174     NAryMatIterator operator ++(int);
2175
2176     //! the iterated arrays
2177     const Mat** arrays;
2178     //! the current planes
2179     Mat* planes;
2180     //! data pointers
2181     uchar** ptrs;
2182     //! the number of arrays
2183     int narrays;
2184     //! the number of hyper-planes that the iterator steps through
2185     size_t nplanes;
2186     //! the size of each segment (in elements)
2187     size_t size;
2188 protected:
2189     int iterdepth;
2190     size_t idx;
2191 };
2192
2193
2194
2195 ///////////////////////////////// Matrix Expressions /////////////////////////////////
2196
2197 class CV_EXPORTS MatOp
2198 {
2199 public:
2200     MatOp();
2201     virtual ~MatOp();
2202
2203     virtual bool elementWise(const MatExpr& expr) const;
2204     virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0;
2205     virtual void roi(const MatExpr& expr, const Range& rowRange,
2206                      const Range& colRange, MatExpr& res) const;
2207     virtual void diag(const MatExpr& expr, int d, MatExpr& res) const;
2208     virtual void augAssignAdd(const MatExpr& expr, Mat& m) const;
2209     virtual void augAssignSubtract(const MatExpr& expr, Mat& m) const;
2210     virtual void augAssignMultiply(const MatExpr& expr, Mat& m) const;
2211     virtual void augAssignDivide(const MatExpr& expr, Mat& m) const;
2212     virtual void augAssignAnd(const MatExpr& expr, Mat& m) const;
2213     virtual void augAssignOr(const MatExpr& expr, Mat& m) const;
2214     virtual void augAssignXor(const MatExpr& expr, Mat& m) const;
2215
2216     virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
2217     virtual void add(const MatExpr& expr1, const Scalar& s, MatExpr& res) const;
2218
2219     virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
2220     virtual void subtract(const Scalar& s, const MatExpr& expr, MatExpr& res) const;
2221
2222     virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
2223     virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const;
2224
2225     virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
2226     virtual void divide(double s, const MatExpr& expr, MatExpr& res) const;
2227
2228     virtual void abs(const MatExpr& expr, MatExpr& res) const;
2229
2230     virtual void transpose(const MatExpr& expr, MatExpr& res) const;
2231     virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
2232     virtual void invert(const MatExpr& expr, int method, MatExpr& res) const;
2233
2234     virtual Size size(const MatExpr& expr) const;
2235     virtual int type(const MatExpr& expr) const;
2236 };
2237
2238
2239 class CV_EXPORTS MatExpr
2240 {
2241 public:
2242     MatExpr();
2243     explicit MatExpr(const Mat& m);
2244
2245     MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(),
2246             const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar& _s = Scalar());
2247
2248     operator Mat() const;
2249     template<typename _Tp> operator Mat_<_Tp>() const;
2250
2251     Size size() const;
2252     int type() const;
2253
2254     MatExpr row(int y) const;
2255     MatExpr col(int x) const;
2256     MatExpr diag(int d = 0) const;
2257     MatExpr operator()( const Range& rowRange, const Range& colRange ) const;
2258     MatExpr operator()( const Rect& roi ) const;
2259
2260     MatExpr t() const;
2261     MatExpr inv(int method = DECOMP_LU) const;
2262     MatExpr mul(const MatExpr& e, double scale=1) const;
2263     MatExpr mul(const Mat& m, double scale=1) const;
2264
2265     Mat cross(const Mat& m) const;
2266     double dot(const Mat& m) const;
2267
2268     const MatOp* op;
2269     int flags;
2270
2271     Mat a, b, c;
2272     double alpha, beta;
2273     Scalar s;
2274 };
2275
2276
2277 CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b);
2278 CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s);
2279 CV_EXPORTS MatExpr operator + (const Scalar& s, const Mat& a);
2280 CV_EXPORTS MatExpr operator + (const MatExpr& e, const Mat& m);
2281 CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e);
2282 CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar& s);
2283 CV_EXPORTS MatExpr operator + (const Scalar& s, const MatExpr& e);
2284 CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2);
2285
2286 CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b);
2287 CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar& s);
2288 CV_EXPORTS MatExpr operator - (const Scalar& s, const Mat& a);
2289 CV_EXPORTS MatExpr operator - (const MatExpr& e, const Mat& m);
2290 CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e);
2291 CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar& s);
2292 CV_EXPORTS MatExpr operator - (const Scalar& s, const MatExpr& e);
2293 CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2);
2294
2295 CV_EXPORTS MatExpr operator - (const Mat& m);
2296 CV_EXPORTS MatExpr operator - (const MatExpr& e);
2297
2298 CV_EXPORTS MatExpr operator * (const Mat& a, const Mat& b);
2299 CV_EXPORTS MatExpr operator * (const Mat& a, double s);
2300 CV_EXPORTS MatExpr operator * (double s, const Mat& a);
2301 CV_EXPORTS MatExpr operator * (const MatExpr& e, const Mat& m);
2302 CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e);
2303 CV_EXPORTS MatExpr operator * (const MatExpr& e, double s);
2304 CV_EXPORTS MatExpr operator * (double s, const MatExpr& e);
2305 CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2);
2306
2307 CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b);
2308 CV_EXPORTS MatExpr operator / (const Mat& a, double s);
2309 CV_EXPORTS MatExpr operator / (double s, const Mat& a);
2310 CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m);
2311 CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e);
2312 CV_EXPORTS MatExpr operator / (const MatExpr& e, double s);
2313 CV_EXPORTS MatExpr operator / (double s, const MatExpr& e);
2314 CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2);
2315
2316 CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b);
2317 CV_EXPORTS MatExpr operator < (const Mat& a, double s);
2318 CV_EXPORTS MatExpr operator < (double s, const Mat& a);
2319
2320 CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b);
2321 CV_EXPORTS MatExpr operator <= (const Mat& a, double s);
2322 CV_EXPORTS MatExpr operator <= (double s, const Mat& a);
2323
2324 CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b);
2325 CV_EXPORTS MatExpr operator == (const Mat& a, double s);
2326 CV_EXPORTS MatExpr operator == (double s, const Mat& a);
2327
2328 CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b);
2329 CV_EXPORTS MatExpr operator != (const Mat& a, double s);
2330 CV_EXPORTS MatExpr operator != (double s, const Mat& a);
2331
2332 CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b);
2333 CV_EXPORTS MatExpr operator >= (const Mat& a, double s);
2334 CV_EXPORTS MatExpr operator >= (double s, const Mat& a);
2335
2336 CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b);
2337 CV_EXPORTS MatExpr operator > (const Mat& a, double s);
2338 CV_EXPORTS MatExpr operator > (double s, const Mat& a);
2339
2340 CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b);
2341 CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s);
2342 CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a);
2343
2344 CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b);
2345 CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar& s);
2346 CV_EXPORTS MatExpr operator | (const Scalar& s, const Mat& a);
2347
2348 CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b);
2349 CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s);
2350 CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a);
2351
2352 CV_EXPORTS MatExpr operator ~(const Mat& m);
2353
2354 CV_EXPORTS MatExpr min(const Mat& a, const Mat& b);
2355 CV_EXPORTS MatExpr min(const Mat& a, double s);
2356 CV_EXPORTS MatExpr min(double s, const Mat& a);
2357
2358 CV_EXPORTS MatExpr max(const Mat& a, const Mat& b);
2359 CV_EXPORTS MatExpr max(const Mat& a, double s);
2360 CV_EXPORTS MatExpr max(double s, const Mat& a);
2361
2362 CV_EXPORTS MatExpr abs(const Mat& m);
2363 CV_EXPORTS MatExpr abs(const MatExpr& e);
2364
2365 } // cv
2366
2367 #include "opencv2/core/mat.inl.hpp"
2368
2369 #endif // __OPENCV_CORE_MAT_HPP__