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