Merge remote-tracking branch 'upstream/3.4' into merge-3.4
[platform/upstream/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 #include <type_traits>
57
58 namespace cv
59 {
60
61 //! @addtogroup core_basic
62 //! @{
63
64 enum AccessFlag { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25,
65     ACCESS_RW=3<<24, ACCESS_MASK=ACCESS_RW, ACCESS_FAST=1<<26 };
66 CV_ENUM_FLAGS(AccessFlag)
67 __CV_ENUM_FLAGS_BITWISE_AND(AccessFlag, int, AccessFlag)
68
69 CV__DEBUG_NS_BEGIN
70
71 class CV_EXPORTS _OutputArray;
72
73 //////////////////////// Input/Output Array Arguments /////////////////////////////////
74
75 /** @brief This is the proxy class for passing read-only input arrays into OpenCV functions.
76
77 It is defined as:
78 @code
79     typedef const _InputArray& InputArray;
80 @endcode
81 where _InputArray is a class that can be constructed from `Mat`, `Mat_<T>`, `Matx<T, m, n>`,
82 `std::vector<T>`, `std::vector<std::vector<T> >`, `std::vector<Mat>`, `std::vector<Mat_<T> >`,
83 `UMat`, `std::vector<UMat>` or `double`. It can also be constructed from a matrix expression.
84
85 Since this is mostly implementation-level class, and its interface may change in future versions, we
86 do not describe it in details. There are a few key things, though, that should be kept in mind:
87
88 -   When you see in the reference manual or in OpenCV source code a function that takes
89     InputArray, it means that you can actually pass `Mat`, `Matx`, `vector<T>` etc. (see above the
90     complete list).
91 -   Optional input arguments: If some of the input arrays may be empty, pass cv::noArray() (or
92     simply cv::Mat() as you probably did before).
93 -   The class is designed solely for passing parameters. That is, normally you *should not*
94     declare class members, local and global variables of this type.
95 -   If you want to design your own function or a class method that can operate of arrays of
96     multiple types, you can use InputArray (or OutputArray) for the respective parameters. Inside
97     a function you should use _InputArray::getMat() method to construct a matrix header for the
98     array (without copying data). _InputArray::kind() can be used to distinguish Mat from
99     `vector<>` etc., but normally it is not needed.
100
101 Here is how you can use a function that takes InputArray :
102 @code
103     std::vector<Point2f> vec;
104     // points or a circle
105     for( int i = 0; i < 30; i++ )
106         vec.push_back(Point2f((float)(100 + 30*cos(i*CV_PI*2/5)),
107                               (float)(100 - 30*sin(i*CV_PI*2/5))));
108     cv::transform(vec, vec, cv::Matx23f(0.707, -0.707, 10, 0.707, 0.707, 20));
109 @endcode
110 That is, we form an STL vector containing points, and apply in-place affine transformation to the
111 vector using the 2x3 matrix created inline as `Matx<float, 2, 3>` instance.
112
113 Here is how such a function can be implemented (for simplicity, we implement a very specific case of
114 it, according to the assertion statement inside) :
115 @code
116     void myAffineTransform(InputArray _src, OutputArray _dst, InputArray _m)
117     {
118         // get Mat headers for input arrays. This is O(1) operation,
119         // unless _src and/or _m are matrix expressions.
120         Mat src = _src.getMat(), m = _m.getMat();
121         CV_Assert( src.type() == CV_32FC2 && m.type() == CV_32F && m.size() == Size(3, 2) );
122
123         // [re]create the output array so that it has the proper size and type.
124         // In case of Mat it calls Mat::create, in case of STL vector it calls vector::resize.
125         _dst.create(src.size(), src.type());
126         Mat dst = _dst.getMat();
127
128         for( int i = 0; i < src.rows; i++ )
129             for( int j = 0; j < src.cols; j++ )
130             {
131                 Point2f pt = src.at<Point2f>(i, j);
132                 dst.at<Point2f>(i, j) = Point2f(m.at<float>(0, 0)*pt.x +
133                                                 m.at<float>(0, 1)*pt.y +
134                                                 m.at<float>(0, 2),
135                                                 m.at<float>(1, 0)*pt.x +
136                                                 m.at<float>(1, 1)*pt.y +
137                                                 m.at<float>(1, 2));
138             }
139     }
140 @endcode
141 There is another related type, InputArrayOfArrays, which is currently defined as a synonym for
142 InputArray:
143 @code
144     typedef InputArray InputArrayOfArrays;
145 @endcode
146 It denotes function arguments that are either vectors of vectors or vectors of matrices. A separate
147 synonym is needed to generate Python/Java etc. wrappers properly. At the function implementation
148 level their use is similar, but _InputArray::getMat(idx) should be used to get header for the
149 idx-th component of the outer vector and _InputArray::size().area() should be used to find the
150 number of components (vectors/matrices) of the outer vector.
151
152 In general, type support is limited to cv::Mat types. Other types are forbidden.
153 But in some cases we need to support passing of custom non-general Mat types, like arrays of cv::KeyPoint, cv::DMatch, etc.
154 This data is not intended to be interpreted as an image data, or processed somehow like regular cv::Mat.
155 To pass such custom type use rawIn() / rawOut() / rawInOut() wrappers.
156 Custom type is wrapped as Mat-compatible `CV_8UC<N>` values (N = sizeof(T), N <= CV_CN_MAX).
157  */
158 class CV_EXPORTS _InputArray
159 {
160 public:
161     enum KindFlag {
162         KIND_SHIFT = 16,
163         FIXED_TYPE = 0x8000 << KIND_SHIFT,
164         FIXED_SIZE = 0x4000 << KIND_SHIFT,
165         KIND_MASK = 31 << KIND_SHIFT,
166
167         NONE              = 0 << KIND_SHIFT,
168         MAT               = 1 << KIND_SHIFT,
169         MATX              = 2 << KIND_SHIFT,
170         STD_VECTOR        = 3 << KIND_SHIFT,
171         STD_VECTOR_VECTOR = 4 << KIND_SHIFT,
172         STD_VECTOR_MAT    = 5 << KIND_SHIFT,
173         EXPR              = 6 << KIND_SHIFT,  //!< removed
174         OPENGL_BUFFER     = 7 << KIND_SHIFT,
175         CUDA_HOST_MEM     = 8 << KIND_SHIFT,
176         CUDA_GPU_MAT      = 9 << KIND_SHIFT,
177         UMAT              =10 << KIND_SHIFT,
178         STD_VECTOR_UMAT   =11 << KIND_SHIFT,
179         STD_BOOL_VECTOR   =12 << KIND_SHIFT,
180         STD_VECTOR_CUDA_GPU_MAT = 13 << KIND_SHIFT,
181         STD_ARRAY         =14 << KIND_SHIFT,
182         STD_ARRAY_MAT     =15 << KIND_SHIFT
183     };
184
185     _InputArray();
186     _InputArray(int _flags, void* _obj);
187     _InputArray(const Mat& m);
188     _InputArray(const MatExpr& expr);
189     _InputArray(const std::vector<Mat>& vec);
190     template<typename _Tp> _InputArray(const Mat_<_Tp>& m);
191     template<typename _Tp> _InputArray(const std::vector<_Tp>& vec);
192     _InputArray(const std::vector<bool>& vec);
193     template<typename _Tp> _InputArray(const std::vector<std::vector<_Tp> >& vec);
194     _InputArray(const std::vector<std::vector<bool> >&) = delete;  // not supported
195     template<typename _Tp> _InputArray(const std::vector<Mat_<_Tp> >& vec);
196     template<typename _Tp> _InputArray(const _Tp* vec, int n);
197     template<typename _Tp, int m, int n> _InputArray(const Matx<_Tp, m, n>& matx);
198     _InputArray(const double& val);
199     _InputArray(const cuda::GpuMat& d_mat);
200     _InputArray(const std::vector<cuda::GpuMat>& d_mat_array);
201     _InputArray(const ogl::Buffer& buf);
202     _InputArray(const cuda::HostMem& cuda_mem);
203     template<typename _Tp> _InputArray(const cudev::GpuMat_<_Tp>& m);
204     _InputArray(const UMat& um);
205     _InputArray(const std::vector<UMat>& umv);
206
207     template<typename _Tp, std::size_t _Nm> _InputArray(const std::array<_Tp, _Nm>& arr);
208     template<std::size_t _Nm> _InputArray(const std::array<Mat, _Nm>& arr);
209
210     template<typename _Tp> static _InputArray rawIn(const std::vector<_Tp>& vec);
211     template<typename _Tp, std::size_t _Nm> static _InputArray rawIn(const std::array<_Tp, _Nm>& arr);
212
213     Mat getMat(int idx=-1) const;
214     Mat getMat_(int idx=-1) const;
215     UMat getUMat(int idx=-1) const;
216     void getMatVector(std::vector<Mat>& mv) const;
217     void getUMatVector(std::vector<UMat>& umv) const;
218     void getGpuMatVector(std::vector<cuda::GpuMat>& gpumv) const;
219     cuda::GpuMat getGpuMat() const;
220     ogl::Buffer getOGlBuffer() const;
221
222     int getFlags() const;
223     void* getObj() const;
224     Size getSz() const;
225
226     _InputArray::KindFlag kind() const;
227     int dims(int i=-1) const;
228     int cols(int i=-1) const;
229     int rows(int i=-1) const;
230     Size size(int i=-1) const;
231     int sizend(int* sz, int i=-1) const;
232     bool sameSize(const _InputArray& arr) const;
233     size_t total(int i=-1) const;
234     int type(int i=-1) const;
235     int depth(int i=-1) const;
236     int channels(int i=-1) const;
237     bool isContinuous(int i=-1) const;
238     bool isSubmatrix(int i=-1) const;
239     bool empty() const;
240     void copyTo(const _OutputArray& arr) const;
241     void copyTo(const _OutputArray& arr, const _InputArray & mask) const;
242     size_t offset(int i=-1) const;
243     size_t step(int i=-1) const;
244     bool isMat() const;
245     bool isUMat() const;
246     bool isMatVector() const;
247     bool isUMatVector() const;
248     bool isMatx() const;
249     bool isVector() const;
250     bool isGpuMat() const;
251     bool isGpuMatVector() const;
252     ~_InputArray();
253
254 protected:
255     int flags;
256     void* obj;
257     Size sz;
258
259     void init(int _flags, const void* _obj);
260     void init(int _flags, const void* _obj, Size _sz);
261 };
262 CV_ENUM_FLAGS(_InputArray::KindFlag)
263 __CV_ENUM_FLAGS_BITWISE_AND(_InputArray::KindFlag, int, _InputArray::KindFlag)
264
265 /** @brief This type is very similar to InputArray except that it is used for input/output and output function
266 parameters.
267
268 Just like with InputArray, OpenCV users should not care about OutputArray, they just pass `Mat`,
269 `vector<T>` etc. to the functions. The same limitation as for `InputArray`: *Do not explicitly
270 create OutputArray instances* applies here too.
271
272 If you want to make your function polymorphic (i.e. accept different arrays as output parameters),
273 it is also not very difficult. Take the sample above as the reference. Note that
274 _OutputArray::create() needs to be called before _OutputArray::getMat(). This way you guarantee
275 that the output array is properly allocated.
276
277 Optional output parameters. If you do not need certain output array to be computed and returned to
278 you, pass cv::noArray(), just like you would in the case of optional input array. At the
279 implementation level, use _OutputArray::needed() to check if certain output array needs to be
280 computed or not.
281
282 There are several synonyms for OutputArray that are used to assist automatic Python/Java/... wrapper
283 generators:
284 @code
285     typedef OutputArray OutputArrayOfArrays;
286     typedef OutputArray InputOutputArray;
287     typedef OutputArray InputOutputArrayOfArrays;
288 @endcode
289  */
290 class CV_EXPORTS _OutputArray : public _InputArray
291 {
292 public:
293     enum DepthMask
294     {
295         DEPTH_MASK_8U = 1 << CV_8U,
296         DEPTH_MASK_8S = 1 << CV_8S,
297         DEPTH_MASK_16U = 1 << CV_16U,
298         DEPTH_MASK_16S = 1 << CV_16S,
299         DEPTH_MASK_32S = 1 << CV_32S,
300         DEPTH_MASK_32F = 1 << CV_32F,
301         DEPTH_MASK_64F = 1 << CV_64F,
302         DEPTH_MASK_16F = 1 << CV_16F,
303         DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1,
304         DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S,
305         DEPTH_MASK_ALL_16F = (DEPTH_MASK_16F<<1)-1,
306         DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F
307     };
308
309     _OutputArray();
310     _OutputArray(int _flags, void* _obj);
311     _OutputArray(Mat& m);
312     _OutputArray(std::vector<Mat>& vec);
313     _OutputArray(cuda::GpuMat& d_mat);
314     _OutputArray(std::vector<cuda::GpuMat>& d_mat);
315     _OutputArray(ogl::Buffer& buf);
316     _OutputArray(cuda::HostMem& cuda_mem);
317     template<typename _Tp> _OutputArray(cudev::GpuMat_<_Tp>& m);
318     template<typename _Tp> _OutputArray(std::vector<_Tp>& vec);
319     _OutputArray(std::vector<bool>& vec) = delete;  // not supported
320     template<typename _Tp> _OutputArray(std::vector<std::vector<_Tp> >& vec);
321     _OutputArray(std::vector<std::vector<bool> >&) = delete;  // not supported
322     template<typename _Tp> _OutputArray(std::vector<Mat_<_Tp> >& vec);
323     template<typename _Tp> _OutputArray(Mat_<_Tp>& m);
324     template<typename _Tp> _OutputArray(_Tp* vec, int n);
325     template<typename _Tp, int m, int n> _OutputArray(Matx<_Tp, m, n>& matx);
326     _OutputArray(UMat& m);
327     _OutputArray(std::vector<UMat>& vec);
328
329     _OutputArray(const Mat& m);
330     _OutputArray(const std::vector<Mat>& vec);
331     _OutputArray(const cuda::GpuMat& d_mat);
332     _OutputArray(const std::vector<cuda::GpuMat>& d_mat);
333     _OutputArray(const ogl::Buffer& buf);
334     _OutputArray(const cuda::HostMem& cuda_mem);
335     template<typename _Tp> _OutputArray(const cudev::GpuMat_<_Tp>& m);
336     template<typename _Tp> _OutputArray(const std::vector<_Tp>& vec);
337     template<typename _Tp> _OutputArray(const std::vector<std::vector<_Tp> >& vec);
338     template<typename _Tp> _OutputArray(const std::vector<Mat_<_Tp> >& vec);
339     template<typename _Tp> _OutputArray(const Mat_<_Tp>& m);
340     template<typename _Tp> _OutputArray(const _Tp* vec, int n);
341     template<typename _Tp, int m, int n> _OutputArray(const Matx<_Tp, m, n>& matx);
342     _OutputArray(const UMat& m);
343     _OutputArray(const std::vector<UMat>& vec);
344
345     template<typename _Tp, std::size_t _Nm> _OutputArray(std::array<_Tp, _Nm>& arr);
346     template<typename _Tp, std::size_t _Nm> _OutputArray(const std::array<_Tp, _Nm>& arr);
347     template<std::size_t _Nm> _OutputArray(std::array<Mat, _Nm>& arr);
348     template<std::size_t _Nm> _OutputArray(const std::array<Mat, _Nm>& arr);
349
350     template<typename _Tp> static _OutputArray rawOut(std::vector<_Tp>& vec);
351     template<typename _Tp, std::size_t _Nm> static _OutputArray rawOut(std::array<_Tp, _Nm>& arr);
352
353     bool fixedSize() const;
354     bool fixedType() const;
355     bool needed() const;
356     Mat& getMatRef(int i=-1) const;
357     UMat& getUMatRef(int i=-1) const;
358     cuda::GpuMat& getGpuMatRef() const;
359     std::vector<cuda::GpuMat>& getGpuMatVecRef() const;
360     ogl::Buffer& getOGlBufferRef() const;
361     cuda::HostMem& getHostMemRef() const;
362     void create(Size sz, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const;
363     void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const;
364     void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const;
365     void createSameSize(const _InputArray& arr, int mtype) const;
366     void release() const;
367     void clear() const;
368     void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const;
369
370     void assign(const UMat& u) const;
371     void assign(const Mat& m) const;
372
373     void assign(const std::vector<UMat>& v) const;
374     void assign(const std::vector<Mat>& v) const;
375
376     void move(UMat& u) const;
377     void move(Mat& m) const;
378 };
379
380
381 class CV_EXPORTS _InputOutputArray : public _OutputArray
382 {
383 public:
384     _InputOutputArray();
385     _InputOutputArray(int _flags, void* _obj);
386     _InputOutputArray(Mat& m);
387     _InputOutputArray(std::vector<Mat>& vec);
388     _InputOutputArray(cuda::GpuMat& d_mat);
389     _InputOutputArray(ogl::Buffer& buf);
390     _InputOutputArray(cuda::HostMem& cuda_mem);
391     template<typename _Tp> _InputOutputArray(cudev::GpuMat_<_Tp>& m);
392     template<typename _Tp> _InputOutputArray(std::vector<_Tp>& vec);
393     _InputOutputArray(std::vector<bool>& vec) = delete;  // not supported
394     template<typename _Tp> _InputOutputArray(std::vector<std::vector<_Tp> >& vec);
395     template<typename _Tp> _InputOutputArray(std::vector<Mat_<_Tp> >& vec);
396     template<typename _Tp> _InputOutputArray(Mat_<_Tp>& m);
397     template<typename _Tp> _InputOutputArray(_Tp* vec, int n);
398     template<typename _Tp, int m, int n> _InputOutputArray(Matx<_Tp, m, n>& matx);
399     _InputOutputArray(UMat& m);
400     _InputOutputArray(std::vector<UMat>& vec);
401
402     _InputOutputArray(const Mat& m);
403     _InputOutputArray(const std::vector<Mat>& vec);
404     _InputOutputArray(const cuda::GpuMat& d_mat);
405     _InputOutputArray(const std::vector<cuda::GpuMat>& d_mat);
406     _InputOutputArray(const ogl::Buffer& buf);
407     _InputOutputArray(const cuda::HostMem& cuda_mem);
408     template<typename _Tp> _InputOutputArray(const cudev::GpuMat_<_Tp>& m);
409     template<typename _Tp> _InputOutputArray(const std::vector<_Tp>& vec);
410     template<typename _Tp> _InputOutputArray(const std::vector<std::vector<_Tp> >& vec);
411     template<typename _Tp> _InputOutputArray(const std::vector<Mat_<_Tp> >& vec);
412     template<typename _Tp> _InputOutputArray(const Mat_<_Tp>& m);
413     template<typename _Tp> _InputOutputArray(const _Tp* vec, int n);
414     template<typename _Tp, int m, int n> _InputOutputArray(const Matx<_Tp, m, n>& matx);
415     _InputOutputArray(const UMat& m);
416     _InputOutputArray(const std::vector<UMat>& vec);
417
418     template<typename _Tp, std::size_t _Nm> _InputOutputArray(std::array<_Tp, _Nm>& arr);
419     template<typename _Tp, std::size_t _Nm> _InputOutputArray(const std::array<_Tp, _Nm>& arr);
420     template<std::size_t _Nm> _InputOutputArray(std::array<Mat, _Nm>& arr);
421     template<std::size_t _Nm> _InputOutputArray(const std::array<Mat, _Nm>& arr);
422
423     template<typename _Tp> static _InputOutputArray rawInOut(std::vector<_Tp>& vec);
424     template<typename _Tp, std::size_t _Nm> _InputOutputArray rawInOut(std::array<_Tp, _Nm>& arr);
425
426 };
427
428 /** Helper to wrap custom types. @see InputArray */
429 template<typename _Tp> static inline _InputArray rawIn(_Tp& v);
430 /** Helper to wrap custom types. @see InputArray */
431 template<typename _Tp> static inline _OutputArray rawOut(_Tp& v);
432 /** Helper to wrap custom types. @see InputArray */
433 template<typename _Tp> static inline _InputOutputArray rawInOut(_Tp& v);
434
435 CV__DEBUG_NS_END
436
437 typedef const _InputArray& InputArray;
438 typedef InputArray InputArrayOfArrays;
439 typedef const _OutputArray& OutputArray;
440 typedef OutputArray OutputArrayOfArrays;
441 typedef const _InputOutputArray& InputOutputArray;
442 typedef InputOutputArray InputOutputArrayOfArrays;
443
444 CV_EXPORTS InputOutputArray noArray();
445
446 /////////////////////////////////// MatAllocator //////////////////////////////////////
447
448 //! Usage flags for allocator
449 enum UMatUsageFlags
450 {
451     USAGE_DEFAULT = 0,
452
453     // buffer allocation policy is platform and usage specific
454     USAGE_ALLOCATE_HOST_MEMORY = 1 << 0,
455     USAGE_ALLOCATE_DEVICE_MEMORY = 1 << 1,
456     USAGE_ALLOCATE_SHARED_MEMORY = 1 << 2, // It is not equal to: USAGE_ALLOCATE_HOST_MEMORY | USAGE_ALLOCATE_DEVICE_MEMORY
457
458     __UMAT_USAGE_FLAGS_32BIT = 0x7fffffff // Binary compatibility hint
459 };
460
461 struct CV_EXPORTS UMatData;
462
463 /** @brief  Custom array allocator
464 */
465 class CV_EXPORTS MatAllocator
466 {
467 public:
468     MatAllocator() {}
469     virtual ~MatAllocator() {}
470
471     // let's comment it off for now to detect and fix all the uses of allocator
472     //virtual void allocate(int dims, const int* sizes, int type, int*& refcount,
473     //                      uchar*& datastart, uchar*& data, size_t* step) = 0;
474     //virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0;
475     virtual UMatData* allocate(int dims, const int* sizes, int type,
476                                void* data, size_t* step, AccessFlag flags, UMatUsageFlags usageFlags) const = 0;
477     virtual bool allocate(UMatData* data, AccessFlag accessflags, UMatUsageFlags usageFlags) const = 0;
478     virtual void deallocate(UMatData* data) const = 0;
479     virtual void map(UMatData* data, AccessFlag accessflags) const;
480     virtual void unmap(UMatData* data) const;
481     virtual void download(UMatData* data, void* dst, int dims, const size_t sz[],
482                           const size_t srcofs[], const size_t srcstep[],
483                           const size_t dststep[]) const;
484     virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[],
485                         const size_t dstofs[], const size_t dststep[],
486                         const size_t srcstep[]) const;
487     virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[],
488                       const size_t srcofs[], const size_t srcstep[],
489                       const size_t dstofs[], const size_t dststep[], bool sync) const;
490
491     // default implementation returns DummyBufferPoolController
492     virtual BufferPoolController* getBufferPoolController(const char* id = NULL) const;
493 };
494
495
496 //////////////////////////////// MatCommaInitializer //////////////////////////////////
497
498 /** @brief  Comma-separated Matrix Initializer
499
500  The class instances are usually not created explicitly.
501  Instead, they are created on "matrix << firstValue" operator.
502
503  The sample below initializes 2x2 rotation matrix:
504
505  \code
506  double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180);
507  Mat R = (Mat_<double>(2,2) << a, -b, b, a);
508  \endcode
509 */
510 template<typename _Tp> class MatCommaInitializer_
511 {
512 public:
513     //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat
514     MatCommaInitializer_(Mat_<_Tp>* _m);
515     //! the operator that takes the next value and put it to the matrix
516     template<typename T2> MatCommaInitializer_<_Tp>& operator , (T2 v);
517     //! another form of conversion operator
518     operator Mat_<_Tp>() const;
519 protected:
520     MatIterator_<_Tp> it;
521 };
522
523
524 /////////////////////////////////////// Mat ///////////////////////////////////////////
525
526 // note that umatdata might be allocated together
527 // with the matrix data, not as a separate object.
528 // therefore, it does not have constructor or destructor;
529 // it should be explicitly initialized using init().
530 struct CV_EXPORTS UMatData
531 {
532     enum MemoryFlag { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2,
533         DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24,
534         USER_ALLOCATED=32, DEVICE_MEM_MAPPED=64,
535         ASYNC_CLEANUP=128
536     };
537     UMatData(const MatAllocator* allocator);
538     ~UMatData();
539
540     // provide atomic access to the structure
541     void lock();
542     void unlock();
543
544     bool hostCopyObsolete() const;
545     bool deviceCopyObsolete() const;
546     bool deviceMemMapped() const;
547     bool copyOnMap() const;
548     bool tempUMat() const;
549     bool tempCopiedUMat() const;
550     void markHostCopyObsolete(bool flag);
551     void markDeviceCopyObsolete(bool flag);
552     void markDeviceMemMapped(bool flag);
553
554     const MatAllocator* prevAllocator;
555     const MatAllocator* currAllocator;
556     int urefcount;
557     int refcount;
558     uchar* data;
559     uchar* origdata;
560     size_t size;
561
562     UMatData::MemoryFlag flags;
563     void* handle;
564     void* userdata;
565     int allocatorFlags_;
566     int mapcount;
567     UMatData* originalUMatData;
568     std::shared_ptr<void> allocatorContext;
569 };
570 CV_ENUM_FLAGS(UMatData::MemoryFlag)
571
572
573 struct CV_EXPORTS MatSize
574 {
575     explicit MatSize(int* _p);
576     int dims() const;
577     Size operator()() const;
578     const int& operator[](int i) const;
579     int& operator[](int i);
580     operator const int*() const;  // TODO OpenCV 4.0: drop this
581     bool operator == (const MatSize& sz) const;
582     bool operator != (const MatSize& sz) const;
583
584     int* p;
585 };
586
587 struct CV_EXPORTS MatStep
588 {
589     MatStep();
590     explicit MatStep(size_t s);
591     const size_t& operator[](int i) const;
592     size_t& operator[](int i);
593     operator size_t() const;
594     MatStep& operator = (size_t s);
595
596     size_t* p;
597     size_t buf[2];
598 protected:
599     MatStep& operator = (const MatStep&);
600 };
601
602 /** @example samples/cpp/cout_mat.cpp
603 An example demonstrating the serial out capabilities of cv::Mat
604 */
605
606  /** @brief n-dimensional dense array class \anchor CVMat_Details
607
608 The class Mat represents an n-dimensional dense numerical single-channel or multi-channel array. It
609 can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel
610 volumes, vector fields, point clouds, tensors, histograms (though, very high-dimensional histograms
611 may be better stored in a SparseMat ). The data layout of the array `M` is defined by the array
612 `M.step[]`, so that the address of element \f$(i_0,...,i_{M.dims-1})\f$, where \f$0\leq i_k<M.size[k]\f$, is
613 computed as:
614 \f[addr(M_{i_0,...,i_{M.dims-1}}) = M.data + M.step[0]*i_0 + M.step[1]*i_1 + ... + M.step[M.dims-1]*i_{M.dims-1}\f]
615 In case of a 2-dimensional array, the above formula is reduced to:
616 \f[addr(M_{i,j}) = M.data + M.step[0]*i + M.step[1]*j\f]
617 Note that `M.step[i] >= M.step[i+1]` (in fact, `M.step[i] >= M.step[i+1]*M.size[i+1]` ). This means
618 that 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane,
619 and so on. M.step[M.dims-1] is minimal and always equal to the element size M.elemSize() .
620
621 So, the data layout in Mat is compatible with the majority of dense array types from the standard
622 toolkits and SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others,
623 that is, with any array that uses *steps* (or *strides*) to compute the position of a pixel.
624 Due to this compatibility, it is possible to make a Mat header for user-allocated data and process
625 it in-place using OpenCV functions.
626
627 There are many different ways to create a Mat object. The most popular options are listed below:
628
629 - Use the create(nrows, ncols, type) method or the similar Mat(nrows, ncols, type[, fillValue])
630 constructor. A new array of the specified size and type is allocated. type has the same meaning as
631 in the cvCreateMat method. For example, CV_8UC1 means a 8-bit single-channel array, CV_32FC2
632 means a 2-channel (complex) floating-point array, and so on.
633 @code
634     // make a 7x7 complex matrix filled with 1+3j.
635     Mat M(7,7,CV_32FC2,Scalar(1,3));
636     // and now turn M to a 100x60 15-channel 8-bit matrix.
637     // The old content will be deallocated
638     M.create(100,60,CV_8UC(15));
639 @endcode
640 As noted in the introduction to this chapter, create() allocates only a new array when the shape
641 or type of the current array are different from the specified ones.
642
643 - Create a multi-dimensional array:
644 @code
645     // create a 100x100x100 8-bit array
646     int sz[] = {100, 100, 100};
647     Mat bigCube(3, sz, CV_8U, Scalar::all(0));
648 @endcode
649 It passes the number of dimensions =1 to the Mat constructor but the created array will be
650 2-dimensional with the number of columns set to 1. So, Mat::dims is always \>= 2 (can also be 0
651 when the array is empty).
652
653 - Use a copy constructor or assignment operator where there can be an array or expression on the
654 right side (see below). As noted in the introduction, the array assignment is an O(1) operation
655 because it only copies the header and increases the reference counter. The Mat::clone() method can
656 be used to get a full (deep) copy of the array when you need it.
657
658 - Construct a header for a part of another array. It can be a single row, single column, several
659 rows, several columns, rectangular region in the array (called a *minor* in algebra) or a
660 diagonal. Such operations are also O(1) because the new header references the same data. You can
661 actually modify a part of the array using this feature, for example:
662 @code
663     // add the 5-th row, multiplied by 3 to the 3rd row
664     M.row(3) = M.row(3) + M.row(5)*3;
665     // now copy the 7-th column to the 1-st column
666     // M.col(1) = M.col(7); // this will not work
667     Mat M1 = M.col(1);
668     M.col(7).copyTo(M1);
669     // create a new 320x240 image
670     Mat img(Size(320,240),CV_8UC3);
671     // select a ROI
672     Mat roi(img, Rect(10,10,100,100));
673     // fill the ROI with (0,255,0) (which is green in RGB space);
674     // the original 320x240 image will be modified
675     roi = Scalar(0,255,0);
676 @endcode
677 Due to the additional datastart and dataend members, it is possible to compute a relative
678 sub-array position in the main *container* array using locateROI():
679 @code
680     Mat A = Mat::eye(10, 10, CV_32S);
681     // extracts A columns, 1 (inclusive) to 3 (exclusive).
682     Mat B = A(Range::all(), Range(1, 3));
683     // extracts B rows, 5 (inclusive) to 9 (exclusive).
684     // that is, C \~ A(Range(5, 9), Range(1, 3))
685     Mat C = B(Range(5, 9), Range::all());
686     Size size; Point ofs;
687     C.locateROI(size, ofs);
688     // size will be (width=10,height=10) and the ofs will be (x=1, y=5)
689 @endcode
690 As in case of whole matrices, if you need a deep copy, use the `clone()` method of the extracted
691 sub-matrices.
692
693 - Make a header for user-allocated data. It can be useful to do the following:
694     -# Process "foreign" data using OpenCV (for example, when you implement a DirectShow\* filter or
695     a processing module for gstreamer, and so on). For example:
696     @code
697         void process_video_frame(const unsigned char* pixels,
698                                  int width, int height, int step)
699         {
700             Mat img(height, width, CV_8UC3, pixels, step);
701             GaussianBlur(img, img, Size(7,7), 1.5, 1.5);
702         }
703     @endcode
704     -# Quickly initialize small matrices and/or get a super-fast element access.
705     @code
706         double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
707         Mat M = Mat(3, 3, CV_64F, m).inv();
708     @endcode
709     .
710
711 - Use MATLAB-style array initializers, zeros(), ones(), eye(), for example:
712 @code
713     // create a double-precision identity matrix and add it to M.
714     M += Mat::eye(M.rows, M.cols, CV_64F);
715 @endcode
716
717 - Use a comma-separated initializer:
718 @code
719     // create a 3x3 double-precision identity matrix
720     Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
721 @endcode
722 With this approach, you first call a constructor of the Mat class with the proper parameters, and
723 then you just put `<< operator` followed by comma-separated values that can be constants,
724 variables, expressions, and so on. Also, note the extra parentheses required to avoid compilation
725 errors.
726
727 Once the array is created, it is automatically managed via a reference-counting mechanism. If the
728 array header is built on top of user-allocated data, you should handle the data by yourself. The
729 array data is deallocated when no one points to it. If you want to release the data pointed by a
730 array header before the array destructor is called, use Mat::release().
731
732 The next important thing to learn about the array class is element access. This manual already
733 described how to compute an address of each array element. Normally, you are not required to use the
734 formula directly in the code. If you know the array element type (which can be retrieved using the
735 method Mat::type() ), you can access the element \f$M_{ij}\f$ of a 2-dimensional array as:
736 @code
737     M.at<double>(i,j) += 1.f;
738 @endcode
739 assuming that `M` is a double-precision floating-point array. There are several variants of the method
740 at for a different number of dimensions.
741
742 If you need to process a whole row of a 2D array, the most efficient way is to get the pointer to
743 the row first, and then just use the plain C operator [] :
744 @code
745     // compute sum of positive matrix elements
746     // (assuming that M is a double-precision matrix)
747     double sum=0;
748     for(int i = 0; i < M.rows; i++)
749     {
750         const double* Mi = M.ptr<double>(i);
751         for(int j = 0; j < M.cols; j++)
752             sum += std::max(Mi[j], 0.);
753     }
754 @endcode
755 Some operations, like the one above, do not actually depend on the array shape. They just process
756 elements of an array one by one (or elements from multiple arrays that have the same coordinates,
757 for example, array addition). Such operations are called *element-wise*. It makes sense to check
758 whether all the input/output arrays are continuous, namely, have no gaps at the end of each row. If
759 yes, process them as a long single row:
760 @code
761     // compute the sum of positive matrix elements, optimized variant
762     double sum=0;
763     int cols = M.cols, rows = M.rows;
764     if(M.isContinuous())
765     {
766         cols *= rows;
767         rows = 1;
768     }
769     for(int i = 0; i < rows; i++)
770     {
771         const double* Mi = M.ptr<double>(i);
772         for(int j = 0; j < cols; j++)
773             sum += std::max(Mi[j], 0.);
774     }
775 @endcode
776 In case of the continuous matrix, the outer loop body is executed just once. So, the overhead is
777 smaller, which is especially noticeable in case of small matrices.
778
779 Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:
780 @code
781     // compute sum of positive matrix elements, iterator-based variant
782     double sum=0;
783     MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
784     for(; it != it_end; ++it)
785         sum += std::max(*it, 0.);
786 @endcode
787 The matrix iterators are random-access iterators, so they can be passed to any STL algorithm,
788 including std::sort().
789
790 @note Matrix Expressions and arithmetic see MatExpr
791 */
792 class CV_EXPORTS Mat
793 {
794 public:
795     /**
796     These are various constructors that form a matrix. As noted in the AutomaticAllocation, often
797     the default constructor is enough, and the proper matrix will be allocated by an OpenCV function.
798     The constructed matrix can further be assigned to another matrix or matrix expression or can be
799     allocated with Mat::create . In the former case, the old content is de-referenced.
800      */
801     Mat();
802
803     /** @overload
804     @param rows Number of rows in a 2D array.
805     @param cols Number of columns in a 2D array.
806     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
807     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
808     */
809     Mat(int rows, int cols, int type);
810
811     /** @overload
812     @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the
813     number of columns go in the reverse order.
814     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
815     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
816       */
817     Mat(Size size, int type);
818
819     /** @overload
820     @param rows Number of rows in a 2D array.
821     @param cols Number of columns in a 2D array.
822     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
823     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
824     @param s An optional value to initialize each matrix element with. To set all the matrix elements to
825     the particular value after the construction, use the assignment operator
826     Mat::operator=(const Scalar& value) .
827     */
828     Mat(int rows, int cols, int type, const Scalar& s);
829
830     /** @overload
831     @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the
832     number of columns go in the reverse order.
833     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
834     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
835     @param s An optional value to initialize each matrix element with. To set all the matrix elements to
836     the particular value after the construction, use the assignment operator
837     Mat::operator=(const Scalar& value) .
838       */
839     Mat(Size size, int type, const Scalar& s);
840
841     /** @overload
842     @param ndims Array dimensionality.
843     @param sizes Array of integers specifying an n-dimensional array shape.
844     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
845     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
846     */
847     Mat(int ndims, const int* sizes, int type);
848
849     /** @overload
850     @param sizes Array of integers specifying an n-dimensional array shape.
851     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
852     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
853     */
854     Mat(const std::vector<int>& sizes, int type);
855
856     /** @overload
857     @param ndims Array dimensionality.
858     @param sizes Array of integers specifying an n-dimensional array shape.
859     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
860     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
861     @param s An optional value to initialize each matrix element with. To set all the matrix elements to
862     the particular value after the construction, use the assignment operator
863     Mat::operator=(const Scalar& value) .
864     */
865     Mat(int ndims, const int* sizes, int type, const Scalar& s);
866
867     /** @overload
868     @param sizes Array of integers specifying an n-dimensional array shape.
869     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
870     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
871     @param s An optional value to initialize each matrix element with. To set all the matrix elements to
872     the particular value after the construction, use the assignment operator
873     Mat::operator=(const Scalar& value) .
874     */
875     Mat(const std::vector<int>& sizes, int type, const Scalar& s);
876
877
878     /** @overload
879     @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
880     by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
881     associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
882     formed using such a constructor, you also modify the corresponding elements of m . If you want to
883     have an independent copy of the sub-array, use Mat::clone() .
884     */
885     Mat(const Mat& m);
886
887     /** @overload
888     @param rows Number of rows in a 2D array.
889     @param cols Number of columns in a 2D array.
890     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
891     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
892     @param data Pointer to the user data. Matrix constructors that take data and step parameters do not
893     allocate matrix data. Instead, they just initialize the matrix header that points to the specified
894     data, which means that no data is copied. This operation is very efficient and can be used to
895     process external data using OpenCV functions. The external data is not automatically deallocated, so
896     you should take care of it.
897     @param step Number of bytes each matrix row occupies. The value should include the padding bytes at
898     the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed
899     and the actual step is calculated as cols*elemSize(). See Mat::elemSize.
900     */
901     Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP);
902
903     /** @overload
904     @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the
905     number of columns go in the reverse order.
906     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
907     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
908     @param data Pointer to the user data. Matrix constructors that take data and step parameters do not
909     allocate matrix data. Instead, they just initialize the matrix header that points to the specified
910     data, which means that no data is copied. This operation is very efficient and can be used to
911     process external data using OpenCV functions. The external data is not automatically deallocated, so
912     you should take care of it.
913     @param step Number of bytes each matrix row occupies. The value should include the padding bytes at
914     the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed
915     and the actual step is calculated as cols*elemSize(). See Mat::elemSize.
916     */
917     Mat(Size size, int type, void* data, size_t step=AUTO_STEP);
918
919     /** @overload
920     @param ndims Array dimensionality.
921     @param sizes Array of integers specifying an n-dimensional array shape.
922     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
923     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
924     @param data Pointer to the user data. Matrix constructors that take data and step parameters do not
925     allocate matrix data. Instead, they just initialize the matrix header that points to the specified
926     data, which means that no data is copied. This operation is very efficient and can be used to
927     process external data using OpenCV functions. The external data is not automatically deallocated, so
928     you should take care of it.
929     @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always
930     set to the element size). If not specified, the matrix is assumed to be continuous.
931     */
932     Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0);
933
934     /** @overload
935     @param sizes Array of integers specifying an n-dimensional array shape.
936     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
937     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
938     @param data Pointer to the user data. Matrix constructors that take data and step parameters do not
939     allocate matrix data. Instead, they just initialize the matrix header that points to the specified
940     data, which means that no data is copied. This operation is very efficient and can be used to
941     process external data using OpenCV functions. The external data is not automatically deallocated, so
942     you should take care of it.
943     @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always
944     set to the element size). If not specified, the matrix is assumed to be continuous.
945     */
946     Mat(const std::vector<int>& sizes, int type, void* data, const size_t* steps=0);
947
948     /** @overload
949     @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
950     by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
951     associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
952     formed using such a constructor, you also modify the corresponding elements of m . If you want to
953     have an independent copy of the sub-array, use Mat::clone() .
954     @param rowRange Range of the m rows to take. As usual, the range start is inclusive and the range
955     end is exclusive. Use Range::all() to take all the rows.
956     @param colRange Range of the m columns to take. Use Range::all() to take all the columns.
957     */
958     Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all());
959
960     /** @overload
961     @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
962     by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
963     associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
964     formed using such a constructor, you also modify the corresponding elements of m . If you want to
965     have an independent copy of the sub-array, use Mat::clone() .
966     @param roi Region of interest.
967     */
968     Mat(const Mat& m, const Rect& roi);
969
970     /** @overload
971     @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
972     by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
973     associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
974     formed using such a constructor, you also modify the corresponding elements of m . If you want to
975     have an independent copy of the sub-array, use Mat::clone() .
976     @param ranges Array of selected ranges of m along each dimensionality.
977     */
978     Mat(const Mat& m, const Range* ranges);
979
980     /** @overload
981     @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
982     by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
983     associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
984     formed using such a constructor, you also modify the corresponding elements of m . If you want to
985     have an independent copy of the sub-array, use Mat::clone() .
986     @param ranges Array of selected ranges of m along each dimensionality.
987     */
988     Mat(const Mat& m, const std::vector<Range>& ranges);
989
990     /** @overload
991     @param vec STL vector whose elements form the matrix. The matrix has a single column and the number
992     of rows equal to the number of vector elements. Type of the matrix matches the type of vector
993     elements. The constructor can handle arbitrary types, for which there is a properly declared
994     DataType . This means that the vector elements must be primitive numbers or uni-type numerical
995     tuples of numbers. Mixed-type structures are not supported. The corresponding constructor is
996     explicit. Since STL vectors are not automatically converted to Mat instances, you should write
997     Mat(vec) explicitly. Unless you copy the data into the matrix ( copyData=true ), no new elements
998     will be added to the vector because it can potentially yield vector data reallocation, and, thus,
999     the matrix data pointer will be invalid.
1000     @param copyData Flag to specify whether the underlying data of the STL vector should be copied
1001     to (true) or shared with (false) the newly constructed matrix. When the data is copied, the
1002     allocated buffer is managed using Mat reference counting mechanism. While the data is shared,
1003     the reference counter is NULL, and you should not deallocate the data until the matrix is not
1004     destructed.
1005     */
1006     template<typename _Tp> explicit Mat(const std::vector<_Tp>& vec, bool copyData=false);
1007
1008     /** @overload
1009     */
1010     template<typename _Tp, typename = typename std::enable_if<std::is_arithmetic<_Tp>::value>::type>
1011     explicit Mat(const std::initializer_list<_Tp> list);
1012
1013     /** @overload
1014     */
1015     template<typename _Tp> explicit Mat(const std::initializer_list<int> sizes, const std::initializer_list<_Tp> list);
1016
1017     /** @overload
1018     */
1019     template<typename _Tp, size_t _Nm> explicit Mat(const std::array<_Tp, _Nm>& arr, bool copyData=false);
1020
1021     /** @overload
1022     */
1023     template<typename _Tp, int n> explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true);
1024
1025     /** @overload
1026     */
1027     template<typename _Tp, int m, int n> explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
1028
1029     /** @overload
1030     */
1031     template<typename _Tp> explicit Mat(const Point_<_Tp>& pt, bool copyData=true);
1032
1033     /** @overload
1034     */
1035     template<typename _Tp> explicit Mat(const Point3_<_Tp>& pt, bool copyData=true);
1036
1037     /** @overload
1038     */
1039     template<typename _Tp> explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer);
1040
1041     //! download data from GpuMat
1042     explicit Mat(const cuda::GpuMat& m);
1043
1044     //! destructor - calls release()
1045     ~Mat();
1046
1047     /** @brief assignment operators
1048
1049     These are available assignment operators. Since they all are very different, make sure to read the
1050     operator parameters description.
1051     @param m Assigned, right-hand-side matrix. Matrix assignment is an O(1) operation. This means that
1052     no data is copied but the data is shared and the reference counter, if any, is incremented. Before
1053     assigning new data, the old data is de-referenced via Mat::release .
1054      */
1055     Mat& operator = (const Mat& m);
1056
1057     /** @overload
1058     @param expr Assigned matrix expression object. As opposite to the first form of the assignment
1059     operation, the second form can reuse already allocated matrix if it has the right size and type to
1060     fit the matrix expression result. It is automatically handled by the real function that the matrix
1061     expressions is expanded to. For example, C=A+B is expanded to add(A, B, C), and add takes care of
1062     automatic C reallocation.
1063     */
1064     Mat& operator = (const MatExpr& expr);
1065
1066     //! retrieve UMat from Mat
1067     UMat getUMat(AccessFlag accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const;
1068
1069     /** @brief Creates a matrix header for the specified matrix row.
1070
1071     The method makes a new header for the specified matrix row and returns it. This is an O(1)
1072     operation, regardless of the matrix size. The underlying data of the new matrix is shared with the
1073     original matrix. Here is the example of one of the classical basic matrix processing operations,
1074     axpy, used by LU and many other algorithms:
1075     @code
1076         inline void matrix_axpy(Mat& A, int i, int j, double alpha)
1077         {
1078             A.row(i) += A.row(j)*alpha;
1079         }
1080     @endcode
1081     @note In the current implementation, the following code does not work as expected:
1082     @code
1083         Mat A;
1084         ...
1085         A.row(i) = A.row(j); // will not work
1086     @endcode
1087     This happens because A.row(i) forms a temporary header that is further assigned to another header.
1088     Remember that each of these operations is O(1), that is, no data is copied. Thus, the above
1089     assignment is not true if you may have expected the j-th row to be copied to the i-th row. To
1090     achieve that, you should either turn this simple assignment into an expression or use the
1091     Mat::copyTo method:
1092     @code
1093         Mat A;
1094         ...
1095         // works, but looks a bit obscure.
1096         A.row(i) = A.row(j) + 0;
1097         // this is a bit longer, but the recommended method.
1098         A.row(j).copyTo(A.row(i));
1099     @endcode
1100     @param y A 0-based row index.
1101      */
1102     Mat row(int y) const;
1103
1104     /** @brief Creates a matrix header for the specified matrix column.
1105
1106     The method makes a new header for the specified matrix column and returns it. This is an O(1)
1107     operation, regardless of the matrix size. The underlying data of the new matrix is shared with the
1108     original matrix. See also the Mat::row description.
1109     @param x A 0-based column index.
1110      */
1111     Mat col(int x) const;
1112
1113     /** @brief Creates a matrix header for the specified row span.
1114
1115     The method makes a new header for the specified row span of the matrix. Similarly to Mat::row and
1116     Mat::col , this is an O(1) operation.
1117     @param startrow An inclusive 0-based start index of the row span.
1118     @param endrow An exclusive 0-based ending index of the row span.
1119      */
1120     Mat rowRange(int startrow, int endrow) const;
1121
1122     /** @overload
1123     @param r Range structure containing both the start and the end indices.
1124     */
1125     Mat rowRange(const Range& r) const;
1126
1127     /** @brief Creates a matrix header for the specified column span.
1128
1129     The method makes a new header for the specified column span of the matrix. Similarly to Mat::row and
1130     Mat::col , this is an O(1) operation.
1131     @param startcol An inclusive 0-based start index of the column span.
1132     @param endcol An exclusive 0-based ending index of the column span.
1133      */
1134     Mat colRange(int startcol, int endcol) const;
1135
1136     /** @overload
1137     @param r Range structure containing both the start and the end indices.
1138     */
1139     Mat colRange(const Range& r) const;
1140
1141     /** @brief Extracts a diagonal from a matrix
1142
1143     The method makes a new header for the specified matrix diagonal. The new matrix is represented as a
1144     single-column matrix. Similarly to Mat::row and Mat::col, this is an O(1) operation.
1145     @param d index of the diagonal, with the following values:
1146     - `d=0` is the main diagonal.
1147     - `d<0` is a diagonal from the lower half. For example, d=-1 means the diagonal is set
1148       immediately below the main one.
1149     - `d>0` is a diagonal from the upper half. For example, d=1 means the diagonal is set
1150       immediately above the main one.
1151     For example:
1152     @code
1153         Mat m = (Mat_<int>(3,3) <<
1154                     1,2,3,
1155                     4,5,6,
1156                     7,8,9);
1157         Mat d0 = m.diag(0);
1158         Mat d1 = m.diag(1);
1159         Mat d_1 = m.diag(-1);
1160     @endcode
1161     The resulting matrices are
1162     @code
1163      d0 =
1164        [1;
1165         5;
1166         9]
1167      d1 =
1168        [2;
1169         6]
1170      d_1 =
1171        [4;
1172         8]
1173     @endcode
1174      */
1175     Mat diag(int d=0) const;
1176
1177     /** @brief creates a diagonal matrix
1178
1179     The method creates a square diagonal matrix from specified main diagonal.
1180     @param d One-dimensional matrix that represents the main diagonal.
1181      */
1182     static Mat diag(const Mat& d);
1183
1184     /** @brief Creates a full copy of the array and the underlying data.
1185
1186     The method creates a full copy of the array. The original step[] is not taken into account. So, the
1187     array copy is a continuous array occupying total()*elemSize() bytes.
1188      */
1189     Mat clone() const CV_NODISCARD;
1190
1191     /** @brief Copies the matrix to another one.
1192
1193     The method copies the matrix data to another matrix. Before copying the data, the method invokes :
1194     @code
1195         m.create(this->size(), this->type());
1196     @endcode
1197     so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the
1198     function does not handle the case of a partial overlap between the source and the destination
1199     matrices.
1200
1201     When the operation mask is specified, if the Mat::create call shown above reallocates the matrix,
1202     the newly allocated matrix is initialized with all zeros before copying the data.
1203     @param m Destination matrix. If it does not have a proper size or type before the operation, it is
1204     reallocated.
1205      */
1206     void copyTo( OutputArray m ) const;
1207
1208     /** @overload
1209     @param m Destination matrix. If it does not have a proper size or type before the operation, it is
1210     reallocated.
1211     @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix
1212     elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels.
1213     */
1214     void copyTo( OutputArray m, InputArray mask ) const;
1215
1216     /** @brief Converts an array to another data type with optional scaling.
1217
1218     The method converts source pixel values to the target data type. saturate_cast\<\> is applied at
1219     the end to avoid possible overflows:
1220
1221     \f[m(x,y) = saturate \_ cast<rType>( \alpha (*this)(x,y) +  \beta )\f]
1222     @param m output matrix; if it does not have a proper size or type before the operation, it is
1223     reallocated.
1224     @param rtype desired output matrix type or, rather, the depth since the number of channels are the
1225     same as the input has; if rtype is negative, the output matrix will have the same type as the input.
1226     @param alpha optional scale factor.
1227     @param beta optional delta added to the scaled values.
1228      */
1229     void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
1230
1231     /** @brief Provides a functional form of convertTo.
1232
1233     This is an internally used method called by the @ref MatrixExpressions engine.
1234     @param m Destination array.
1235     @param type Desired destination array depth (or -1 if it should be the same as the source type).
1236      */
1237     void assignTo( Mat& m, int type=-1 ) const;
1238
1239     /** @brief Sets all or some of the array elements to the specified value.
1240     @param s Assigned scalar converted to the actual array type.
1241     */
1242     Mat& operator = (const Scalar& s);
1243
1244     /** @brief Sets all or some of the array elements to the specified value.
1245
1246     This is an advanced variant of the Mat::operator=(const Scalar& s) operator.
1247     @param value Assigned scalar converted to the actual array type.
1248     @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix
1249     elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels
1250      */
1251     Mat& setTo(InputArray value, InputArray mask=noArray());
1252
1253     /** @brief Changes the shape and/or the number of channels of a 2D matrix without copying the data.
1254
1255     The method makes a new matrix header for \*this elements. The new matrix may have a different size
1256     and/or different number of channels. Any combination is possible if:
1257     -   No extra elements are included into the new matrix and no elements are excluded. Consequently,
1258         the product rows\*cols\*channels() must stay the same after the transformation.
1259     -   No data is copied. That is, this is an O(1) operation. Consequently, if you change the number of
1260         rows, or the operation changes the indices of elements row in some other way, the matrix must be
1261         continuous. See Mat::isContinuous .
1262
1263     For example, if there is a set of 3D points stored as an STL vector, and you want to represent the
1264     points as a 3xN matrix, do the following:
1265     @code
1266         std::vector<Point3f> vec;
1267         ...
1268         Mat pointMat = Mat(vec). // convert vector to Mat, O(1) operation
1269                           reshape(1). // make Nx3 1-channel matrix out of Nx1 3-channel.
1270                                       // Also, an O(1) operation
1271                              t(); // finally, transpose the Nx3 matrix.
1272                                   // This involves copying all the elements
1273     @endcode
1274     @param cn New number of channels. If the parameter is 0, the number of channels remains the same.
1275     @param rows New number of rows. If the parameter is 0, the number of rows remains the same.
1276      */
1277     Mat reshape(int cn, int rows=0) const;
1278
1279     /** @overload */
1280     Mat reshape(int cn, int newndims, const int* newsz) const;
1281
1282     /** @overload */
1283     Mat reshape(int cn, const std::vector<int>& newshape) const;
1284
1285     /** @brief Transposes a matrix.
1286
1287     The method performs matrix transposition by means of matrix expressions. It does not perform the
1288     actual transposition but returns a temporary matrix transposition object that can be further used as
1289     a part of more complex matrix expressions or can be assigned to a matrix:
1290     @code
1291         Mat A1 = A + Mat::eye(A.size(), A.type())*lambda;
1292         Mat C = A1.t()*A1; // compute (A + lambda*I)^t * (A + lamda*I)
1293     @endcode
1294      */
1295     MatExpr t() const;
1296
1297     /** @brief Inverses a matrix.
1298
1299     The method performs a matrix inversion by means of matrix expressions. This means that a temporary
1300     matrix inversion object is returned by the method and can be used further as a part of more complex
1301     matrix expressions or can be assigned to a matrix.
1302     @param method Matrix inversion method. One of cv::DecompTypes
1303      */
1304     MatExpr inv(int method=DECOMP_LU) const;
1305
1306     /** @brief Performs an element-wise multiplication or division of the two matrices.
1307
1308     The method returns a temporary object encoding per-element array multiplication, with optional
1309     scale. Note that this is not a matrix multiplication that corresponds to a simpler "\*" operator.
1310
1311     Example:
1312     @code
1313         Mat C = A.mul(5/B); // equivalent to divide(A, B, C, 5)
1314     @endcode
1315     @param m Another array of the same type and the same size as \*this, or a matrix expression.
1316     @param scale Optional scale factor.
1317      */
1318     MatExpr mul(InputArray m, double scale=1) const;
1319
1320     /** @brief Computes a cross-product of two 3-element vectors.
1321
1322     The method computes a cross-product of two 3-element vectors. The vectors must be 3-element
1323     floating-point vectors of the same shape and size. The result is another 3-element vector of the
1324     same shape and type as operands.
1325     @param m Another cross-product operand.
1326      */
1327     Mat cross(InputArray m) const;
1328
1329     /** @brief Computes a dot-product of two vectors.
1330
1331     The method computes a dot-product of two matrices. If the matrices are not single-column or
1332     single-row vectors, the top-to-bottom left-to-right scan ordering is used to treat them as 1D
1333     vectors. The vectors must have the same size and type. If the matrices have more than one channel,
1334     the dot products from all the channels are summed together.
1335     @param m another dot-product operand.
1336      */
1337     double dot(InputArray m) const;
1338
1339     /** @brief Returns a zero array of the specified size and type.
1340
1341     The method returns a Matlab-style zero array initializer. It can be used to quickly form a constant
1342     array as a function parameter, part of a matrix expression, or as a matrix initializer:
1343     @code
1344         Mat A;
1345         A = Mat::zeros(3, 3, CV_32F);
1346     @endcode
1347     In the example above, a new matrix is allocated only if A is not a 3x3 floating-point matrix.
1348     Otherwise, the existing matrix A is filled with zeros.
1349     @param rows Number of rows.
1350     @param cols Number of columns.
1351     @param type Created matrix type.
1352      */
1353     static MatExpr zeros(int rows, int cols, int type);
1354
1355     /** @overload
1356     @param size Alternative to the matrix size specification Size(cols, rows) .
1357     @param type Created matrix type.
1358     */
1359     static MatExpr zeros(Size size, int type);
1360
1361     /** @overload
1362     @param ndims Array dimensionality.
1363     @param sz Array of integers specifying the array shape.
1364     @param type Created matrix type.
1365     */
1366     static MatExpr zeros(int ndims, const int* sz, int type);
1367
1368     /** @brief Returns an array of all 1's of the specified size and type.
1369
1370     The method returns a Matlab-style 1's array initializer, similarly to Mat::zeros. Note that using
1371     this method you can initialize an array with an arbitrary value, using the following Matlab idiom:
1372     @code
1373         Mat A = Mat::ones(100, 100, CV_8U)*3; // make 100x100 matrix filled with 3.
1374     @endcode
1375     The above operation does not form a 100x100 matrix of 1's and then multiply it by 3. Instead, it
1376     just remembers the scale factor (3 in this case) and use it when actually invoking the matrix
1377     initializer.
1378     @note In case of multi-channels type, only the first channel will be initialized with 1's, the
1379     others will be set to 0's.
1380     @param rows Number of rows.
1381     @param cols Number of columns.
1382     @param type Created matrix type.
1383      */
1384     static MatExpr ones(int rows, int cols, int type);
1385
1386     /** @overload
1387     @param size Alternative to the matrix size specification Size(cols, rows) .
1388     @param type Created matrix type.
1389     */
1390     static MatExpr ones(Size size, int type);
1391
1392     /** @overload
1393     @param ndims Array dimensionality.
1394     @param sz Array of integers specifying the array shape.
1395     @param type Created matrix type.
1396     */
1397     static MatExpr ones(int ndims, const int* sz, int type);
1398
1399     /** @brief Returns an identity matrix of the specified size and type.
1400
1401     The method returns a Matlab-style identity matrix initializer, similarly to Mat::zeros. Similarly to
1402     Mat::ones, you can use a scale operation to create a scaled identity matrix efficiently:
1403     @code
1404         // make a 4x4 diagonal matrix with 0.1's on the diagonal.
1405         Mat A = Mat::eye(4, 4, CV_32F)*0.1;
1406     @endcode
1407     @note In case of multi-channels type, identity matrix will be initialized only for the first channel,
1408     the others will be set to 0's
1409     @param rows Number of rows.
1410     @param cols Number of columns.
1411     @param type Created matrix type.
1412      */
1413     static MatExpr eye(int rows, int cols, int type);
1414
1415     /** @overload
1416     @param size Alternative matrix size specification as Size(cols, rows) .
1417     @param type Created matrix type.
1418     */
1419     static MatExpr eye(Size size, int type);
1420
1421     /** @brief Allocates new array data if needed.
1422
1423     This is one of the key Mat methods. Most new-style OpenCV functions and methods that produce arrays
1424     call this method for each output array. The method uses the following algorithm:
1425
1426     -# If the current array shape and the type match the new ones, return immediately. Otherwise,
1427        de-reference the previous data by calling Mat::release.
1428     -# Initialize the new header.
1429     -# Allocate the new data of total()\*elemSize() bytes.
1430     -# Allocate the new, associated with the data, reference counter and set it to 1.
1431
1432     Such a scheme makes the memory management robust and efficient at the same time and helps avoid
1433     extra typing for you. This means that usually there is no need to explicitly allocate output arrays.
1434     That is, instead of writing:
1435     @code
1436         Mat color;
1437         ...
1438         Mat gray(color.rows, color.cols, color.depth());
1439         cvtColor(color, gray, COLOR_BGR2GRAY);
1440     @endcode
1441     you can simply write:
1442     @code
1443         Mat color;
1444         ...
1445         Mat gray;
1446         cvtColor(color, gray, COLOR_BGR2GRAY);
1447     @endcode
1448     because cvtColor, as well as the most of OpenCV functions, calls Mat::create() for the output array
1449     internally.
1450     @param rows New number of rows.
1451     @param cols New number of columns.
1452     @param type New matrix type.
1453      */
1454     void create(int rows, int cols, int type);
1455
1456     /** @overload
1457     @param size Alternative new matrix size specification: Size(cols, rows)
1458     @param type New matrix type.
1459     */
1460     void create(Size size, int type);
1461
1462     /** @overload
1463     @param ndims New array dimensionality.
1464     @param sizes Array of integers specifying a new array shape.
1465     @param type New matrix type.
1466     */
1467     void create(int ndims, const int* sizes, int type);
1468
1469     /** @overload
1470     @param sizes Array of integers specifying a new array shape.
1471     @param type New matrix type.
1472     */
1473     void create(const std::vector<int>& sizes, int type);
1474
1475     /** @brief Increments the reference counter.
1476
1477     The method increments the reference counter associated with the matrix data. If the matrix header
1478     points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no
1479     effect in this case. Normally, to avoid memory leaks, the method should not be called explicitly. It
1480     is called implicitly by the matrix assignment operator. The reference counter increment is an atomic
1481     operation on the platforms that support it. Thus, it is safe to operate on the same matrices
1482     asynchronously in different threads.
1483      */
1484     void addref();
1485
1486     /** @brief Decrements the reference counter and deallocates the matrix if needed.
1487
1488     The method decrements the reference counter associated with the matrix data. When the reference
1489     counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers
1490     are set to NULL's. If the matrix header points to an external data set (see Mat::Mat ), the
1491     reference counter is NULL, and the method has no effect in this case.
1492
1493     This method can be called manually to force the matrix data deallocation. But since this method is
1494     automatically called in the destructor, or by any other method that changes the data pointer, it is
1495     usually not needed. The reference counter decrement and check for 0 is an atomic operation on the
1496     platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in
1497     different threads.
1498      */
1499     void release();
1500
1501     //! internal use function, consider to use 'release' method instead; deallocates the matrix data
1502     void deallocate();
1503     //! internal use function; properly re-allocates _size, _step arrays
1504     void copySize(const Mat& m);
1505
1506     /** @brief Reserves space for the certain number of rows.
1507
1508     The method reserves space for sz rows. If the matrix already has enough space to store sz rows,
1509     nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method
1510     emulates the corresponding method of the STL vector class.
1511     @param sz Number of rows.
1512      */
1513     void reserve(size_t sz);
1514
1515     /** @brief Reserves space for the certain number of bytes.
1516
1517     The method reserves space for sz bytes. If the matrix already has enough space to store sz bytes,
1518     nothing happens. If matrix has to be reallocated its previous content could be lost.
1519     @param sz Number of bytes.
1520     */
1521     void reserveBuffer(size_t sz);
1522
1523     /** @brief Changes the number of matrix rows.
1524
1525     The methods change the number of matrix rows. If the matrix is reallocated, the first
1526     min(Mat::rows, sz) rows are preserved. The methods emulate the corresponding methods of the STL
1527     vector class.
1528     @param sz New number of rows.
1529      */
1530     void resize(size_t sz);
1531
1532     /** @overload
1533     @param sz New number of rows.
1534     @param s Value assigned to the newly added elements.
1535      */
1536     void resize(size_t sz, const Scalar& s);
1537
1538     //! internal function
1539     void push_back_(const void* elem);
1540
1541     /** @brief Adds elements to the bottom of the matrix.
1542
1543     The methods add one or more elements to the bottom of the matrix. They emulate the corresponding
1544     method of the STL vector class. When elem is Mat , its type and the number of columns must be the
1545     same as in the container matrix.
1546     @param elem Added element(s).
1547      */
1548     template<typename _Tp> void push_back(const _Tp& elem);
1549
1550     /** @overload
1551     @param elem Added element(s).
1552     */
1553     template<typename _Tp> void push_back(const Mat_<_Tp>& elem);
1554
1555     /** @overload
1556     @param elem Added element(s).
1557     */
1558     template<typename _Tp> void push_back(const std::vector<_Tp>& elem);
1559
1560     /** @overload
1561     @param m Added line(s).
1562     */
1563     void push_back(const Mat& m);
1564
1565     /** @brief Removes elements from the bottom of the matrix.
1566
1567     The method removes one or more rows from the bottom of the matrix.
1568     @param nelems Number of removed rows. If it is greater than the total number of rows, an exception
1569     is thrown.
1570      */
1571     void pop_back(size_t nelems=1);
1572
1573     /** @brief Locates the matrix header within a parent matrix.
1574
1575     After you extracted a submatrix from a matrix using Mat::row, Mat::col, Mat::rowRange,
1576     Mat::colRange, and others, the resultant submatrix points just to the part of the original big
1577     matrix. However, each submatrix contains information (represented by datastart and dataend
1578     fields) that helps reconstruct the original matrix size and the position of the extracted
1579     submatrix within the original matrix. The method locateROI does exactly that.
1580     @param wholeSize Output parameter that contains the size of the whole matrix containing *this*
1581     as a part.
1582     @param ofs Output parameter that contains an offset of *this* inside the whole matrix.
1583      */
1584     void locateROI( Size& wholeSize, Point& ofs ) const;
1585
1586     /** @brief Adjusts a submatrix size and position within the parent matrix.
1587
1588     The method is complimentary to Mat::locateROI . The typical use of these functions is to determine
1589     the submatrix position within the parent matrix and then shift the position somehow. Typically, it
1590     can be required for filtering operations when pixels outside of the ROI should be taken into
1591     account. When all the method parameters are positive, the ROI needs to grow in all directions by the
1592     specified amount, for example:
1593     @code
1594         A.adjustROI(2, 2, 2, 2);
1595     @endcode
1596     In this example, the matrix size is increased by 4 elements in each direction. The matrix is shifted
1597     by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the
1598     filtering with the 5x5 kernel.
1599
1600     adjustROI forces the adjusted ROI to be inside of the parent matrix that is boundaries of the
1601     adjusted ROI are constrained by boundaries of the parent matrix. For example, if the submatrix A is
1602     located in the first row of a parent matrix and you called A.adjustROI(2, 2, 2, 2) then A will not
1603     be increased in the upward direction.
1604
1605     The function is used internally by the OpenCV filtering functions, like filter2D , morphological
1606     operations, and so on.
1607     @param dtop Shift of the top submatrix boundary upwards.
1608     @param dbottom Shift of the bottom submatrix boundary downwards.
1609     @param dleft Shift of the left submatrix boundary to the left.
1610     @param dright Shift of the right submatrix boundary to the right.
1611     @sa copyMakeBorder
1612      */
1613     Mat& adjustROI( int dtop, int dbottom, int dleft, int dright );
1614
1615     /** @brief Extracts a rectangular submatrix.
1616
1617     The operators make a new header for the specified sub-array of \*this . They are the most
1618     generalized forms of Mat::row, Mat::col, Mat::rowRange, and Mat::colRange . For example,
1619     `A(Range(0, 10), Range::all())` is equivalent to `A.rowRange(0, 10)`. Similarly to all of the above,
1620     the operators are O(1) operations, that is, no matrix data is copied.
1621     @param rowRange Start and end row of the extracted submatrix. The upper boundary is not included. To
1622     select all the rows, use Range::all().
1623     @param colRange Start and end column of the extracted submatrix. The upper boundary is not included.
1624     To select all the columns, use Range::all().
1625      */
1626     Mat operator()( Range rowRange, Range colRange ) const;
1627
1628     /** @overload
1629     @param roi Extracted submatrix specified as a rectangle.
1630     */
1631     Mat operator()( const Rect& roi ) const;
1632
1633     /** @overload
1634     @param ranges Array of selected ranges along each array dimension.
1635     */
1636     Mat operator()( const Range* ranges ) const;
1637
1638     /** @overload
1639     @param ranges Array of selected ranges along each array dimension.
1640     */
1641     Mat operator()(const std::vector<Range>& ranges) const;
1642
1643     template<typename _Tp> operator std::vector<_Tp>() const;
1644     template<typename _Tp, int n> operator Vec<_Tp, n>() const;
1645     template<typename _Tp, int m, int n> operator Matx<_Tp, m, n>() const;
1646
1647     template<typename _Tp, std::size_t _Nm> operator std::array<_Tp, _Nm>() const;
1648
1649     /** @brief Reports whether the matrix is continuous or not.
1650
1651     The method returns true if the matrix elements are stored continuously without gaps at the end of
1652     each row. Otherwise, it returns false. Obviously, 1x1 or 1xN matrices are always continuous.
1653     Matrices created with Mat::create are always continuous. But if you extract a part of the matrix
1654     using Mat::col, Mat::diag, and so on, or constructed a matrix header for externally allocated data,
1655     such matrices may no longer have this property.
1656
1657     The continuity flag is stored as a bit in the Mat::flags field and is computed automatically when
1658     you construct a matrix header. Thus, the continuity check is a very fast operation, though
1659     theoretically it could be done as follows:
1660     @code
1661         // alternative implementation of Mat::isContinuous()
1662         bool myCheckMatContinuity(const Mat& m)
1663         {
1664             //return (m.flags & Mat::CONTINUOUS_FLAG) != 0;
1665             return m.rows == 1 || m.step == m.cols*m.elemSize();
1666         }
1667     @endcode
1668     The method is used in quite a few of OpenCV functions. The point is that element-wise operations
1669     (such as arithmetic and logical operations, math functions, alpha blending, color space
1670     transformations, and others) do not depend on the image geometry. Thus, if all the input and output
1671     arrays are continuous, the functions can process them as very long single-row vectors. The example
1672     below illustrates how an alpha-blending function can be implemented:
1673     @code
1674         template<typename T>
1675         void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst)
1676         {
1677             const float alpha_scale = (float)std::numeric_limits<T>::max(),
1678                         inv_scale = 1.f/alpha_scale;
1679
1680             CV_Assert( src1.type() == src2.type() &&
1681                        src1.type() == CV_MAKETYPE(traits::Depth<T>::value, 4) &&
1682                        src1.size() == src2.size());
1683             Size size = src1.size();
1684             dst.create(size, src1.type());
1685
1686             // here is the idiom: check the arrays for continuity and,
1687             // if this is the case,
1688             // treat the arrays as 1D vectors
1689             if( src1.isContinuous() && src2.isContinuous() && dst.isContinuous() )
1690             {
1691                 size.width *= size.height;
1692                 size.height = 1;
1693             }
1694             size.width *= 4;
1695
1696             for( int i = 0; i < size.height; i++ )
1697             {
1698                 // when the arrays are continuous,
1699                 // the outer loop is executed only once
1700                 const T* ptr1 = src1.ptr<T>(i);
1701                 const T* ptr2 = src2.ptr<T>(i);
1702                 T* dptr = dst.ptr<T>(i);
1703
1704                 for( int j = 0; j < size.width; j += 4 )
1705                 {
1706                     float alpha = ptr1[j+3]*inv_scale, beta = ptr2[j+3]*inv_scale;
1707                     dptr[j] = saturate_cast<T>(ptr1[j]*alpha + ptr2[j]*beta);
1708                     dptr[j+1] = saturate_cast<T>(ptr1[j+1]*alpha + ptr2[j+1]*beta);
1709                     dptr[j+2] = saturate_cast<T>(ptr1[j+2]*alpha + ptr2[j+2]*beta);
1710                     dptr[j+3] = saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale);
1711                 }
1712             }
1713         }
1714     @endcode
1715     This approach, while being very simple, can boost the performance of a simple element-operation by
1716     10-20 percents, especially if the image is rather small and the operation is quite simple.
1717
1718     Another OpenCV idiom in this function, a call of Mat::create for the destination array, that
1719     allocates the destination array unless it already has the proper size and type. And while the newly
1720     allocated arrays are always continuous, you still need to check the destination array because
1721     Mat::create does not always allocate a new matrix.
1722      */
1723     bool isContinuous() const;
1724
1725     //! returns true if the matrix is a submatrix of another matrix
1726     bool isSubmatrix() const;
1727
1728     /** @brief Returns the matrix element size in bytes.
1729
1730     The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 ,
1731     the method returns 3\*sizeof(short) or 6.
1732      */
1733     size_t elemSize() const;
1734
1735     /** @brief Returns the size of each matrix element channel in bytes.
1736
1737     The method returns the matrix element channel size in bytes, that is, it ignores the number of
1738     channels. For example, if the matrix type is CV_16SC3 , the method returns sizeof(short) or 2.
1739      */
1740     size_t elemSize1() const;
1741
1742     /** @brief Returns the type of a matrix element.
1743
1744     The method returns a matrix element type. This is an identifier compatible with the CvMat type
1745     system, like CV_16SC3 or 16-bit signed 3-channel array, and so on.
1746      */
1747     int type() const;
1748
1749     /** @brief Returns the depth of a matrix element.
1750
1751     The method returns the identifier of the matrix element depth (the type of each individual channel).
1752     For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of
1753     matrix types contains the following values:
1754     -   CV_8U - 8-bit unsigned integers ( 0..255 )
1755     -   CV_8S - 8-bit signed integers ( -128..127 )
1756     -   CV_16U - 16-bit unsigned integers ( 0..65535 )
1757     -   CV_16S - 16-bit signed integers ( -32768..32767 )
1758     -   CV_32S - 32-bit signed integers ( -2147483648..2147483647 )
1759     -   CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN )
1760     -   CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN )
1761      */
1762     int depth() const;
1763
1764     /** @brief Returns the number of matrix channels.
1765
1766     The method returns the number of matrix channels.
1767      */
1768     int channels() const;
1769
1770     /** @brief Returns a normalized step.
1771
1772     The method returns a matrix step divided by Mat::elemSize1() . It can be useful to quickly access an
1773     arbitrary matrix element.
1774      */
1775     size_t step1(int i=0) const;
1776
1777     /** @brief Returns true if the array has no elements.
1778
1779     The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and
1780     resize() methods `M.total() == 0` does not imply that `M.data == NULL`.
1781      */
1782     bool empty() const;
1783
1784     /** @brief Returns the total number of array elements.
1785
1786     The method returns the number of array elements (a number of pixels if the array represents an
1787     image).
1788      */
1789     size_t total() const;
1790
1791     /** @brief Returns the total number of array elements.
1792
1793      The method returns the number of elements within a certain sub-array slice with startDim <= dim < endDim
1794      */
1795     size_t total(int startDim, int endDim=INT_MAX) const;
1796
1797     /**
1798      * @param elemChannels Number of channels or number of columns the matrix should have.
1799      *                     For a 2-D matrix, when the matrix has only 1 column, then it should have
1800      *                     elemChannels channels; When the matrix has only 1 channel,
1801      *                     then it should have elemChannels columns.
1802      *                     For a 3-D matrix, it should have only one channel. Furthermore,
1803      *                     if the number of planes is not one, then the number of rows
1804      *                     within every plane has to be 1; if the number of rows within
1805      *                     every plane is not 1, then the number of planes has to be 1.
1806      * @param depth The depth the matrix should have. Set it to -1 when any depth is fine.
1807      * @param requireContinuous Set it to true to require the matrix to be continuous
1808      * @return -1 if the requirement is not satisfied.
1809      *         Otherwise, it returns the number of elements in the matrix. Note
1810      *         that an element may have multiple channels.
1811      *
1812      * The following code demonstrates its usage for a 2-d matrix:
1813      * @snippet snippets/core_mat_checkVector.cpp example-2d
1814      *
1815      * The following code demonstrates its usage for a 3-d matrix:
1816      * @snippet snippets/core_mat_checkVector.cpp example-3d
1817      */
1818     int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
1819
1820     /** @brief Returns a pointer to the specified matrix row.
1821
1822     The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in
1823     Mat::isContinuous to know how to use these methods.
1824     @param i0 A 0-based row index.
1825      */
1826     uchar* ptr(int i0=0);
1827     /** @overload */
1828     const uchar* ptr(int i0=0) const;
1829
1830     /** @overload
1831     @param row Index along the dimension 0
1832     @param col Index along the dimension 1
1833     */
1834     uchar* ptr(int row, int col);
1835     /** @overload
1836     @param row Index along the dimension 0
1837     @param col Index along the dimension 1
1838     */
1839     const uchar* ptr(int row, int col) const;
1840
1841     /** @overload */
1842     uchar* ptr(int i0, int i1, int i2);
1843     /** @overload */
1844     const uchar* ptr(int i0, int i1, int i2) const;
1845
1846     /** @overload */
1847     uchar* ptr(const int* idx);
1848     /** @overload */
1849     const uchar* ptr(const int* idx) const;
1850     /** @overload */
1851     template<int n> uchar* ptr(const Vec<int, n>& idx);
1852     /** @overload */
1853     template<int n> const uchar* ptr(const Vec<int, n>& idx) const;
1854
1855     /** @overload */
1856     template<typename _Tp> _Tp* ptr(int i0=0);
1857     /** @overload */
1858     template<typename _Tp> const _Tp* ptr(int i0=0) const;
1859     /** @overload
1860     @param row Index along the dimension 0
1861     @param col Index along the dimension 1
1862     */
1863     template<typename _Tp> _Tp* ptr(int row, int col);
1864     /** @overload
1865     @param row Index along the dimension 0
1866     @param col Index along the dimension 1
1867     */
1868     template<typename _Tp> const _Tp* ptr(int row, int col) const;
1869     /** @overload */
1870     template<typename _Tp> _Tp* ptr(int i0, int i1, int i2);
1871     /** @overload */
1872     template<typename _Tp> const _Tp* ptr(int i0, int i1, int i2) const;
1873     /** @overload */
1874     template<typename _Tp> _Tp* ptr(const int* idx);
1875     /** @overload */
1876     template<typename _Tp> const _Tp* ptr(const int* idx) const;
1877     /** @overload */
1878     template<typename _Tp, int n> _Tp* ptr(const Vec<int, n>& idx);
1879     /** @overload */
1880     template<typename _Tp, int n> const _Tp* ptr(const Vec<int, n>& idx) const;
1881
1882     /** @brief Returns a reference to the specified array element.
1883
1884     The template methods return a reference to the specified array element. For the sake of higher
1885     performance, the index range checks are only performed in the Debug configuration.
1886
1887     Note that the variants with a single index (i) can be used to access elements of single-row or
1888     single-column 2-dimensional arrays. That is, if, for example, A is a 1 x N floating-point matrix and
1889     B is an M x 1 integer matrix, you can simply write `A.at<float>(k+4)` and `B.at<int>(2*i+1)`
1890     instead of `A.at<float>(0,k+4)` and `B.at<int>(2*i+1,0)`, respectively.
1891
1892     The example below initializes a Hilbert matrix:
1893     @code
1894         Mat H(100, 100, CV_64F);
1895         for(int i = 0; i < H.rows; i++)
1896             for(int j = 0; j < H.cols; j++)
1897                 H.at<double>(i,j)=1./(i+j+1);
1898     @endcode
1899
1900     Keep in mind that the size identifier used in the at operator cannot be chosen at random. It depends
1901     on the image from which you are trying to retrieve the data. The table below gives a better insight in this:
1902      - If matrix is of type `CV_8U` then use `Mat.at<uchar>(y,x)`.
1903      - If matrix is of type `CV_8S` then use `Mat.at<schar>(y,x)`.
1904      - If matrix is of type `CV_16U` then use `Mat.at<ushort>(y,x)`.
1905      - If matrix is of type `CV_16S` then use `Mat.at<short>(y,x)`.
1906      - If matrix is of type `CV_32S`  then use `Mat.at<int>(y,x)`.
1907      - If matrix is of type `CV_32F`  then use `Mat.at<float>(y,x)`.
1908      - If matrix is of type `CV_64F` then use `Mat.at<double>(y,x)`.
1909
1910     @param i0 Index along the dimension 0
1911      */
1912     template<typename _Tp> _Tp& at(int i0=0);
1913     /** @overload
1914     @param i0 Index along the dimension 0
1915     */
1916     template<typename _Tp> const _Tp& at(int i0=0) const;
1917     /** @overload
1918     @param row Index along the dimension 0
1919     @param col Index along the dimension 1
1920     */
1921     template<typename _Tp> _Tp& at(int row, int col);
1922     /** @overload
1923     @param row Index along the dimension 0
1924     @param col Index along the dimension 1
1925     */
1926     template<typename _Tp> const _Tp& at(int row, int col) const;
1927
1928     /** @overload
1929     @param i0 Index along the dimension 0
1930     @param i1 Index along the dimension 1
1931     @param i2 Index along the dimension 2
1932     */
1933     template<typename _Tp> _Tp& at(int i0, int i1, int i2);
1934     /** @overload
1935     @param i0 Index along the dimension 0
1936     @param i1 Index along the dimension 1
1937     @param i2 Index along the dimension 2
1938     */
1939     template<typename _Tp> const _Tp& at(int i0, int i1, int i2) const;
1940
1941     /** @overload
1942     @param idx Array of Mat::dims indices.
1943     */
1944     template<typename _Tp> _Tp& at(const int* idx);
1945     /** @overload
1946     @param idx Array of Mat::dims indices.
1947     */
1948     template<typename _Tp> const _Tp& at(const int* idx) const;
1949
1950     /** @overload */
1951     template<typename _Tp, int n> _Tp& at(const Vec<int, n>& idx);
1952     /** @overload */
1953     template<typename _Tp, int n> const _Tp& at(const Vec<int, n>& idx) const;
1954
1955     /** @overload
1956     special versions for 2D arrays (especially convenient for referencing image pixels)
1957     @param pt Element position specified as Point(j,i) .
1958     */
1959     template<typename _Tp> _Tp& at(Point pt);
1960     /** @overload
1961     special versions for 2D arrays (especially convenient for referencing image pixels)
1962     @param pt Element position specified as Point(j,i) .
1963     */
1964     template<typename _Tp> const _Tp& at(Point pt) const;
1965
1966     /** @brief Returns the matrix iterator and sets it to the first matrix element.
1967
1968     The methods return the matrix read-only or read-write iterators. The use of matrix iterators is very
1969     similar to the use of bi-directional STL iterators. In the example below, the alpha blending
1970     function is rewritten using the matrix iterators:
1971     @code
1972         template<typename T>
1973         void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst)
1974         {
1975             typedef Vec<T, 4> VT;
1976
1977             const float alpha_scale = (float)std::numeric_limits<T>::max(),
1978                         inv_scale = 1.f/alpha_scale;
1979
1980             CV_Assert( src1.type() == src2.type() &&
1981                        src1.type() == traits::Type<VT>::value &&
1982                        src1.size() == src2.size());
1983             Size size = src1.size();
1984             dst.create(size, src1.type());
1985
1986             MatConstIterator_<VT> it1 = src1.begin<VT>(), it1_end = src1.end<VT>();
1987             MatConstIterator_<VT> it2 = src2.begin<VT>();
1988             MatIterator_<VT> dst_it = dst.begin<VT>();
1989
1990             for( ; it1 != it1_end; ++it1, ++it2, ++dst_it )
1991             {
1992                 VT pix1 = *it1, pix2 = *it2;
1993                 float alpha = pix1[3]*inv_scale, beta = pix2[3]*inv_scale;
1994                 *dst_it = VT(saturate_cast<T>(pix1[0]*alpha + pix2[0]*beta),
1995                              saturate_cast<T>(pix1[1]*alpha + pix2[1]*beta),
1996                              saturate_cast<T>(pix1[2]*alpha + pix2[2]*beta),
1997                              saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale));
1998             }
1999         }
2000     @endcode
2001      */
2002     template<typename _Tp> MatIterator_<_Tp> begin();
2003     template<typename _Tp> MatConstIterator_<_Tp> begin() const;
2004
2005     /** @brief Returns the matrix iterator and sets it to the after-last matrix element.
2006
2007     The methods return the matrix read-only or read-write iterators, set to the point following the last
2008     matrix element.
2009      */
2010     template<typename _Tp> MatIterator_<_Tp> end();
2011     template<typename _Tp> MatConstIterator_<_Tp> end() const;
2012
2013     /** @brief Runs the given functor over all matrix elements in parallel.
2014
2015     The operation passed as argument has to be a function pointer, a function object or a lambda(C++11).
2016
2017     Example 1. All of the operations below put 0xFF the first channel of all matrix elements:
2018     @code
2019         Mat image(1920, 1080, CV_8UC3);
2020         typedef cv::Point3_<uint8_t> Pixel;
2021
2022         // first. raw pointer access.
2023         for (int r = 0; r < image.rows; ++r) {
2024             Pixel* ptr = image.ptr<Pixel>(r, 0);
2025             const Pixel* ptr_end = ptr + image.cols;
2026             for (; ptr != ptr_end; ++ptr) {
2027                 ptr->x = 255;
2028             }
2029         }
2030
2031         // Using MatIterator. (Simple but there are a Iterator's overhead)
2032         for (Pixel &p : cv::Mat_<Pixel>(image)) {
2033             p.x = 255;
2034         }
2035
2036         // Parallel execution with function object.
2037         struct Operator {
2038             void operator ()(Pixel &pixel, const int * position) {
2039                 pixel.x = 255;
2040             }
2041         };
2042         image.forEach<Pixel>(Operator());
2043
2044         // Parallel execution using C++11 lambda.
2045         image.forEach<Pixel>([](Pixel &p, const int * position) -> void {
2046             p.x = 255;
2047         });
2048     @endcode
2049     Example 2. Using the pixel's position:
2050     @code
2051         // Creating 3D matrix (255 x 255 x 255) typed uint8_t
2052         // and initialize all elements by the value which equals elements position.
2053         // i.e. pixels (x,y,z) = (1,2,3) is (b,g,r) = (1,2,3).
2054
2055         int sizes[] = { 255, 255, 255 };
2056         typedef cv::Point3_<uint8_t> Pixel;
2057
2058         Mat_<Pixel> image = Mat::zeros(3, sizes, CV_8UC3);
2059
2060         image.forEach<Pixel>([&](Pixel& pixel, const int position[]) -> void {
2061             pixel.x = position[0];
2062             pixel.y = position[1];
2063             pixel.z = position[2];
2064         });
2065     @endcode
2066      */
2067     template<typename _Tp, typename Functor> void forEach(const Functor& operation);
2068     /** @overload */
2069     template<typename _Tp, typename Functor> void forEach(const Functor& operation) const;
2070
2071     Mat(Mat&& m);
2072     Mat& operator = (Mat&& m);
2073
2074     enum { MAGIC_VAL  = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
2075     enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
2076
2077     /*! includes several bit-fields:
2078          - the magic signature
2079          - continuity flag
2080          - depth
2081          - number of channels
2082      */
2083     int flags;
2084     //! the matrix dimensionality, >= 2
2085     int dims;
2086     //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
2087     int rows, cols;
2088     //! pointer to the data
2089     uchar* data;
2090
2091     //! helper fields used in locateROI and adjustROI
2092     const uchar* datastart;
2093     const uchar* dataend;
2094     const uchar* datalimit;
2095
2096     //! custom allocator
2097     MatAllocator* allocator;
2098     //! and the standard allocator
2099     static MatAllocator* getStdAllocator();
2100     static MatAllocator* getDefaultAllocator();
2101     static void setDefaultAllocator(MatAllocator* allocator);
2102
2103     //! internal use method: updates the continuity flag
2104     void updateContinuityFlag();
2105
2106     //! interaction with UMat
2107     UMatData* u;
2108
2109     MatSize size;
2110     MatStep step;
2111
2112 protected:
2113     template<typename _Tp, typename Functor> void forEach_impl(const Functor& operation);
2114 };
2115
2116
2117 ///////////////////////////////// Mat_<_Tp> ////////////////////////////////////
2118
2119 /** @brief Template matrix class derived from Mat
2120
2121 @code{.cpp}
2122     template<typename _Tp> class Mat_ : public Mat
2123     {
2124     public:
2125         // ... some specific methods
2126         //         and
2127         // no new extra fields
2128     };
2129 @endcode
2130 The class `Mat_<_Tp>` is a *thin* template wrapper on top of the Mat class. It does not have any
2131 extra data fields. Nor this class nor Mat has any virtual methods. Thus, references or pointers to
2132 these two classes can be freely but carefully converted one to another. For example:
2133 @code{.cpp}
2134     // create a 100x100 8-bit matrix
2135     Mat M(100,100,CV_8U);
2136     // this will be compiled fine. no any data conversion will be done.
2137     Mat_<float>& M1 = (Mat_<float>&)M;
2138     // the program is likely to crash at the statement below
2139     M1(99,99) = 1.f;
2140 @endcode
2141 While Mat is sufficient in most cases, Mat_ can be more convenient if you use a lot of element
2142 access operations and if you know matrix type at the compilation time. Note that
2143 `Mat::at(int y,int x)` and `Mat_::operator()(int y,int x)` do absolutely the same
2144 and run at the same speed, but the latter is certainly shorter:
2145 @code{.cpp}
2146     Mat_<double> M(20,20);
2147     for(int i = 0; i < M.rows; i++)
2148         for(int j = 0; j < M.cols; j++)
2149             M(i,j) = 1./(i+j+1);
2150     Mat E, V;
2151     eigen(M,E,V);
2152     cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
2153 @endcode
2154 To use Mat_ for multi-channel images/matrices, pass Vec as a Mat_ parameter:
2155 @code{.cpp}
2156     // allocate a 320x240 color image and fill it with green (in RGB space)
2157     Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
2158     // now draw a diagonal white line
2159     for(int i = 0; i < 100; i++)
2160         img(i,i)=Vec3b(255,255,255);
2161     // and now scramble the 2nd (red) channel of each pixel
2162     for(int i = 0; i < img.rows; i++)
2163         for(int j = 0; j < img.cols; j++)
2164             img(i,j)[2] ^= (uchar)(i ^ j);
2165 @endcode
2166 Mat_ is fully compatible with C++11 range-based for loop. For example such loop
2167 can be used to safely apply look-up table:
2168 @code{.cpp}
2169 void applyTable(Mat_<uchar>& I, const uchar* const table)
2170 {
2171     for(auto& pixel : I)
2172     {
2173         pixel = table[pixel];
2174     }
2175 }
2176 @endcode
2177  */
2178 template<typename _Tp> class Mat_ : public Mat
2179 {
2180 public:
2181     typedef _Tp value_type;
2182     typedef typename DataType<_Tp>::channel_type channel_type;
2183     typedef MatIterator_<_Tp> iterator;
2184     typedef MatConstIterator_<_Tp> const_iterator;
2185
2186     //! default constructor
2187     Mat_();
2188     //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type)
2189     Mat_(int _rows, int _cols);
2190     //! constructor that sets each matrix element to specified value
2191     Mat_(int _rows, int _cols, const _Tp& value);
2192     //! equivalent to Mat(_size, DataType<_Tp>::type)
2193     explicit Mat_(Size _size);
2194     //! constructor that sets each matrix element to specified value
2195     Mat_(Size _size, const _Tp& value);
2196     //! n-dim array constructor
2197     Mat_(int _ndims, const int* _sizes);
2198     //! n-dim array constructor that sets each matrix element to specified value
2199     Mat_(int _ndims, const int* _sizes, const _Tp& value);
2200     //! copy/conversion constructor. If m is of different type, it's converted
2201     Mat_(const Mat& m);
2202     //! copy constructor
2203     Mat_(const Mat_& m);
2204     //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type
2205     Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP);
2206     //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type
2207     Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0);
2208     //! selects a submatrix
2209     Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all());
2210     //! selects a submatrix
2211     Mat_(const Mat_& m, const Rect& roi);
2212     //! selects a submatrix, n-dim version
2213     Mat_(const Mat_& m, const Range* ranges);
2214     //! selects a submatrix, n-dim version
2215     Mat_(const Mat_& m, const std::vector<Range>& ranges);
2216     //! from a matrix expression
2217     explicit Mat_(const MatExpr& e);
2218     //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column
2219     explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false);
2220     template<int n> explicit Mat_(const Vec<typename DataType<_Tp>::channel_type, n>& vec, bool copyData=true);
2221     template<int m, int n> explicit Mat_(const Matx<typename DataType<_Tp>::channel_type, m, n>& mtx, bool copyData=true);
2222     explicit Mat_(const Point_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
2223     explicit Mat_(const Point3_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
2224     explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer);
2225
2226     Mat_(std::initializer_list<_Tp> values);
2227     explicit Mat_(const std::initializer_list<int> sizes, const std::initializer_list<_Tp> values);
2228
2229     template <std::size_t _Nm> explicit Mat_(const std::array<_Tp, _Nm>& arr, bool copyData=false);
2230
2231     Mat_& operator = (const Mat& m);
2232     Mat_& operator = (const Mat_& m);
2233     //! set all the elements to s.
2234     Mat_& operator = (const _Tp& s);
2235     //! assign a matrix expression
2236     Mat_& operator = (const MatExpr& e);
2237
2238     //! iterators; they are smart enough to skip gaps in the end of rows
2239     iterator begin();
2240     iterator end();
2241     const_iterator begin() const;
2242     const_iterator end() const;
2243
2244     //! template methods for for operation over all matrix elements.
2245     // the operations take care of skipping gaps in the end of rows (if any)
2246     template<typename Functor> void forEach(const Functor& operation);
2247     template<typename Functor> void forEach(const Functor& operation) const;
2248
2249     //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type)
2250     void create(int _rows, int _cols);
2251     //! equivalent to Mat::create(_size, DataType<_Tp>::type)
2252     void create(Size _size);
2253     //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type)
2254     void create(int _ndims, const int* _sizes);
2255     //! equivalent to Mat::release()
2256     void release();
2257     //! cross-product
2258     Mat_ cross(const Mat_& m) const;
2259     //! data type conversion
2260     template<typename T2> operator Mat_<T2>() const;
2261     //! overridden forms of Mat::row() etc.
2262     Mat_ row(int y) const;
2263     Mat_ col(int x) const;
2264     Mat_ diag(int d=0) const;
2265     Mat_ clone() const CV_NODISCARD;
2266
2267     //! overridden forms of Mat::elemSize() etc.
2268     size_t elemSize() const;
2269     size_t elemSize1() const;
2270     int type() const;
2271     int depth() const;
2272     int channels() const;
2273     size_t step1(int i=0) const;
2274     //! returns step()/sizeof(_Tp)
2275     size_t stepT(int i=0) const;
2276
2277     //! overridden forms of Mat::zeros() etc. Data type is omitted, of course
2278     static MatExpr zeros(int rows, int cols);
2279     static MatExpr zeros(Size size);
2280     static MatExpr zeros(int _ndims, const int* _sizes);
2281     static MatExpr ones(int rows, int cols);
2282     static MatExpr ones(Size size);
2283     static MatExpr ones(int _ndims, const int* _sizes);
2284     static MatExpr eye(int rows, int cols);
2285     static MatExpr eye(Size size);
2286
2287     //! some more overridden methods
2288     Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright );
2289     Mat_ operator()( const Range& rowRange, const Range& colRange ) const;
2290     Mat_ operator()( const Rect& roi ) const;
2291     Mat_ operator()( const Range* ranges ) const;
2292     Mat_ operator()(const std::vector<Range>& ranges) const;
2293
2294     //! more convenient forms of row and element access operators
2295     _Tp* operator [](int y);
2296     const _Tp* operator [](int y) const;
2297
2298     //! returns reference to the specified element
2299     _Tp& operator ()(const int* idx);
2300     //! returns read-only reference to the specified element
2301     const _Tp& operator ()(const int* idx) const;
2302
2303     //! returns reference to the specified element
2304     template<int n> _Tp& operator ()(const Vec<int, n>& idx);
2305     //! returns read-only reference to the specified element
2306     template<int n> const _Tp& operator ()(const Vec<int, n>& idx) const;
2307
2308     //! returns reference to the specified element (1D case)
2309     _Tp& operator ()(int idx0);
2310     //! returns read-only reference to the specified element (1D case)
2311     const _Tp& operator ()(int idx0) const;
2312     //! returns reference to the specified element (2D case)
2313     _Tp& operator ()(int row, int col);
2314     //! returns read-only reference to the specified element (2D case)
2315     const _Tp& operator ()(int row, int col) const;
2316     //! returns reference to the specified element (3D case)
2317     _Tp& operator ()(int idx0, int idx1, int idx2);
2318     //! returns read-only reference to the specified element (3D case)
2319     const _Tp& operator ()(int idx0, int idx1, int idx2) const;
2320
2321     _Tp& operator ()(Point pt);
2322     const _Tp& operator ()(Point pt) const;
2323
2324     //! conversion to vector.
2325     operator std::vector<_Tp>() const;
2326
2327     //! conversion to array.
2328     template<std::size_t _Nm> operator std::array<_Tp, _Nm>() const;
2329
2330     //! conversion to Vec
2331     template<int n> operator Vec<typename DataType<_Tp>::channel_type, n>() const;
2332     //! conversion to Matx
2333     template<int m, int n> operator Matx<typename DataType<_Tp>::channel_type, m, n>() const;
2334
2335     Mat_(Mat_&& m);
2336     Mat_& operator = (Mat_&& m);
2337
2338     Mat_(Mat&& m);
2339     Mat_& operator = (Mat&& m);
2340
2341     Mat_(MatExpr&& e);
2342 };
2343
2344 typedef Mat_<uchar> Mat1b;
2345 typedef Mat_<Vec2b> Mat2b;
2346 typedef Mat_<Vec3b> Mat3b;
2347 typedef Mat_<Vec4b> Mat4b;
2348
2349 typedef Mat_<short> Mat1s;
2350 typedef Mat_<Vec2s> Mat2s;
2351 typedef Mat_<Vec3s> Mat3s;
2352 typedef Mat_<Vec4s> Mat4s;
2353
2354 typedef Mat_<ushort> Mat1w;
2355 typedef Mat_<Vec2w> Mat2w;
2356 typedef Mat_<Vec3w> Mat3w;
2357 typedef Mat_<Vec4w> Mat4w;
2358
2359 typedef Mat_<int>   Mat1i;
2360 typedef Mat_<Vec2i> Mat2i;
2361 typedef Mat_<Vec3i> Mat3i;
2362 typedef Mat_<Vec4i> Mat4i;
2363
2364 typedef Mat_<float> Mat1f;
2365 typedef Mat_<Vec2f> Mat2f;
2366 typedef Mat_<Vec3f> Mat3f;
2367 typedef Mat_<Vec4f> Mat4f;
2368
2369 typedef Mat_<double> Mat1d;
2370 typedef Mat_<Vec2d> Mat2d;
2371 typedef Mat_<Vec3d> Mat3d;
2372 typedef Mat_<Vec4d> Mat4d;
2373
2374 /** @todo document */
2375 class CV_EXPORTS UMat
2376 {
2377 public:
2378     //! default constructor
2379     UMat(UMatUsageFlags usageFlags = USAGE_DEFAULT);
2380     //! constructs 2D matrix of the specified size and type
2381     // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
2382     UMat(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
2383     UMat(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
2384     //! constructs 2D matrix and fills it with the specified value _s.
2385     UMat(int rows, int cols, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
2386     UMat(Size size, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
2387
2388     //! constructs n-dimensional matrix
2389     UMat(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
2390     UMat(int ndims, const int* sizes, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
2391
2392     //! copy constructor
2393     UMat(const UMat& m);
2394
2395     //! creates a matrix header for a part of the bigger matrix
2396     UMat(const UMat& m, const Range& rowRange, const Range& colRange=Range::all());
2397     UMat(const UMat& m, const Rect& roi);
2398     UMat(const UMat& m, const Range* ranges);
2399     UMat(const UMat& m, const std::vector<Range>& ranges);
2400
2401     // FIXIT copyData=false is not implemented, drop this in favor of cv::Mat (OpenCV 5.0)
2402     //! builds matrix from std::vector with or without copying the data
2403     template<typename _Tp> explicit UMat(const std::vector<_Tp>& vec, bool copyData=false);
2404
2405     //! destructor - calls release()
2406     ~UMat();
2407     //! assignment operators
2408     UMat& operator = (const UMat& m);
2409
2410     Mat getMat(AccessFlag flags) const;
2411
2412     //! returns a new matrix header for the specified row
2413     UMat row(int y) const;
2414     //! returns a new matrix header for the specified column
2415     UMat col(int x) const;
2416     //! ... for the specified row span
2417     UMat rowRange(int startrow, int endrow) const;
2418     UMat rowRange(const Range& r) const;
2419     //! ... for the specified column span
2420     UMat colRange(int startcol, int endcol) const;
2421     UMat colRange(const Range& r) const;
2422     //! ... for the specified diagonal
2423     //! (d=0 - the main diagonal,
2424     //!  >0 - a diagonal from the upper half,
2425     //!  <0 - a diagonal from the lower half)
2426     UMat diag(int d=0) const;
2427     //! constructs a square diagonal matrix which main diagonal is vector "d"
2428     static UMat diag(const UMat& d);
2429
2430     //! returns deep copy of the matrix, i.e. the data is copied
2431     UMat clone() const CV_NODISCARD;
2432     //! copies the matrix content to "m".
2433     // It calls m.create(this->size(), this->type()).
2434     void copyTo( OutputArray m ) const;
2435     //! copies those matrix elements to "m" that are marked with non-zero mask elements.
2436     void copyTo( OutputArray m, InputArray mask ) const;
2437     //! converts matrix to another datatype with optional scaling. See cvConvertScale.
2438     void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
2439
2440     void assignTo( UMat& m, int type=-1 ) const;
2441
2442     //! sets every matrix element to s
2443     UMat& operator = (const Scalar& s);
2444     //! sets some of the matrix elements to s, according to the mask
2445     UMat& setTo(InputArray value, InputArray mask=noArray());
2446     //! creates alternative matrix header for the same data, with different
2447     // number of channels and/or different number of rows. see cvReshape.
2448     UMat reshape(int cn, int rows=0) const;
2449     UMat reshape(int cn, int newndims, const int* newsz) const;
2450
2451     //! matrix transposition by means of matrix expressions
2452     UMat t() const;
2453     //! matrix inversion by means of matrix expressions
2454     UMat inv(int method=DECOMP_LU) const;
2455     //! per-element matrix multiplication by means of matrix expressions
2456     UMat mul(InputArray m, double scale=1) const;
2457
2458     //! computes dot-product
2459     double dot(InputArray m) const;
2460
2461     //! Matlab-style matrix initialization
2462     static UMat zeros(int rows, int cols, int type);
2463     static UMat zeros(Size size, int type);
2464     static UMat zeros(int ndims, const int* sz, int type);
2465     static UMat ones(int rows, int cols, int type);
2466     static UMat ones(Size size, int type);
2467     static UMat ones(int ndims, const int* sz, int type);
2468     static UMat eye(int rows, int cols, int type);
2469     static UMat eye(Size size, int type);
2470
2471     //! allocates new matrix data unless the matrix already has specified size and type.
2472     // previous data is unreferenced if needed.
2473     void create(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
2474     void create(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
2475     void create(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
2476     void create(const std::vector<int>& sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
2477
2478     //! increases the reference counter; use with care to avoid memleaks
2479     void addref();
2480     //! decreases reference counter;
2481     // deallocates the data when reference counter reaches 0.
2482     void release();
2483
2484     //! deallocates the matrix data
2485     void deallocate();
2486     //! internal use function; properly re-allocates _size, _step arrays
2487     void copySize(const UMat& m);
2488
2489     //! locates matrix header within a parent matrix. See below
2490     void locateROI( Size& wholeSize, Point& ofs ) const;
2491     //! moves/resizes the current matrix ROI inside the parent matrix.
2492     UMat& adjustROI( int dtop, int dbottom, int dleft, int dright );
2493     //! extracts a rectangular sub-matrix
2494     // (this is a generalized form of row, rowRange etc.)
2495     UMat operator()( Range rowRange, Range colRange ) const;
2496     UMat operator()( const Rect& roi ) const;
2497     UMat operator()( const Range* ranges ) const;
2498     UMat operator()(const std::vector<Range>& ranges) const;
2499
2500     //! returns true iff the matrix data is continuous
2501     // (i.e. when there are no gaps between successive rows).
2502     // similar to CV_IS_MAT_CONT(cvmat->type)
2503     bool isContinuous() const;
2504
2505     //! returns true if the matrix is a submatrix of another matrix
2506     bool isSubmatrix() const;
2507
2508     //! returns element size in bytes,
2509     // similar to CV_ELEM_SIZE(cvmat->type)
2510     size_t elemSize() const;
2511     //! returns the size of element channel in bytes.
2512     size_t elemSize1() const;
2513     //! returns element type, similar to CV_MAT_TYPE(cvmat->type)
2514     int type() const;
2515     //! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
2516     int depth() const;
2517     //! returns element type, similar to CV_MAT_CN(cvmat->type)
2518     int channels() const;
2519     //! returns step/elemSize1()
2520     size_t step1(int i=0) const;
2521     //! returns true if matrix data is NULL
2522     bool empty() const;
2523     //! returns the total number of matrix elements
2524     size_t total() const;
2525
2526     //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
2527     int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
2528
2529     UMat(UMat&& m);
2530     UMat& operator = (UMat&& m);
2531
2532     /*! Returns the OpenCL buffer handle on which UMat operates on.
2533         The UMat instance should be kept alive during the use of the handle to prevent the buffer to be
2534         returned to the OpenCV buffer pool.
2535      */
2536     void* handle(AccessFlag accessFlags) const;
2537     void ndoffset(size_t* ofs) const;
2538
2539     enum { MAGIC_VAL  = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
2540     enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
2541
2542     /*! includes several bit-fields:
2543          - the magic signature
2544          - continuity flag
2545          - depth
2546          - number of channels
2547      */
2548     int flags;
2549     //! the matrix dimensionality, >= 2
2550     int dims;
2551     //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
2552     int rows, cols;
2553
2554     //! custom allocator
2555     MatAllocator* allocator;
2556     UMatUsageFlags usageFlags; // usage flags for allocator
2557     //! and the standard allocator
2558     static MatAllocator* getStdAllocator();
2559
2560     //! internal use method: updates the continuity flag
2561     void updateContinuityFlag();
2562
2563     // black-box container of UMat data
2564     UMatData* u;
2565
2566     // offset of the submatrix (or 0)
2567     size_t offset;
2568
2569     MatSize size;
2570     MatStep step;
2571
2572 protected:
2573 };
2574
2575
2576 /////////////////////////// multi-dimensional sparse matrix //////////////////////////
2577
2578 /** @brief The class SparseMat represents multi-dimensional sparse numerical arrays.
2579
2580 Such a sparse array can store elements of any type that Mat can store. *Sparse* means that only
2581 non-zero elements are stored (though, as a result of operations on a sparse matrix, some of its
2582 stored elements can actually become 0. It is up to you to detect such elements and delete them
2583 using SparseMat::erase ). The non-zero elements are stored in a hash table that grows when it is
2584 filled so that the search time is O(1) in average (regardless of whether element is there or not).
2585 Elements can be accessed using the following methods:
2586 -   Query operations (SparseMat::ptr and the higher-level SparseMat::ref, SparseMat::value and
2587     SparseMat::find), for example:
2588     @code
2589         const int dims = 5;
2590         int size[5] = {10, 10, 10, 10, 10};
2591         SparseMat sparse_mat(dims, size, CV_32F);
2592         for(int i = 0; i < 1000; i++)
2593         {
2594             int idx[dims];
2595             for(int k = 0; k < dims; k++)
2596                 idx[k] = rand() % size[k];
2597             sparse_mat.ref<float>(idx) += 1.f;
2598         }
2599         cout << "nnz = " << sparse_mat.nzcount() << endl;
2600     @endcode
2601 -   Sparse matrix iterators. They are similar to MatIterator but different from NAryMatIterator.
2602     That is, the iteration loop is familiar to STL users:
2603     @code
2604         // prints elements of a sparse floating-point matrix
2605         // and the sum of elements.
2606         SparseMatConstIterator_<float>
2607             it = sparse_mat.begin<float>(),
2608             it_end = sparse_mat.end<float>();
2609         double s = 0;
2610         int dims = sparse_mat.dims();
2611         for(; it != it_end; ++it)
2612         {
2613             // print element indices and the element value
2614             const SparseMat::Node* n = it.node();
2615             printf("(");
2616             for(int i = 0; i < dims; i++)
2617                 printf("%d%s", n->idx[i], i < dims-1 ? ", " : ")");
2618             printf(": %g\n", it.value<float>());
2619             s += *it;
2620         }
2621         printf("Element sum is %g\n", s);
2622     @endcode
2623     If you run this loop, you will notice that elements are not enumerated in a logical order
2624     (lexicographical, and so on). They come in the same order as they are stored in the hash table
2625     (semi-randomly). You may collect pointers to the nodes and sort them to get the proper ordering.
2626     Note, however, that pointers to the nodes may become invalid when you add more elements to the
2627     matrix. This may happen due to possible buffer reallocation.
2628 -   Combination of the above 2 methods when you need to process 2 or more sparse matrices
2629     simultaneously. For example, this is how you can compute unnormalized cross-correlation of the 2
2630     floating-point sparse matrices:
2631     @code
2632         double cross_corr(const SparseMat& a, const SparseMat& b)
2633         {
2634             const SparseMat *_a = &a, *_b = &b;
2635             // if b contains less elements than a,
2636             // it is faster to iterate through b
2637             if(_a->nzcount() > _b->nzcount())
2638                 std::swap(_a, _b);
2639             SparseMatConstIterator_<float> it = _a->begin<float>(),
2640                                            it_end = _a->end<float>();
2641             double ccorr = 0;
2642             for(; it != it_end; ++it)
2643             {
2644                 // take the next element from the first matrix
2645                 float avalue = *it;
2646                 const Node* anode = it.node();
2647                 // and try to find an element with the same index in the second matrix.
2648                 // since the hash value depends only on the element index,
2649                 // reuse the hash value stored in the node
2650                 float bvalue = _b->value<float>(anode->idx,&anode->hashval);
2651                 ccorr += avalue*bvalue;
2652             }
2653             return ccorr;
2654         }
2655     @endcode
2656  */
2657 class CV_EXPORTS SparseMat
2658 {
2659 public:
2660     typedef SparseMatIterator iterator;
2661     typedef SparseMatConstIterator const_iterator;
2662
2663     enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 };
2664
2665     //! the sparse matrix header
2666     struct CV_EXPORTS Hdr
2667     {
2668         Hdr(int _dims, const int* _sizes, int _type);
2669         void clear();
2670         int refcount;
2671         int dims;
2672         int valueOffset;
2673         size_t nodeSize;
2674         size_t nodeCount;
2675         size_t freeList;
2676         std::vector<uchar> pool;
2677         std::vector<size_t> hashtab;
2678         int size[MAX_DIM];
2679     };
2680
2681     //! sparse matrix node - element of a hash table
2682     struct CV_EXPORTS Node
2683     {
2684         //! hash value
2685         size_t hashval;
2686         //! index of the next node in the same hash table entry
2687         size_t next;
2688         //! index of the matrix element
2689         int idx[MAX_DIM];
2690     };
2691
2692     /** @brief Various SparseMat constructors.
2693      */
2694     SparseMat();
2695
2696     /** @overload
2697     @param dims Array dimensionality.
2698     @param _sizes Sparce matrix size on all dementions.
2699     @param _type Sparse matrix data type.
2700     */
2701     SparseMat(int dims, const int* _sizes, int _type);
2702
2703     /** @overload
2704     @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted
2705     to sparse representation.
2706     */
2707     SparseMat(const SparseMat& m);
2708
2709     /** @overload
2710     @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted
2711     to sparse representation.
2712     */
2713     explicit SparseMat(const Mat& m);
2714
2715     //! the destructor
2716     ~SparseMat();
2717
2718     //! assignment operator. This is O(1) operation, i.e. no data is copied
2719     SparseMat& operator = (const SparseMat& m);
2720     //! equivalent to the corresponding constructor
2721     SparseMat& operator = (const Mat& m);
2722
2723     //! creates full copy of the matrix
2724     SparseMat clone() const CV_NODISCARD;
2725
2726     //! copies all the data to the destination matrix. All the previous content of m is erased
2727     void copyTo( SparseMat& m ) const;
2728     //! converts sparse matrix to dense matrix.
2729     void copyTo( Mat& m ) const;
2730     //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type
2731     void convertTo( SparseMat& m, int rtype, double alpha=1 ) const;
2732     //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling.
2733     /*!
2734         @param [out] m - output matrix; if it does not have a proper size or type before the operation,
2735             it is reallocated
2736         @param [in] rtype - desired output matrix type or, rather, the depth since the number of channels
2737             are the same as the input has; if rtype is negative, the output matrix will have the
2738             same type as the input.
2739         @param [in] alpha - optional scale factor
2740         @param [in] beta - optional delta added to the scaled values
2741     */
2742     void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
2743
2744     // not used now
2745     void assignTo( SparseMat& m, int type=-1 ) const;
2746
2747     //! reallocates sparse matrix.
2748     /*!
2749         If the matrix already had the proper size and type,
2750         it is simply cleared with clear(), otherwise,
2751         the old matrix is released (using release()) and the new one is allocated.
2752     */
2753     void create(int dims, const int* _sizes, int _type);
2754     //! sets all the sparse matrix elements to 0, which means clearing the hash table.
2755     void clear();
2756     //! manually increments the reference counter to the header.
2757     void addref();
2758     // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated.
2759     void release();
2760
2761     //! converts sparse matrix to the old-style representation; all the elements are copied.
2762     //operator CvSparseMat*() const;
2763     //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements)
2764     size_t elemSize() const;
2765     //! returns elemSize()/channels()
2766     size_t elemSize1() const;
2767
2768     //! returns type of sparse matrix elements
2769     int type() const;
2770     //! returns the depth of sparse matrix elements
2771     int depth() const;
2772     //! returns the number of channels
2773     int channels() const;
2774
2775     //! returns the array of sizes, or NULL if the matrix is not allocated
2776     const int* size() const;
2777     //! returns the size of i-th matrix dimension (or 0)
2778     int size(int i) const;
2779     //! returns the matrix dimensionality
2780     int dims() const;
2781     //! returns the number of non-zero elements (=the number of hash table nodes)
2782     size_t nzcount() const;
2783
2784     //! computes the element hash value (1D case)
2785     size_t hash(int i0) const;
2786     //! computes the element hash value (2D case)
2787     size_t hash(int i0, int i1) const;
2788     //! computes the element hash value (3D case)
2789     size_t hash(int i0, int i1, int i2) const;
2790     //! computes the element hash value (nD case)
2791     size_t hash(const int* idx) const;
2792
2793     //!@{
2794     /*!
2795      specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case.
2796      return pointer to the matrix element.
2797       - if the element is there (it's non-zero), the pointer to it is returned
2798       - if it's not there and createMissing=false, NULL pointer is returned
2799       - if it's not there and createMissing=true, then the new element
2800         is created and initialized with 0. Pointer to it is returned
2801       - if the optional hashval pointer is not NULL, the element hash value is
2802         not computed, but *hashval is taken instead.
2803     */
2804     //! returns pointer to the specified element (1D case)
2805     uchar* ptr(int i0, bool createMissing, size_t* hashval=0);
2806     //! returns pointer to the specified element (2D case)
2807     uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0);
2808     //! returns pointer to the specified element (3D case)
2809     uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0);
2810     //! returns pointer to the specified element (nD case)
2811     uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0);
2812     //!@}
2813
2814     //!@{
2815     /*!
2816      return read-write reference to the specified sparse matrix element.
2817
2818      `ref<_Tp>(i0,...[,hashval])` is equivalent to `*(_Tp*)ptr(i0,...,true[,hashval])`.
2819      The methods always return a valid reference.
2820      If the element did not exist, it is created and initialized with 0.
2821     */
2822     //! returns reference to the specified element (1D case)
2823     template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0);
2824     //! returns reference to the specified element (2D case)
2825     template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0);
2826     //! returns reference to the specified element (3D case)
2827     template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
2828     //! returns reference to the specified element (nD case)
2829     template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0);
2830     //!@}
2831
2832     //!@{
2833     /*!
2834      return value of the specified sparse matrix element.
2835
2836      `value<_Tp>(i0,...[,hashval])` is equivalent to
2837      @code
2838      { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); }
2839      @endcode
2840
2841      That is, if the element did not exist, the methods return 0.
2842      */
2843     //! returns value of the specified element (1D case)
2844     template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const;
2845     //! returns value of the specified element (2D case)
2846     template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const;
2847     //! returns value of the specified element (3D case)
2848     template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0) const;
2849     //! returns value of the specified element (nD case)
2850     template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const;
2851     //!@}
2852
2853     //!@{
2854     /*!
2855      Return pointer to the specified sparse matrix element if it exists
2856
2857      `find<_Tp>(i0,...[,hashval])` is equivalent to `(_const Tp*)ptr(i0,...false[,hashval])`.
2858
2859      If the specified element does not exist, the methods return NULL.
2860     */
2861     //! returns pointer to the specified element (1D case)
2862     template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const;
2863     //! returns pointer to the specified element (2D case)
2864     template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0) const;
2865     //! returns pointer to the specified element (3D case)
2866     template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const;
2867     //! returns pointer to the specified element (nD case)
2868     template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0) const;
2869     //!@}
2870
2871     //! erases the specified element (2D case)
2872     void erase(int i0, int i1, size_t* hashval=0);
2873     //! erases the specified element (3D case)
2874     void erase(int i0, int i1, int i2, size_t* hashval=0);
2875     //! erases the specified element (nD case)
2876     void erase(const int* idx, size_t* hashval=0);
2877
2878     //!@{
2879     /*!
2880        return the sparse matrix iterator pointing to the first sparse matrix element
2881     */
2882     //! returns the sparse matrix iterator at the matrix beginning
2883     SparseMatIterator begin();
2884     //! returns the sparse matrix iterator at the matrix beginning
2885     template<typename _Tp> SparseMatIterator_<_Tp> begin();
2886     //! returns the read-only sparse matrix iterator at the matrix beginning
2887     SparseMatConstIterator begin() const;
2888     //! returns the read-only sparse matrix iterator at the matrix beginning
2889     template<typename _Tp> SparseMatConstIterator_<_Tp> begin() const;
2890     //!@}
2891     /*!
2892        return the sparse matrix iterator pointing to the element following the last sparse matrix element
2893     */
2894     //! returns the sparse matrix iterator at the matrix end
2895     SparseMatIterator end();
2896     //! returns the read-only sparse matrix iterator at the matrix end
2897     SparseMatConstIterator end() const;
2898     //! returns the typed sparse matrix iterator at the matrix end
2899     template<typename _Tp> SparseMatIterator_<_Tp> end();
2900     //! returns the typed read-only sparse matrix iterator at the matrix end
2901     template<typename _Tp> SparseMatConstIterator_<_Tp> end() const;
2902
2903     //! returns the value stored in the sparse martix node
2904     template<typename _Tp> _Tp& value(Node* n);
2905     //! returns the value stored in the sparse martix node
2906     template<typename _Tp> const _Tp& value(const Node* n) const;
2907
2908     ////////////// some internal-use methods ///////////////
2909     Node* node(size_t nidx);
2910     const Node* node(size_t nidx) const;
2911
2912     uchar* newNode(const int* idx, size_t hashval);
2913     void removeNode(size_t hidx, size_t nidx, size_t previdx);
2914     void resizeHashTab(size_t newsize);
2915
2916     int flags;
2917     Hdr* hdr;
2918 };
2919
2920
2921
2922 ///////////////////////////////// SparseMat_<_Tp> ////////////////////////////////////
2923
2924 /** @brief Template sparse n-dimensional array class derived from SparseMat
2925
2926 SparseMat_ is a thin wrapper on top of SparseMat created in the same way as Mat_ . It simplifies
2927 notation of some operations:
2928 @code
2929     int sz[] = {10, 20, 30};
2930     SparseMat_<double> M(3, sz);
2931     ...
2932     M.ref(1, 2, 3) = M(4, 5, 6) + M(7, 8, 9);
2933 @endcode
2934  */
2935 template<typename _Tp> class SparseMat_ : public SparseMat
2936 {
2937 public:
2938     typedef SparseMatIterator_<_Tp> iterator;
2939     typedef SparseMatConstIterator_<_Tp> const_iterator;
2940
2941     //! the default constructor
2942     SparseMat_();
2943     //! the full constructor equivalent to SparseMat(dims, _sizes, DataType<_Tp>::type)
2944     SparseMat_(int dims, const int* _sizes);
2945     //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted
2946     SparseMat_(const SparseMat& m);
2947     //! the copy constructor. This is O(1) operation - no data is copied
2948     SparseMat_(const SparseMat_& m);
2949     //! converts dense matrix to the sparse form
2950     SparseMat_(const Mat& m);
2951     //! converts the old-style sparse matrix to the C++ class. All the elements are copied
2952     //SparseMat_(const CvSparseMat* m);
2953     //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted
2954     SparseMat_& operator = (const SparseMat& m);
2955     //! the assignment operator. This is O(1) operation - no data is copied
2956     SparseMat_& operator = (const SparseMat_& m);
2957     //! converts dense matrix to the sparse form
2958     SparseMat_& operator = (const Mat& m);
2959
2960     //! makes full copy of the matrix. All the elements are duplicated
2961     SparseMat_ clone() const CV_NODISCARD;
2962     //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type)
2963     void create(int dims, const int* _sizes);
2964     //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied
2965     //operator CvSparseMat*() const;
2966
2967     //! returns type of the matrix elements
2968     int type() const;
2969     //! returns depth of the matrix elements
2970     int depth() const;
2971     //! returns the number of channels in each matrix element
2972     int channels() const;
2973
2974     //! equivalent to SparseMat::ref<_Tp>(i0, hashval)
2975     _Tp& ref(int i0, size_t* hashval=0);
2976     //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval)
2977     _Tp& ref(int i0, int i1, size_t* hashval=0);
2978     //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval)
2979     _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
2980     //! equivalent to SparseMat::ref<_Tp>(idx, hashval)
2981     _Tp& ref(const int* idx, size_t* hashval=0);
2982
2983     //! equivalent to SparseMat::value<_Tp>(i0, hashval)
2984     _Tp operator()(int i0, size_t* hashval=0) const;
2985     //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval)
2986     _Tp operator()(int i0, int i1, size_t* hashval=0) const;
2987     //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval)
2988     _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const;
2989     //! equivalent to SparseMat::value<_Tp>(idx, hashval)
2990     _Tp operator()(const int* idx, size_t* hashval=0) const;
2991
2992     //! returns sparse matrix iterator pointing to the first sparse matrix element
2993     SparseMatIterator_<_Tp> begin();
2994     //! returns read-only sparse matrix iterator pointing to the first sparse matrix element
2995     SparseMatConstIterator_<_Tp> begin() const;
2996     //! returns sparse matrix iterator pointing to the element following the last sparse matrix element
2997     SparseMatIterator_<_Tp> end();
2998     //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element
2999     SparseMatConstIterator_<_Tp> end() const;
3000 };
3001
3002
3003
3004 ////////////////////////////////// MatConstIterator //////////////////////////////////
3005
3006 class CV_EXPORTS MatConstIterator
3007 {
3008 public:
3009     typedef uchar* value_type;
3010     typedef ptrdiff_t difference_type;
3011     typedef const uchar** pointer;
3012     typedef uchar* reference;
3013
3014     typedef std::random_access_iterator_tag iterator_category;
3015
3016     //! default constructor
3017     MatConstIterator();
3018     //! constructor that sets the iterator to the beginning of the matrix
3019     MatConstIterator(const Mat* _m);
3020     //! constructor that sets the iterator to the specified element of the matrix
3021     MatConstIterator(const Mat* _m, int _row, int _col=0);
3022     //! constructor that sets the iterator to the specified element of the matrix
3023     MatConstIterator(const Mat* _m, Point _pt);
3024     //! constructor that sets the iterator to the specified element of the matrix
3025     MatConstIterator(const Mat* _m, const int* _idx);
3026     //! copy constructor
3027     MatConstIterator(const MatConstIterator& it);
3028
3029     //! copy operator
3030     MatConstIterator& operator = (const MatConstIterator& it);
3031     //! returns the current matrix element
3032     const uchar* operator *() const;
3033     //! returns the i-th matrix element, relative to the current
3034     const uchar* operator [](ptrdiff_t i) const;
3035
3036     //! shifts the iterator forward by the specified number of elements
3037     MatConstIterator& operator += (ptrdiff_t ofs);
3038     //! shifts the iterator backward by the specified number of elements
3039     MatConstIterator& operator -= (ptrdiff_t ofs);
3040     //! decrements the iterator
3041     MatConstIterator& operator --();
3042     //! decrements the iterator
3043     MatConstIterator operator --(int);
3044     //! increments the iterator
3045     MatConstIterator& operator ++();
3046     //! increments the iterator
3047     MatConstIterator operator ++(int);
3048     //! returns the current iterator position
3049     Point pos() const;
3050     //! returns the current iterator position
3051     void pos(int* _idx) const;
3052
3053     ptrdiff_t lpos() const;
3054     void seek(ptrdiff_t ofs, bool relative = false);
3055     void seek(const int* _idx, bool relative = false);
3056
3057     const Mat* m;
3058     size_t elemSize;
3059     const uchar* ptr;
3060     const uchar* sliceStart;
3061     const uchar* sliceEnd;
3062 };
3063
3064
3065
3066 ////////////////////////////////// MatConstIterator_ /////////////////////////////////
3067
3068 /** @brief Matrix read-only iterator
3069  */
3070 template<typename _Tp>
3071 class MatConstIterator_ : public MatConstIterator
3072 {
3073 public:
3074     typedef _Tp value_type;
3075     typedef ptrdiff_t difference_type;
3076     typedef const _Tp* pointer;
3077     typedef const _Tp& reference;
3078
3079     typedef std::random_access_iterator_tag iterator_category;
3080
3081     //! default constructor
3082     MatConstIterator_();
3083     //! constructor that sets the iterator to the beginning of the matrix
3084     MatConstIterator_(const Mat_<_Tp>* _m);
3085     //! constructor that sets the iterator to the specified element of the matrix
3086     MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0);
3087     //! constructor that sets the iterator to the specified element of the matrix
3088     MatConstIterator_(const Mat_<_Tp>* _m, Point _pt);
3089     //! constructor that sets the iterator to the specified element of the matrix
3090     MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx);
3091     //! copy constructor
3092     MatConstIterator_(const MatConstIterator_& it);
3093
3094     //! copy operator
3095     MatConstIterator_& operator = (const MatConstIterator_& it);
3096     //! returns the current matrix element
3097     const _Tp& operator *() const;
3098     //! returns the i-th matrix element, relative to the current
3099     const _Tp& operator [](ptrdiff_t i) const;
3100
3101     //! shifts the iterator forward by the specified number of elements
3102     MatConstIterator_& operator += (ptrdiff_t ofs);
3103     //! shifts the iterator backward by the specified number of elements
3104     MatConstIterator_& operator -= (ptrdiff_t ofs);
3105     //! decrements the iterator
3106     MatConstIterator_& operator --();
3107     //! decrements the iterator
3108     MatConstIterator_ operator --(int);
3109     //! increments the iterator
3110     MatConstIterator_& operator ++();
3111     //! increments the iterator
3112     MatConstIterator_ operator ++(int);
3113     //! returns the current iterator position
3114     Point pos() const;
3115 };
3116
3117
3118
3119 //////////////////////////////////// MatIterator_ ////////////////////////////////////
3120
3121 /** @brief Matrix read-write iterator
3122 */
3123 template<typename _Tp>
3124 class MatIterator_ : public MatConstIterator_<_Tp>
3125 {
3126 public:
3127     typedef _Tp* pointer;
3128     typedef _Tp& reference;
3129
3130     typedef std::random_access_iterator_tag iterator_category;
3131
3132     //! the default constructor
3133     MatIterator_();
3134     //! constructor that sets the iterator to the beginning of the matrix
3135     MatIterator_(Mat_<_Tp>* _m);
3136     //! constructor that sets the iterator to the specified element of the matrix
3137     MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0);
3138     //! constructor that sets the iterator to the specified element of the matrix
3139     MatIterator_(Mat_<_Tp>* _m, Point _pt);
3140     //! constructor that sets the iterator to the specified element of the matrix
3141     MatIterator_(Mat_<_Tp>* _m, const int* _idx);
3142     //! copy constructor
3143     MatIterator_(const MatIterator_& it);
3144     //! copy operator
3145     MatIterator_& operator = (const MatIterator_<_Tp>& it );
3146
3147     //! returns the current matrix element
3148     _Tp& operator *() const;
3149     //! returns the i-th matrix element, relative to the current
3150     _Tp& operator [](ptrdiff_t i) const;
3151
3152     //! shifts the iterator forward by the specified number of elements
3153     MatIterator_& operator += (ptrdiff_t ofs);
3154     //! shifts the iterator backward by the specified number of elements
3155     MatIterator_& operator -= (ptrdiff_t ofs);
3156     //! decrements the iterator
3157     MatIterator_& operator --();
3158     //! decrements the iterator
3159     MatIterator_ operator --(int);
3160     //! increments the iterator
3161     MatIterator_& operator ++();
3162     //! increments the iterator
3163     MatIterator_ operator ++(int);
3164 };
3165
3166
3167
3168 /////////////////////////////// SparseMatConstIterator ///////////////////////////////
3169
3170 /**  @brief Read-Only Sparse Matrix Iterator.
3171
3172  Here is how to use the iterator to compute the sum of floating-point sparse matrix elements:
3173
3174  \code
3175  SparseMatConstIterator it = m.begin(), it_end = m.end();
3176  double s = 0;
3177  CV_Assert( m.type() == CV_32F );
3178  for( ; it != it_end; ++it )
3179     s += it.value<float>();
3180  \endcode
3181 */
3182 class CV_EXPORTS SparseMatConstIterator
3183 {
3184 public:
3185     //! the default constructor
3186     SparseMatConstIterator();
3187     //! the full constructor setting the iterator to the first sparse matrix element
3188     SparseMatConstIterator(const SparseMat* _m);
3189     //! the copy constructor
3190     SparseMatConstIterator(const SparseMatConstIterator& it);
3191
3192     //! the assignment operator
3193     SparseMatConstIterator& operator = (const SparseMatConstIterator& it);
3194
3195     //! template method returning the current matrix element
3196     template<typename _Tp> const _Tp& value() const;
3197     //! returns the current node of the sparse matrix. it.node->idx is the current element index
3198     const SparseMat::Node* node() const;
3199
3200     //! moves iterator to the previous element
3201     SparseMatConstIterator& operator --();
3202     //! moves iterator to the previous element
3203     SparseMatConstIterator operator --(int);
3204     //! moves iterator to the next element
3205     SparseMatConstIterator& operator ++();
3206     //! moves iterator to the next element
3207     SparseMatConstIterator operator ++(int);
3208
3209     //! moves iterator to the element after the last element
3210     void seekEnd();
3211
3212     const SparseMat* m;
3213     size_t hashidx;
3214     uchar* ptr;
3215 };
3216
3217
3218
3219 ////////////////////////////////// SparseMatIterator /////////////////////////////////
3220
3221 /** @brief  Read-write Sparse Matrix Iterator
3222
3223  The class is similar to cv::SparseMatConstIterator,
3224  but can be used for in-place modification of the matrix elements.
3225 */
3226 class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator
3227 {
3228 public:
3229     //! the default constructor
3230     SparseMatIterator();
3231     //! the full constructor setting the iterator to the first sparse matrix element
3232     SparseMatIterator(SparseMat* _m);
3233     //! the full constructor setting the iterator to the specified sparse matrix element
3234     SparseMatIterator(SparseMat* _m, const int* idx);
3235     //! the copy constructor
3236     SparseMatIterator(const SparseMatIterator& it);
3237
3238     //! the assignment operator
3239     SparseMatIterator& operator = (const SparseMatIterator& it);
3240     //! returns read-write reference to the current sparse matrix element
3241     template<typename _Tp> _Tp& value() const;
3242     //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!)
3243     SparseMat::Node* node() const;
3244
3245     //! moves iterator to the next element
3246     SparseMatIterator& operator ++();
3247     //! moves iterator to the next element
3248     SparseMatIterator operator ++(int);
3249 };
3250
3251
3252
3253 /////////////////////////////// SparseMatConstIterator_ //////////////////////////////
3254
3255 /** @brief  Template Read-Only Sparse Matrix Iterator Class.
3256
3257  This is the derived from SparseMatConstIterator class that
3258  introduces more convenient operator *() for accessing the current element.
3259 */
3260 template<typename _Tp> class SparseMatConstIterator_ : public SparseMatConstIterator
3261 {
3262 public:
3263
3264     typedef std::forward_iterator_tag iterator_category;
3265
3266     //! the default constructor
3267     SparseMatConstIterator_();
3268     //! the full constructor setting the iterator to the first sparse matrix element
3269     SparseMatConstIterator_(const SparseMat_<_Tp>* _m);
3270     SparseMatConstIterator_(const SparseMat* _m);
3271     //! the copy constructor
3272     SparseMatConstIterator_(const SparseMatConstIterator_& it);
3273
3274     //! the assignment operator
3275     SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it);
3276     //! the element access operator
3277     const _Tp& operator *() const;
3278
3279     //! moves iterator to the next element
3280     SparseMatConstIterator_& operator ++();
3281     //! moves iterator to the next element
3282     SparseMatConstIterator_ operator ++(int);
3283 };
3284
3285
3286
3287 ///////////////////////////////// SparseMatIterator_ /////////////////////////////////
3288
3289 /** @brief  Template Read-Write Sparse Matrix Iterator Class.
3290
3291  This is the derived from cv::SparseMatConstIterator_ class that
3292  introduces more convenient operator *() for accessing the current element.
3293 */
3294 template<typename _Tp> class SparseMatIterator_ : public SparseMatConstIterator_<_Tp>
3295 {
3296 public:
3297
3298     typedef std::forward_iterator_tag iterator_category;
3299
3300     //! the default constructor
3301     SparseMatIterator_();
3302     //! the full constructor setting the iterator to the first sparse matrix element
3303     SparseMatIterator_(SparseMat_<_Tp>* _m);
3304     SparseMatIterator_(SparseMat* _m);
3305     //! the copy constructor
3306     SparseMatIterator_(const SparseMatIterator_& it);
3307
3308     //! the assignment operator
3309     SparseMatIterator_& operator = (const SparseMatIterator_& it);
3310     //! returns the reference to the current element
3311     _Tp& operator *() const;
3312
3313     //! moves the iterator to the next element
3314     SparseMatIterator_& operator ++();
3315     //! moves the iterator to the next element
3316     SparseMatIterator_ operator ++(int);
3317 };
3318
3319
3320
3321 /////////////////////////////////// NAryMatIterator //////////////////////////////////
3322
3323 /** @brief n-ary multi-dimensional array iterator.
3324
3325 Use the class to implement unary, binary, and, generally, n-ary element-wise operations on
3326 multi-dimensional arrays. Some of the arguments of an n-ary function may be continuous arrays, some
3327 may be not. It is possible to use conventional MatIterator 's for each array but incrementing all of
3328 the iterators after each small operations may be a big overhead. In this case consider using
3329 NAryMatIterator to iterate through several matrices simultaneously as long as they have the same
3330 geometry (dimensionality and all the dimension sizes are the same). On each iteration `it.planes[0]`,
3331 `it.planes[1]`,... will be the slices of the corresponding matrices.
3332
3333 The example below illustrates how you can compute a normalized and threshold 3D color histogram:
3334 @code
3335     void computeNormalizedColorHist(const Mat& image, Mat& hist, int N, double minProb)
3336     {
3337         const int histSize[] = {N, N, N};
3338
3339         // make sure that the histogram has a proper size and type
3340         hist.create(3, histSize, CV_32F);
3341
3342         // and clear it
3343         hist = Scalar(0);
3344
3345         // the loop below assumes that the image
3346         // is a 8-bit 3-channel. check it.
3347         CV_Assert(image.type() == CV_8UC3);
3348         MatConstIterator_<Vec3b> it = image.begin<Vec3b>(),
3349                                  it_end = image.end<Vec3b>();
3350         for( ; it != it_end; ++it )
3351         {
3352             const Vec3b& pix = *it;
3353             hist.at<float>(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f;
3354         }
3355
3356         minProb *= image.rows*image.cols;
3357
3358         // initialize iterator (the style is different from STL).
3359         // after initialization the iterator will contain
3360         // the number of slices or planes the iterator will go through.
3361         // it simultaneously increments iterators for several matrices
3362         // supplied as a null terminated list of pointers
3363         const Mat* arrays[] = {&hist, 0};
3364         Mat planes[1];
3365         NAryMatIterator itNAry(arrays, planes, 1);
3366         double s = 0;
3367         // iterate through the matrix. on each iteration
3368         // itNAry.planes[i] (of type Mat) will be set to the current plane
3369         // of the i-th n-dim matrix passed to the iterator constructor.
3370         for(int p = 0; p < itNAry.nplanes; p++, ++itNAry)
3371         {
3372             threshold(itNAry.planes[0], itNAry.planes[0], minProb, 0, THRESH_TOZERO);
3373             s += sum(itNAry.planes[0])[0];
3374         }
3375
3376         s = 1./s;
3377         itNAry = NAryMatIterator(arrays, planes, 1);
3378         for(int p = 0; p < itNAry.nplanes; p++, ++itNAry)
3379             itNAry.planes[0] *= s;
3380     }
3381 @endcode
3382  */
3383 class CV_EXPORTS NAryMatIterator
3384 {
3385 public:
3386     //! the default constructor
3387     NAryMatIterator();
3388     //! the full constructor taking arbitrary number of n-dim matrices
3389     NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1);
3390     //! the full constructor taking arbitrary number of n-dim matrices
3391     NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1);
3392     //! the separate iterator initialization method
3393     void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1);
3394
3395     //! proceeds to the next plane of every iterated matrix
3396     NAryMatIterator& operator ++();
3397     //! proceeds to the next plane of every iterated matrix (postfix increment operator)
3398     NAryMatIterator operator ++(int);
3399
3400     //! the iterated arrays
3401     const Mat** arrays;
3402     //! the current planes
3403     Mat* planes;
3404     //! data pointers
3405     uchar** ptrs;
3406     //! the number of arrays
3407     int narrays;
3408     //! the number of hyper-planes that the iterator steps through
3409     size_t nplanes;
3410     //! the size of each segment (in elements)
3411     size_t size;
3412 protected:
3413     int iterdepth;
3414     size_t idx;
3415 };
3416
3417
3418
3419 ///////////////////////////////// Matrix Expressions /////////////////////////////////
3420
3421 class CV_EXPORTS MatOp
3422 {
3423 public:
3424     MatOp();
3425     virtual ~MatOp();
3426
3427     virtual bool elementWise(const MatExpr& expr) const;
3428     virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0;
3429     virtual void roi(const MatExpr& expr, const Range& rowRange,
3430                      const Range& colRange, MatExpr& res) const;
3431     virtual void diag(const MatExpr& expr, int d, MatExpr& res) const;
3432     virtual void augAssignAdd(const MatExpr& expr, Mat& m) const;
3433     virtual void augAssignSubtract(const MatExpr& expr, Mat& m) const;
3434     virtual void augAssignMultiply(const MatExpr& expr, Mat& m) const;
3435     virtual void augAssignDivide(const MatExpr& expr, Mat& m) const;
3436     virtual void augAssignAnd(const MatExpr& expr, Mat& m) const;
3437     virtual void augAssignOr(const MatExpr& expr, Mat& m) const;
3438     virtual void augAssignXor(const MatExpr& expr, Mat& m) const;
3439
3440     virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
3441     virtual void add(const MatExpr& expr1, const Scalar& s, MatExpr& res) const;
3442
3443     virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
3444     virtual void subtract(const Scalar& s, const MatExpr& expr, MatExpr& res) const;
3445
3446     virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
3447     virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const;
3448
3449     virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
3450     virtual void divide(double s, const MatExpr& expr, MatExpr& res) const;
3451
3452     virtual void abs(const MatExpr& expr, MatExpr& res) const;
3453
3454     virtual void transpose(const MatExpr& expr, MatExpr& res) const;
3455     virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
3456     virtual void invert(const MatExpr& expr, int method, MatExpr& res) const;
3457
3458     virtual Size size(const MatExpr& expr) const;
3459     virtual int type(const MatExpr& expr) const;
3460 };
3461
3462 /** @brief Matrix expression representation
3463 @anchor MatrixExpressions
3464 This is a list of implemented matrix operations that can be combined in arbitrary complex
3465 expressions (here A, B stand for matrices ( Mat ), s for a scalar ( Scalar ), alpha for a
3466 real-valued scalar ( double )):
3467 -   Addition, subtraction, negation: `A+B`, `A-B`, `A+s`, `A-s`, `s+A`, `s-A`, `-A`
3468 -   Scaling: `A*alpha`
3469 -   Per-element multiplication and division: `A.mul(B)`, `A/B`, `alpha/A`
3470 -   Matrix multiplication: `A*B`
3471 -   Transposition: `A.t()` (means A<sup>T</sup>)
3472 -   Matrix inversion and pseudo-inversion, solving linear systems and least-squares problems:
3473     `A.inv([method]) (~ A<sup>-1</sup>)`,   `A.inv([method])*B (~ X: AX=B)`
3474 -   Comparison: `A cmpop B`, `A cmpop alpha`, `alpha cmpop A`, where *cmpop* is one of
3475   `>`, `>=`, `==`, `!=`, `<=`, `<`. The result of comparison is an 8-bit single channel mask whose
3476     elements are set to 255 (if the particular element or pair of elements satisfy the condition) or
3477     0.
3478 -   Bitwise logical operations: `A logicop B`, `A logicop s`, `s logicop A`, `~A`, where *logicop* is one of
3479   `&`, `|`, `^`.
3480 -   Element-wise minimum and maximum: `min(A, B)`, `min(A, alpha)`, `max(A, B)`, `max(A, alpha)`
3481 -   Element-wise absolute value: `abs(A)`
3482 -   Cross-product, dot-product: `A.cross(B)`, `A.dot(B)`
3483 -   Any function of matrix or matrices and scalars that returns a matrix or a scalar, such as norm,
3484     mean, sum, countNonZero, trace, determinant, repeat, and others.
3485 -   Matrix initializers ( Mat::eye(), Mat::zeros(), Mat::ones() ), matrix comma-separated
3486     initializers, matrix constructors and operators that extract sub-matrices (see Mat description).
3487 -   Mat_<destination_type>() constructors to cast the result to the proper type.
3488 @note Comma-separated initializers and probably some other operations may require additional
3489 explicit Mat() or Mat_<T>() constructor calls to resolve a possible ambiguity.
3490
3491 Here are examples of matrix expressions:
3492 @code
3493     // compute pseudo-inverse of A, equivalent to A.inv(DECOMP_SVD)
3494     SVD svd(A);
3495     Mat pinvA = svd.vt.t()*Mat::diag(1./svd.w)*svd.u.t();
3496
3497     // compute the new vector of parameters in the Levenberg-Marquardt algorithm
3498     x -= (A.t()*A + lambda*Mat::eye(A.cols,A.cols,A.type())).inv(DECOMP_CHOLESKY)*(A.t()*err);
3499
3500     // sharpen image using "unsharp mask" algorithm
3501     Mat blurred; double sigma = 1, threshold = 5, amount = 1;
3502     GaussianBlur(img, blurred, Size(), sigma, sigma);
3503     Mat lowContrastMask = abs(img - blurred) < threshold;
3504     Mat sharpened = img*(1+amount) + blurred*(-amount);
3505     img.copyTo(sharpened, lowContrastMask);
3506 @endcode
3507 */
3508 class CV_EXPORTS MatExpr
3509 {
3510 public:
3511     MatExpr();
3512     explicit MatExpr(const Mat& m);
3513
3514     MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(),
3515             const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar& _s = Scalar());
3516
3517     operator Mat() const;
3518     template<typename _Tp> operator Mat_<_Tp>() const;
3519
3520     Size size() const;
3521     int type() const;
3522
3523     MatExpr row(int y) const;
3524     MatExpr col(int x) const;
3525     MatExpr diag(int d = 0) const;
3526     MatExpr operator()( const Range& rowRange, const Range& colRange ) const;
3527     MatExpr operator()( const Rect& roi ) const;
3528
3529     MatExpr t() const;
3530     MatExpr inv(int method = DECOMP_LU) const;
3531     MatExpr mul(const MatExpr& e, double scale=1) const;
3532     MatExpr mul(const Mat& m, double scale=1) const;
3533
3534     Mat cross(const Mat& m) const;
3535     double dot(const Mat& m) const;
3536
3537     void swap(MatExpr& b);
3538
3539     const MatOp* op;
3540     int flags;
3541
3542     Mat a, b, c;
3543     double alpha, beta;
3544     Scalar s;
3545 };
3546
3547 //! @} core_basic
3548
3549 //! @relates cv::MatExpr
3550 //! @{
3551 CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b);
3552 CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s);
3553 CV_EXPORTS MatExpr operator + (const Scalar& s, const Mat& a);
3554 CV_EXPORTS MatExpr operator + (const MatExpr& e, const Mat& m);
3555 CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e);
3556 CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar& s);
3557 CV_EXPORTS MatExpr operator + (const Scalar& s, const MatExpr& e);
3558 CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2);
3559 template<typename _Tp, int m, int n> static inline
3560 MatExpr operator + (const Mat& a, const Matx<_Tp, m, n>& b) { return a + Mat(b); }
3561 template<typename _Tp, int m, int n> static inline
3562 MatExpr operator + (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) + b; }
3563
3564 CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b);
3565 CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar& s);
3566 CV_EXPORTS MatExpr operator - (const Scalar& s, const Mat& a);
3567 CV_EXPORTS MatExpr operator - (const MatExpr& e, const Mat& m);
3568 CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e);
3569 CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar& s);
3570 CV_EXPORTS MatExpr operator - (const Scalar& s, const MatExpr& e);
3571 CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2);
3572 template<typename _Tp, int m, int n> static inline
3573 MatExpr operator - (const Mat& a, const Matx<_Tp, m, n>& b) { return a - Mat(b); }
3574 template<typename _Tp, int m, int n> static inline
3575 MatExpr operator - (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) - b; }
3576
3577 CV_EXPORTS MatExpr operator - (const Mat& m);
3578 CV_EXPORTS MatExpr operator - (const MatExpr& e);
3579
3580 CV_EXPORTS MatExpr operator * (const Mat& a, const Mat& b);
3581 CV_EXPORTS MatExpr operator * (const Mat& a, double s);
3582 CV_EXPORTS MatExpr operator * (double s, const Mat& a);
3583 CV_EXPORTS MatExpr operator * (const MatExpr& e, const Mat& m);
3584 CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e);
3585 CV_EXPORTS MatExpr operator * (const MatExpr& e, double s);
3586 CV_EXPORTS MatExpr operator * (double s, const MatExpr& e);
3587 CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2);
3588 template<typename _Tp, int m, int n> static inline
3589 MatExpr operator * (const Mat& a, const Matx<_Tp, m, n>& b) { return a * Mat(b); }
3590 template<typename _Tp, int m, int n> static inline
3591 MatExpr operator * (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) * b; }
3592
3593 CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b);
3594 CV_EXPORTS MatExpr operator / (const Mat& a, double s);
3595 CV_EXPORTS MatExpr operator / (double s, const Mat& a);
3596 CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m);
3597 CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e);
3598 CV_EXPORTS MatExpr operator / (const MatExpr& e, double s);
3599 CV_EXPORTS MatExpr operator / (double s, const MatExpr& e);
3600 CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2);
3601 template<typename _Tp, int m, int n> static inline
3602 MatExpr operator / (const Mat& a, const Matx<_Tp, m, n>& b) { return a / Mat(b); }
3603 template<typename _Tp, int m, int n> static inline
3604 MatExpr operator / (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) / b; }
3605
3606 CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b);
3607 CV_EXPORTS MatExpr operator < (const Mat& a, double s);
3608 CV_EXPORTS MatExpr operator < (double s, const Mat& a);
3609 template<typename _Tp, int m, int n> static inline
3610 MatExpr operator < (const Mat& a, const Matx<_Tp, m, n>& b) { return a < Mat(b); }
3611 template<typename _Tp, int m, int n> static inline
3612 MatExpr operator < (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) < b; }
3613
3614 CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b);
3615 CV_EXPORTS MatExpr operator <= (const Mat& a, double s);
3616 CV_EXPORTS MatExpr operator <= (double s, const Mat& a);
3617 template<typename _Tp, int m, int n> static inline
3618 MatExpr operator <= (const Mat& a, const Matx<_Tp, m, n>& b) { return a <= Mat(b); }
3619 template<typename _Tp, int m, int n> static inline
3620 MatExpr operator <= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) <= b; }
3621
3622 CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b);
3623 CV_EXPORTS MatExpr operator == (const Mat& a, double s);
3624 CV_EXPORTS MatExpr operator == (double s, const Mat& a);
3625 template<typename _Tp, int m, int n> static inline
3626 MatExpr operator == (const Mat& a, const Matx<_Tp, m, n>& b) { return a == Mat(b); }
3627 template<typename _Tp, int m, int n> static inline
3628 MatExpr operator == (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) == b; }
3629
3630 CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b);
3631 CV_EXPORTS MatExpr operator != (const Mat& a, double s);
3632 CV_EXPORTS MatExpr operator != (double s, const Mat& a);
3633 template<typename _Tp, int m, int n> static inline
3634 MatExpr operator != (const Mat& a, const Matx<_Tp, m, n>& b) { return a != Mat(b); }
3635 template<typename _Tp, int m, int n> static inline
3636 MatExpr operator != (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) != b; }
3637
3638 CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b);
3639 CV_EXPORTS MatExpr operator >= (const Mat& a, double s);
3640 CV_EXPORTS MatExpr operator >= (double s, const Mat& a);
3641 template<typename _Tp, int m, int n> static inline
3642 MatExpr operator >= (const Mat& a, const Matx<_Tp, m, n>& b) { return a >= Mat(b); }
3643 template<typename _Tp, int m, int n> static inline
3644 MatExpr operator >= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) >= b; }
3645
3646 CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b);
3647 CV_EXPORTS MatExpr operator > (const Mat& a, double s);
3648 CV_EXPORTS MatExpr operator > (double s, const Mat& a);
3649 template<typename _Tp, int m, int n> static inline
3650 MatExpr operator > (const Mat& a, const Matx<_Tp, m, n>& b) { return a > Mat(b); }
3651 template<typename _Tp, int m, int n> static inline
3652 MatExpr operator > (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) > b; }
3653
3654 CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b);
3655 CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s);
3656 CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a);
3657 template<typename _Tp, int m, int n> static inline
3658 MatExpr operator & (const Mat& a, const Matx<_Tp, m, n>& b) { return a & Mat(b); }
3659 template<typename _Tp, int m, int n> static inline
3660 MatExpr operator & (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) & b; }
3661
3662 CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b);
3663 CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar& s);
3664 CV_EXPORTS MatExpr operator | (const Scalar& s, const Mat& a);
3665 template<typename _Tp, int m, int n> static inline
3666 MatExpr operator | (const Mat& a, const Matx<_Tp, m, n>& b) { return a | Mat(b); }
3667 template<typename _Tp, int m, int n> static inline
3668 MatExpr operator | (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) | b; }
3669
3670 CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b);
3671 CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s);
3672 CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a);
3673 template<typename _Tp, int m, int n> static inline
3674 MatExpr operator ^ (const Mat& a, const Matx<_Tp, m, n>& b) { return a ^ Mat(b); }
3675 template<typename _Tp, int m, int n> static inline
3676 MatExpr operator ^ (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) ^ b; }
3677
3678 CV_EXPORTS MatExpr operator ~(const Mat& m);
3679
3680 CV_EXPORTS MatExpr min(const Mat& a, const Mat& b);
3681 CV_EXPORTS MatExpr min(const Mat& a, double s);
3682 CV_EXPORTS MatExpr min(double s, const Mat& a);
3683 template<typename _Tp, int m, int n> static inline
3684 MatExpr min (const Mat& a, const Matx<_Tp, m, n>& b) { return min(a, Mat(b)); }
3685 template<typename _Tp, int m, int n> static inline
3686 MatExpr min (const Matx<_Tp, m, n>& a, const Mat& b) { return min(Mat(a), b); }
3687
3688 CV_EXPORTS MatExpr max(const Mat& a, const Mat& b);
3689 CV_EXPORTS MatExpr max(const Mat& a, double s);
3690 CV_EXPORTS MatExpr max(double s, const Mat& a);
3691 template<typename _Tp, int m, int n> static inline
3692 MatExpr max (const Mat& a, const Matx<_Tp, m, n>& b) { return max(a, Mat(b)); }
3693 template<typename _Tp, int m, int n> static inline
3694 MatExpr max (const Matx<_Tp, m, n>& a, const Mat& b) { return max(Mat(a), b); }
3695
3696 /** @brief Calculates an absolute value of each matrix element.
3697
3698 abs is a meta-function that is expanded to one of absdiff or convertScaleAbs forms:
3699 - C = abs(A-B) is equivalent to `absdiff(A, B, C)`
3700 - C = abs(A) is equivalent to `absdiff(A, Scalar::all(0), C)`
3701 - C = `Mat_<Vec<uchar,n> >(abs(A*alpha + beta))` is equivalent to `convertScaleAbs(A, C, alpha,
3702 beta)`
3703
3704 The output matrix has the same size and the same type as the input one except for the last case,
3705 where C is depth=CV_8U .
3706 @param m matrix.
3707 @sa @ref MatrixExpressions, absdiff, convertScaleAbs
3708  */
3709 CV_EXPORTS MatExpr abs(const Mat& m);
3710 /** @overload
3711 @param e matrix expression.
3712 */
3713 CV_EXPORTS MatExpr abs(const MatExpr& e);
3714 //! @} relates cv::MatExpr
3715
3716 } // cv
3717
3718 #include "opencv2/core/mat.inl.hpp"
3719
3720 #endif // OPENCV_CORE_MAT_HPP