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