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