1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
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.
11 // For Open Source Computer Vision Library
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.
18 // Redistribution and use in source and binary forms, with or without modification,
19 // are permitted provided that the following conditions are met:
21 // * Redistribution's of source code must retain the above copyright notice,
22 // this list of conditions and the following disclaimer.
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.
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.
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.
44 #ifndef __OPENCV_CORE_MAT_HPP__
45 #define __OPENCV_CORE_MAT_HPP__
48 # error mat.hpp header must be compiled as C++
51 #include "opencv2/core/matx.hpp"
52 #include "opencv2/core/types.hpp"
54 #include "opencv2/core/bufferpool.hpp"
59 enum { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25,
60 ACCESS_RW=3<<24, ACCESS_MASK=ACCESS_RW, ACCESS_FAST=1<<26 };
62 class CV_EXPORTS _OutputArray;
64 //////////////////////// Input/Output Array Arguments /////////////////////////////////
67 Proxy datatype for passing Mat's and vector<>'s as input parameters
69 class CV_EXPORTS _InputArray
74 FIXED_TYPE = 0x8000 << KIND_SHIFT,
75 FIXED_SIZE = 0x4000 << KIND_SHIFT,
76 KIND_MASK = 31 << KIND_SHIFT,
78 NONE = 0 << KIND_SHIFT,
79 MAT = 1 << KIND_SHIFT,
80 MATX = 2 << KIND_SHIFT,
81 STD_VECTOR = 3 << KIND_SHIFT,
82 STD_VECTOR_VECTOR = 4 << KIND_SHIFT,
83 STD_VECTOR_MAT = 5 << KIND_SHIFT,
84 EXPR = 6 << KIND_SHIFT,
85 OPENGL_BUFFER = 7 << KIND_SHIFT,
86 CUDA_MEM = 8 << KIND_SHIFT,
87 GPU_MAT = 9 << KIND_SHIFT,
88 OCL_MAT =10 << KIND_SHIFT,
89 UMAT =11 << KIND_SHIFT,
90 STD_VECTOR_UMAT =12 << KIND_SHIFT,
91 UEXPR =13 << KIND_SHIFT
95 _InputArray(int _flags, void* _obj);
96 _InputArray(const Mat& m);
97 _InputArray(const MatExpr& expr);
98 _InputArray(const std::vector<Mat>& vec);
99 template<typename _Tp> _InputArray(const Mat_<_Tp>& m);
100 template<typename _Tp> _InputArray(const std::vector<_Tp>& vec);
101 template<typename _Tp> _InputArray(const std::vector<std::vector<_Tp> >& vec);
102 template<typename _Tp> _InputArray(const std::vector<Mat_<_Tp> >& vec);
103 template<typename _Tp> _InputArray(const _Tp* vec, int n);
104 template<typename _Tp, int m, int n> _InputArray(const Matx<_Tp, m, n>& matx);
105 _InputArray(const double& val);
106 _InputArray(const cuda::GpuMat& d_mat);
107 _InputArray(const ogl::Buffer& buf);
108 _InputArray(const cuda::CudaMem& cuda_mem);
109 template<typename _Tp> _InputArray(const cudev::GpuMat_<_Tp>& m);
110 _InputArray(const UMat& um);
111 _InputArray(const std::vector<UMat>& umv);
112 _InputArray(const UMatExpr& uexpr);
114 virtual Mat getMat(int idx=-1) const;
115 virtual UMat getUMat(int idx=-1) const;
116 virtual void getMatVector(std::vector<Mat>& mv) const;
117 virtual void getUMatVector(std::vector<UMat>& umv) const;
118 virtual cuda::GpuMat getGpuMat() const;
119 virtual ogl::Buffer getOGlBuffer() const;
120 void* getObj() const;
122 virtual int kind() const;
123 virtual int dims(int i=-1) const;
124 virtual Size size(int i=-1) const;
125 virtual int sizend(int* sz, int i=-1) const;
126 virtual bool sameSize(const _InputArray& arr) const;
127 virtual size_t total(int i=-1) const;
128 virtual int type(int i=-1) const;
129 virtual int depth(int i=-1) const;
130 virtual int channels(int i=-1) const;
131 virtual bool isContinuous(int i=-1) const;
132 virtual bool isSubmatrix(int i=-1) const;
133 virtual bool empty() const;
134 virtual void copyTo(const _OutputArray& arr) const;
135 virtual size_t offset(int i=-1) const;
136 virtual size_t step(int i=-1) const;
139 bool isMatVector() const;
140 bool isUMatVector() const;
143 virtual ~_InputArray();
150 void init(int _flags, const void* _obj);
151 void init(int _flags, const void* _obj, Size _sz);
156 Proxy datatype for passing Mat's and vector<>'s as input parameters
158 class CV_EXPORTS _OutputArray : public _InputArray
163 DEPTH_MASK_8U = 1 << CV_8U,
164 DEPTH_MASK_8S = 1 << CV_8S,
165 DEPTH_MASK_16U = 1 << CV_16U,
166 DEPTH_MASK_16S = 1 << CV_16S,
167 DEPTH_MASK_32S = 1 << CV_32S,
168 DEPTH_MASK_32F = 1 << CV_32F,
169 DEPTH_MASK_64F = 1 << CV_64F,
170 DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1,
171 DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S,
172 DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F
176 _OutputArray(int _flags, void* _obj);
177 _OutputArray(Mat& m);
178 _OutputArray(std::vector<Mat>& vec);
179 _OutputArray(cuda::GpuMat& d_mat);
180 _OutputArray(ogl::Buffer& buf);
181 _OutputArray(cuda::CudaMem& cuda_mem);
182 template<typename _Tp> _OutputArray(cudev::GpuMat_<_Tp>& m);
183 template<typename _Tp> _OutputArray(std::vector<_Tp>& vec);
184 template<typename _Tp> _OutputArray(std::vector<std::vector<_Tp> >& vec);
185 template<typename _Tp> _OutputArray(std::vector<Mat_<_Tp> >& vec);
186 template<typename _Tp> _OutputArray(Mat_<_Tp>& m);
187 template<typename _Tp> _OutputArray(_Tp* vec, int n);
188 template<typename _Tp, int m, int n> _OutputArray(Matx<_Tp, m, n>& matx);
189 _OutputArray(UMat& m);
190 _OutputArray(std::vector<UMat>& vec);
192 _OutputArray(const Mat& m);
193 _OutputArray(const std::vector<Mat>& vec);
194 _OutputArray(const cuda::GpuMat& d_mat);
195 _OutputArray(const ogl::Buffer& buf);
196 _OutputArray(const cuda::CudaMem& cuda_mem);
197 template<typename _Tp> _OutputArray(const cudev::GpuMat_<_Tp>& m);
198 template<typename _Tp> _OutputArray(const std::vector<_Tp>& vec);
199 template<typename _Tp> _OutputArray(const std::vector<std::vector<_Tp> >& vec);
200 template<typename _Tp> _OutputArray(const std::vector<Mat_<_Tp> >& vec);
201 template<typename _Tp> _OutputArray(const Mat_<_Tp>& m);
202 template<typename _Tp> _OutputArray(const _Tp* vec, int n);
203 template<typename _Tp, int m, int n> _OutputArray(const Matx<_Tp, m, n>& matx);
204 _OutputArray(const UMat& m);
205 _OutputArray(const std::vector<UMat>& vec);
207 virtual bool fixedSize() const;
208 virtual bool fixedType() const;
209 virtual bool needed() const;
210 virtual Mat& getMatRef(int i=-1) const;
211 virtual UMat& getUMatRef(int i=-1) const;
212 virtual cuda::GpuMat& getGpuMatRef() const;
213 virtual ogl::Buffer& getOGlBufferRef() const;
214 virtual cuda::CudaMem& getCudaMemRef() const;
215 virtual void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
216 virtual void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
217 virtual void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
218 virtual void createSameSize(const _InputArray& arr, int mtype) const;
219 virtual void release() const;
220 virtual void clear() const;
221 virtual void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const;
225 class CV_EXPORTS _InputOutputArray : public _OutputArray
229 _InputOutputArray(int _flags, void* _obj);
230 _InputOutputArray(Mat& m);
231 _InputOutputArray(std::vector<Mat>& vec);
232 _InputOutputArray(cuda::GpuMat& d_mat);
233 _InputOutputArray(ogl::Buffer& buf);
234 _InputOutputArray(cuda::CudaMem& cuda_mem);
235 template<typename _Tp> _InputOutputArray(cudev::GpuMat_<_Tp>& m);
236 template<typename _Tp> _InputOutputArray(std::vector<_Tp>& vec);
237 template<typename _Tp> _InputOutputArray(std::vector<std::vector<_Tp> >& vec);
238 template<typename _Tp> _InputOutputArray(std::vector<Mat_<_Tp> >& vec);
239 template<typename _Tp> _InputOutputArray(Mat_<_Tp>& m);
240 template<typename _Tp> _InputOutputArray(_Tp* vec, int n);
241 template<typename _Tp, int m, int n> _InputOutputArray(Matx<_Tp, m, n>& matx);
242 _InputOutputArray(UMat& m);
243 _InputOutputArray(std::vector<UMat>& vec);
245 _InputOutputArray(const Mat& m);
246 _InputOutputArray(const std::vector<Mat>& vec);
247 _InputOutputArray(const cuda::GpuMat& d_mat);
248 _InputOutputArray(const ogl::Buffer& buf);
249 _InputOutputArray(const cuda::CudaMem& cuda_mem);
250 template<typename _Tp> _InputOutputArray(const cudev::GpuMat_<_Tp>& m);
251 template<typename _Tp> _InputOutputArray(const std::vector<_Tp>& vec);
252 template<typename _Tp> _InputOutputArray(const std::vector<std::vector<_Tp> >& vec);
253 template<typename _Tp> _InputOutputArray(const std::vector<Mat_<_Tp> >& vec);
254 template<typename _Tp> _InputOutputArray(const Mat_<_Tp>& m);
255 template<typename _Tp> _InputOutputArray(const _Tp* vec, int n);
256 template<typename _Tp, int m, int n> _InputOutputArray(const Matx<_Tp, m, n>& matx);
257 _InputOutputArray(const UMat& m);
258 _InputOutputArray(const std::vector<UMat>& vec);
261 typedef const _InputArray& InputArray;
262 typedef InputArray InputArrayOfArrays;
263 typedef const _OutputArray& OutputArray;
264 typedef OutputArray OutputArrayOfArrays;
265 typedef const _InputOutputArray& InputOutputArray;
266 typedef InputOutputArray InputOutputArrayOfArrays;
268 CV_EXPORTS InputOutputArray noArray();
270 /////////////////////////////////// MatAllocator //////////////////////////////////////
272 struct CV_EXPORTS UMatData;
275 Custom array allocator
278 class CV_EXPORTS MatAllocator
282 virtual ~MatAllocator() {}
284 // let's comment it off for now to detect and fix all the uses of allocator
285 //virtual void allocate(int dims, const int* sizes, int type, int*& refcount,
286 // uchar*& datastart, uchar*& data, size_t* step) = 0;
287 //virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0;
288 virtual UMatData* allocate(int dims, const int* sizes, int type,
289 void* data, size_t* step, int flags) const = 0;
290 virtual bool allocate(UMatData* data, int accessflags) const = 0;
291 virtual void deallocate(UMatData* data) const = 0;
292 virtual void map(UMatData* data, int accessflags) const;
293 virtual void unmap(UMatData* data) const;
294 virtual void download(UMatData* data, void* dst, int dims, const size_t sz[],
295 const size_t srcofs[], const size_t srcstep[],
296 const size_t dststep[]) const;
297 virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[],
298 const size_t dstofs[], const size_t dststep[],
299 const size_t srcstep[]) const;
300 virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[],
301 const size_t srcofs[], const size_t srcstep[],
302 const size_t dstofs[], const size_t dststep[], bool sync) const;
304 // default implementation returns DummyBufferPoolController
305 virtual BufferPoolController* getBufferPoolController() const;
309 //////////////////////////////// MatCommaInitializer //////////////////////////////////
312 Comma-separated Matrix Initializer
314 The class instances are usually not created explicitly.
315 Instead, they are created on "matrix << firstValue" operator.
317 The sample below initializes 2x2 rotation matrix:
320 double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180);
321 Mat R = (Mat_<double>(2,2) << a, -b, b, a);
324 template<typename _Tp> class MatCommaInitializer_
327 //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat
328 MatCommaInitializer_(Mat_<_Tp>* _m);
329 //! the operator that takes the next value and put it to the matrix
330 template<typename T2> MatCommaInitializer_<_Tp>& operator , (T2 v);
331 //! another form of conversion operator
332 operator Mat_<_Tp>() const;
334 MatIterator_<_Tp> it;
338 /////////////////////////////////////// Mat ///////////////////////////////////////////
340 // note that umatdata might be allocated together
341 // with the matrix data, not as a separate object.
342 // therefore, it does not have constructor or destructor;
343 // it should be explicitly initialized using init().
344 struct CV_EXPORTS UMatData
346 enum { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2,
347 DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24,
349 UMatData(const MatAllocator* allocator);
352 // provide atomic access to the structure
356 bool hostCopyObsolete() const;
357 bool deviceCopyObsolete() const;
358 bool copyOnMap() const;
359 bool tempUMat() const;
360 bool tempCopiedUMat() const;
361 void markHostCopyObsolete(bool flag);
362 void markDeviceCopyObsolete(bool flag);
364 const MatAllocator* prevAllocator;
365 const MatAllocator* currAllocator;
370 size_t size, capacity;
378 struct CV_EXPORTS UMatDataAutoLock
380 UMatDataAutoLock(UMatData* u);
386 struct CV_EXPORTS MatSize
389 Size operator()() const;
390 const int& operator[](int i) const;
391 int& operator[](int i);
392 operator const int*() const;
393 bool operator == (const MatSize& sz) const;
394 bool operator != (const MatSize& sz) const;
399 struct CV_EXPORTS MatStep
403 const size_t& operator[](int i) const;
404 size_t& operator[](int i);
405 operator size_t() const;
406 MatStep& operator = (size_t s);
411 MatStep& operator = (const MatStep&);
415 The n-dimensional matrix class.
417 The class represents an n-dimensional dense numerical array that can act as
418 a matrix, image, optical flow map, 3-focal tensor etc.
419 It is very similar to CvMat and CvMatND types from earlier versions of OpenCV,
420 and similarly to those types, the matrix can be multi-channel. It also fully supports ROI mechanism.
422 There are many different ways to create cv::Mat object. Here are the some popular ones:
424 <li> using cv::Mat::create(nrows, ncols, type) method or
425 the similar constructor cv::Mat::Mat(nrows, ncols, type[, fill_value]) constructor.
426 A new matrix of the specified size and specifed type will be allocated.
427 "type" has the same meaning as in cvCreateMat function,
428 e.g. CV_8UC1 means 8-bit single-channel matrix, CV_32FC2 means 2-channel (i.e. complex)
429 floating-point matrix etc:
432 // make 7x7 complex matrix filled with 1+3j.
433 cv::Mat M(7,7,CV_32FC2,Scalar(1,3));
434 // and now turn M to 100x60 15-channel 8-bit matrix.
435 // The old content will be deallocated
436 M.create(100,60,CV_8UC(15));
439 As noted in the introduction of this chapter, Mat::create()
440 will only allocate a new matrix when the current matrix dimensionality
441 or type are different from the specified.
443 <li> by using a copy constructor or assignment operator, where on the right side it can
444 be a matrix or expression, see below. Again, as noted in the introduction,
445 matrix assignment is O(1) operation because it only copies the header
446 and increases the reference counter. cv::Mat::clone() method can be used to get a full
447 (a.k.a. deep) copy of the matrix when you need it.
449 <li> by constructing a header for a part of another matrix. It can be a single row, single column,
450 several rows, several columns, rectangular region in the matrix (called a minor in algebra) or
451 a diagonal. Such operations are also O(1), because the new header will reference the same data.
452 You can actually modify a part of the matrix using this feature, e.g.
455 // add 5-th row, multiplied by 3 to the 3rd row
456 M.row(3) = M.row(3) + M.row(5)*3;
458 // now copy 7-th column to the 1-st column
459 // M.col(1) = M.col(7); // this will not work
463 // create new 320x240 image
464 cv::Mat img(Size(320,240),CV_8UC3);
466 cv::Mat roi(img, Rect(10,10,100,100));
467 // fill the ROI with (0,255,0) (which is green in RGB space);
468 // the original 320x240 image will be modified
469 roi = Scalar(0,255,0);
472 Thanks to the additional cv::Mat::datastart and cv::Mat::dataend members, it is possible to
473 compute the relative sub-matrix position in the main "container" matrix using cv::Mat::locateROI():
476 Mat A = Mat::eye(10, 10, CV_32S);
477 // extracts A columns, 1 (inclusive) to 3 (exclusive).
478 Mat B = A(Range::all(), Range(1, 3));
479 // extracts B rows, 5 (inclusive) to 9 (exclusive).
480 // that is, C ~ A(Range(5, 9), Range(1, 3))
481 Mat C = B(Range(5, 9), Range::all());
482 Size size; Point ofs;
483 C.locateROI(size, ofs);
484 // size will be (width=10,height=10) and the ofs will be (x=1, y=5)
487 As in the case of whole matrices, if you need a deep copy, use cv::Mat::clone() method
488 of the extracted sub-matrices.
490 <li> by making a header for user-allocated-data. It can be useful for
492 <li> processing "foreign" data using OpenCV (e.g. when you implement
493 a DirectShow filter or a processing module for gstreamer etc.), e.g.
496 void process_video_frame(const unsigned char* pixels,
497 int width, int height, int step)
499 cv::Mat img(height, width, CV_8UC3, pixels, step);
500 cv::GaussianBlur(img, img, cv::Size(7,7), 1.5, 1.5);
504 <li> for quick initialization of small matrices and/or super-fast element access
507 double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
508 cv::Mat M = cv::Mat(3, 3, CV_64F, m).inv();
512 partial yet very common cases of this "user-allocated data" case are conversions
513 from CvMat and IplImage to cv::Mat. For this purpose there are special constructors
514 taking pointers to CvMat or IplImage and the optional
515 flag indicating whether to copy the data or not.
517 Backward conversion from cv::Mat to CvMat or IplImage is provided via cast operators
518 cv::Mat::operator CvMat() an cv::Mat::operator IplImage().
519 The operators do not copy the data.
523 IplImage* img = cvLoadImage("greatwave.jpg", 1);
524 Mat mtx(img); // convert IplImage* -> cv::Mat
525 CvMat oldmat = mtx; // convert cv::Mat -> CvMat
526 CV_Assert(oldmat.cols == img->width && oldmat.rows == img->height &&
527 oldmat.data.ptr == (uchar*)img->imageData && oldmat.step == img->widthStep);
530 <li> by using MATLAB-style matrix initializers, cv::Mat::zeros(), cv::Mat::ones(), cv::Mat::eye(), e.g.:
533 // create a double-precision identity martix and add it to M.
534 M += Mat::eye(M.rows, M.cols, CV_64F);
537 <li> by using comma-separated initializer:
540 // create 3x3 double-precision identity matrix
541 Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
544 here we first call constructor of cv::Mat_ class (that we describe further) with the proper matrix,
545 and then we just put "<<" operator followed by comma-separated values that can be constants,
546 variables, expressions etc. Also, note the extra parentheses that are needed to avoid compiler errors.
550 Once matrix is created, it will be automatically managed by using reference-counting mechanism
551 (unless the matrix header is built on top of user-allocated data,
552 in which case you should handle the data by yourself).
553 The matrix data will be deallocated when no one points to it;
554 if you want to release the data pointed by a matrix header before the matrix destructor is called,
555 use cv::Mat::release().
557 The next important thing to learn about the matrix class is element access. Here is how the matrix is stored.
558 The elements are stored in row-major order (row by row). The cv::Mat::data member points to the first element of the first row,
559 cv::Mat::rows contains the number of matrix rows and cv::Mat::cols - the number of matrix columns. There is yet another member,
560 cv::Mat::step that is used to actually compute address of a matrix element. cv::Mat::step is needed because the matrix can be
561 a part of another matrix or because there can some padding space in the end of each row for a proper alignment.
565 Given these parameters, address of the matrix element M_{ij} is computed as following:
567 addr(M_{ij})=M.data + M.step*i + j*M.elemSize()
569 if you know the matrix element type, e.g. it is float, then you can use cv::Mat::at() method:
571 addr(M_{ij})=&M.at<float>(i,j)
573 (where & is used to convert the reference returned by cv::Mat::at() to a pointer).
574 if you need to process a whole row of matrix, the most efficient way is to get
575 the pointer to the row first, and then just use plain C operator []:
578 // compute sum of positive matrix elements
579 // (assuming that M is double-precision matrix)
581 for(int i = 0; i < M.rows; i++)
583 const double* Mi = M.ptr<double>(i);
584 for(int j = 0; j < M.cols; j++)
585 sum += std::max(Mi[j], 0.);
589 Some operations, like the above one, do not actually depend on the matrix shape,
590 they just process elements of a matrix one by one (or elements from multiple matrices
591 that are sitting in the same place, e.g. matrix addition). Such operations are called
592 element-wise and it makes sense to check whether all the input/output matrices are continuous,
593 i.e. have no gaps in the end of each row, and if yes, process them as a single long row:
596 // compute sum of positive matrix elements, optimized variant
598 int cols = M.cols, rows = M.rows;
604 for(int i = 0; i < rows; i++)
606 const double* Mi = M.ptr<double>(i);
607 for(int j = 0; j < cols; j++)
608 sum += std::max(Mi[j], 0.);
611 in the case of continuous matrix the outer loop body will be executed just once,
612 so the overhead will be smaller, which will be especially noticeable in the case of small matrices.
614 Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:
616 // compute sum of positive matrix elements, iterator-based variant
618 MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
619 for(; it != it_end; ++it)
620 sum += std::max(*it, 0.);
623 The matrix iterators are random-access iterators, so they can be passed
624 to any STL algorithm, including std::sort().
629 //! default constructor
631 //! constructs 2D matrix of the specified size and type
632 // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
633 Mat(int rows, int cols, int type);
634 Mat(Size size, int type);
635 //! constucts 2D matrix and fills it with the specified value _s.
636 Mat(int rows, int cols, int type, const Scalar& s);
637 Mat(Size size, int type, const Scalar& s);
639 //! constructs n-dimensional matrix
640 Mat(int ndims, const int* sizes, int type);
641 Mat(int ndims, const int* sizes, int type, const Scalar& s);
645 //! constructor for matrix headers pointing to user-allocated data
646 Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP);
647 Mat(Size size, int type, void* data, size_t step=AUTO_STEP);
648 Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0);
650 //! creates a matrix header for a part of the bigger matrix
651 Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all());
652 Mat(const Mat& m, const Rect& roi);
653 Mat(const Mat& m, const Range* ranges);
654 //! builds matrix from std::vector with or without copying the data
655 template<typename _Tp> explicit Mat(const std::vector<_Tp>& vec, bool copyData=false);
656 //! builds matrix from cv::Vec; the data is copied by default
657 template<typename _Tp, int n> explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true);
658 //! builds matrix from cv::Matx; the data is copied by default
659 template<typename _Tp, int m, int n> explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
660 //! builds matrix from a 2D point
661 template<typename _Tp> explicit Mat(const Point_<_Tp>& pt, bool copyData=true);
662 //! builds matrix from a 3D point
663 template<typename _Tp> explicit Mat(const Point3_<_Tp>& pt, bool copyData=true);
664 //! builds matrix from comma initializer
665 template<typename _Tp> explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer);
667 //! download data from GpuMat
668 explicit Mat(const cuda::GpuMat& m);
670 //! destructor - calls release()
672 //! assignment operators
673 Mat& operator = (const Mat& m);
674 Mat& operator = (const MatExpr& expr);
676 //! retrieve UMat from Mat
677 UMat getUMat(int accessFlags) const;
679 //! returns a new matrix header for the specified row
680 Mat row(int y) const;
681 //! returns a new matrix header for the specified column
682 Mat col(int x) const;
683 //! ... for the specified row span
684 Mat rowRange(int startrow, int endrow) const;
685 Mat rowRange(const Range& r) const;
686 //! ... for the specified column span
687 Mat colRange(int startcol, int endcol) const;
688 Mat colRange(const Range& r) const;
689 //! ... for the specified diagonal
690 // (d=0 - the main diagonal,
691 // >0 - a diagonal from the lower half,
692 // <0 - a diagonal from the upper half)
693 Mat diag(int d=0) const;
694 //! constructs a square diagonal matrix which main diagonal is vector "d"
695 static Mat diag(const Mat& d);
697 //! returns deep copy of the matrix, i.e. the data is copied
699 //! copies the matrix content to "m".
700 // It calls m.create(this->size(), this->type()).
701 void copyTo( OutputArray m ) const;
702 //! copies those matrix elements to "m" that are marked with non-zero mask elements.
703 void copyTo( OutputArray m, InputArray mask ) const;
704 //! converts matrix to another datatype with optional scalng. See cvConvertScale.
705 void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
707 void assignTo( Mat& m, int type=-1 ) const;
709 //! sets every matrix element to s
710 Mat& operator = (const Scalar& s);
711 //! sets some of the matrix elements to s, according to the mask
712 Mat& setTo(InputArray value, InputArray mask=noArray());
713 //! creates alternative matrix header for the same data, with different
714 // number of channels and/or different number of rows. see cvReshape.
715 Mat reshape(int cn, int rows=0) const;
716 Mat reshape(int cn, int newndims, const int* newsz) const;
718 //! matrix transposition by means of matrix expressions
720 //! matrix inversion by means of matrix expressions
721 MatExpr inv(int method=DECOMP_LU) const;
722 //! per-element matrix multiplication by means of matrix expressions
723 MatExpr mul(InputArray m, double scale=1) const;
725 //! computes cross-product of 2 3D vectors
726 Mat cross(InputArray m) const;
727 //! computes dot-product
728 double dot(InputArray m) const;
730 //! Matlab-style matrix initialization
731 static MatExpr zeros(int rows, int cols, int type);
732 static MatExpr zeros(Size size, int type);
733 static MatExpr zeros(int ndims, const int* sz, int type);
734 static MatExpr ones(int rows, int cols, int type);
735 static MatExpr ones(Size size, int type);
736 static MatExpr ones(int ndims, const int* sz, int type);
737 static MatExpr eye(int rows, int cols, int type);
738 static MatExpr eye(Size size, int type);
740 //! allocates new matrix data unless the matrix already has specified size and type.
741 // previous data is unreferenced if needed.
742 void create(int rows, int cols, int type);
743 void create(Size size, int type);
744 void create(int ndims, const int* sizes, int type);
746 //! increases the reference counter; use with care to avoid memleaks
748 //! decreases reference counter;
749 // deallocates the data when reference counter reaches 0.
752 //! deallocates the matrix data
754 //! internal use function; properly re-allocates _size, _step arrays
755 void copySize(const Mat& m);
757 //! reserves enough space to fit sz hyper-planes
758 void reserve(size_t sz);
759 //! resizes matrix to the specified number of hyper-planes
760 void resize(size_t sz);
761 //! resizes matrix to the specified number of hyper-planes; initializes the newly added elements
762 void resize(size_t sz, const Scalar& s);
763 //! internal function
764 void push_back_(const void* elem);
765 //! adds element to the end of 1d matrix (or possibly multiple elements when _Tp=Mat)
766 template<typename _Tp> void push_back(const _Tp& elem);
767 template<typename _Tp> void push_back(const Mat_<_Tp>& elem);
768 void push_back(const Mat& m);
769 //! removes several hyper-planes from bottom of the matrix
770 void pop_back(size_t nelems=1);
772 //! locates matrix header within a parent matrix. See below
773 void locateROI( Size& wholeSize, Point& ofs ) const;
774 //! moves/resizes the current matrix ROI inside the parent matrix.
775 Mat& adjustROI( int dtop, int dbottom, int dleft, int dright );
776 //! extracts a rectangular sub-matrix
777 // (this is a generalized form of row, rowRange etc.)
778 Mat operator()( Range rowRange, Range colRange ) const;
779 Mat operator()( const Rect& roi ) const;
780 Mat operator()( const Range* ranges ) const;
782 // //! converts header to CvMat; no data is copied
783 // operator CvMat() const;
784 // //! converts header to CvMatND; no data is copied
785 // operator CvMatND() const;
786 // //! converts header to IplImage; no data is copied
787 // operator IplImage() const;
789 template<typename _Tp> operator std::vector<_Tp>() const;
790 template<typename _Tp, int n> operator Vec<_Tp, n>() const;
791 template<typename _Tp, int m, int n> operator Matx<_Tp, m, n>() const;
793 //! returns true iff the matrix data is continuous
794 // (i.e. when there are no gaps between successive rows).
795 // similar to CV_IS_MAT_CONT(cvmat->type)
796 bool isContinuous() const;
798 //! returns true if the matrix is a submatrix of another matrix
799 bool isSubmatrix() const;
801 //! returns element size in bytes,
802 // similar to CV_ELEM_SIZE(cvmat->type)
803 size_t elemSize() const;
804 //! returns the size of element channel in bytes.
805 size_t elemSize1() const;
806 //! returns element type, similar to CV_MAT_TYPE(cvmat->type)
808 //! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
810 //! returns element type, similar to CV_MAT_CN(cvmat->type)
811 int channels() const;
812 //! returns step/elemSize1()
813 size_t step1(int i=0) const;
814 //! returns true if matrix data is NULL
816 //! returns the total number of matrix elements
817 size_t total() const;
819 //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
820 int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
822 //! returns pointer to i0-th submatrix along the dimension #0
823 uchar* ptr(int i0=0);
824 const uchar* ptr(int i0=0) const;
826 //! returns pointer to (i0,i1) submatrix along the dimensions #0 and #1
827 uchar* ptr(int i0, int i1);
828 const uchar* ptr(int i0, int i1) const;
830 //! returns pointer to (i0,i1,i3) submatrix along the dimensions #0, #1, #2
831 uchar* ptr(int i0, int i1, int i2);
832 const uchar* ptr(int i0, int i1, int i2) const;
834 //! returns pointer to the matrix element
835 uchar* ptr(const int* idx);
836 //! returns read-only pointer to the matrix element
837 const uchar* ptr(const int* idx) const;
839 template<int n> uchar* ptr(const Vec<int, n>& idx);
840 template<int n> const uchar* ptr(const Vec<int, n>& idx) const;
842 //! template version of the above method
843 template<typename _Tp> _Tp* ptr(int i0=0);
844 template<typename _Tp> const _Tp* ptr(int i0=0) const;
846 template<typename _Tp> _Tp* ptr(int i0, int i1);
847 template<typename _Tp> const _Tp* ptr(int i0, int i1) const;
849 template<typename _Tp> _Tp* ptr(int i0, int i1, int i2);
850 template<typename _Tp> const _Tp* ptr(int i0, int i1, int i2) const;
852 template<typename _Tp> _Tp* ptr(const int* idx);
853 template<typename _Tp> const _Tp* ptr(const int* idx) const;
855 template<typename _Tp, int n> _Tp* ptr(const Vec<int, n>& idx);
856 template<typename _Tp, int n> const _Tp* ptr(const Vec<int, n>& idx) const;
858 //! the same as above, with the pointer dereferencing
859 template<typename _Tp> _Tp& at(int i0=0);
860 template<typename _Tp> const _Tp& at(int i0=0) const;
862 template<typename _Tp> _Tp& at(int i0, int i1);
863 template<typename _Tp> const _Tp& at(int i0, int i1) const;
865 template<typename _Tp> _Tp& at(int i0, int i1, int i2);
866 template<typename _Tp> const _Tp& at(int i0, int i1, int i2) const;
868 template<typename _Tp> _Tp& at(const int* idx);
869 template<typename _Tp> const _Tp& at(const int* idx) const;
871 template<typename _Tp, int n> _Tp& at(const Vec<int, n>& idx);
872 template<typename _Tp, int n> const _Tp& at(const Vec<int, n>& idx) const;
874 //! special versions for 2D arrays (especially convenient for referencing image pixels)
875 template<typename _Tp> _Tp& at(Point pt);
876 template<typename _Tp> const _Tp& at(Point pt) const;
878 //! template methods for iteration over matrix elements.
879 // the iterators take care of skipping gaps in the end of rows (if any)
880 template<typename _Tp> MatIterator_<_Tp> begin();
881 template<typename _Tp> MatIterator_<_Tp> end();
882 template<typename _Tp> MatConstIterator_<_Tp> begin() const;
883 template<typename _Tp> MatConstIterator_<_Tp> end() const;
885 enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
886 enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
888 /*! includes several bit-fields:
889 - the magic signature
895 //! the matrix dimensionality, >= 2
897 //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
899 //! pointer to the data
902 //! helper fields used in locateROI and adjustROI
908 MatAllocator* allocator;
909 //! and the standard allocator
910 static MatAllocator* getStdAllocator();
912 //! interaction with UMat
922 ///////////////////////////////// Mat_<_Tp> ////////////////////////////////////
925 Template matrix class derived from Mat
927 The class Mat_ is a "thin" template wrapper on top of cv::Mat. It does not have any extra data fields,
928 nor it or cv::Mat have any virtual methods and thus references or pointers to these two classes
929 can be safely converted one to another. But do it with care, for example:
932 // create 100x100 8-bit matrix
933 Mat M(100,100,CV_8U);
934 // this will compile fine. no any data conversion will be done.
935 Mat_<float>& M1 = (Mat_<float>&)M;
936 // the program will likely crash at the statement below
940 While cv::Mat is sufficient in most cases, cv::Mat_ can be more convenient if you use a lot of element
941 access operations and if you know matrix type at compile time.
942 Note that cv::Mat::at<_Tp>(int y, int x) and cv::Mat_<_Tp>::operator ()(int y, int x) do absolutely the
943 same thing and run at the same speed, but the latter is certainly shorter:
946 Mat_<double> M(20,20);
947 for(int i = 0; i < M.rows; i++)
948 for(int j = 0; j < M.cols; j++)
952 cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
955 It is easy to use Mat_ for multi-channel images/matrices - just pass cv::Vec as cv::Mat_ template parameter:
958 // allocate 320x240 color image and fill it with green (in RGB space)
959 Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
960 // now draw a diagonal white line
961 for(int i = 0; i < 100; i++)
962 img(i,i)=Vec3b(255,255,255);
963 // and now modify the 2nd (red) channel of each pixel
964 for(int i = 0; i < img.rows; i++)
965 for(int j = 0; j < img.cols; j++)
966 img(i,j)[2] ^= (uchar)(i ^ j); // img(y,x)[c] accesses c-th channel of the pixel (x,y)
969 template<typename _Tp> class Mat_ : public Mat
972 typedef _Tp value_type;
973 typedef typename DataType<_Tp>::channel_type channel_type;
974 typedef MatIterator_<_Tp> iterator;
975 typedef MatConstIterator_<_Tp> const_iterator;
977 //! default constructor
979 //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type)
980 Mat_(int _rows, int _cols);
981 //! constructor that sets each matrix element to specified value
982 Mat_(int _rows, int _cols, const _Tp& value);
983 //! equivalent to Mat(_size, DataType<_Tp>::type)
984 explicit Mat_(Size _size);
985 //! constructor that sets each matrix element to specified value
986 Mat_(Size _size, const _Tp& value);
987 //! n-dim array constructor
988 Mat_(int _ndims, const int* _sizes);
989 //! n-dim array constructor that sets each matrix element to specified value
990 Mat_(int _ndims, const int* _sizes, const _Tp& value);
991 //! copy/conversion contructor. If m is of different type, it's converted
995 //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type
996 Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP);
997 //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type
998 Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0);
999 //! selects a submatrix
1000 Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all());
1001 //! selects a submatrix
1002 Mat_(const Mat_& m, const Rect& roi);
1003 //! selects a submatrix, n-dim version
1004 Mat_(const Mat_& m, const Range* ranges);
1005 //! from a matrix expression
1006 explicit Mat_(const MatExpr& e);
1007 //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column
1008 explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false);
1009 template<int n> explicit Mat_(const Vec<typename DataType<_Tp>::channel_type, n>& vec, bool copyData=true);
1010 template<int m, int n> explicit Mat_(const Matx<typename DataType<_Tp>::channel_type, m, n>& mtx, bool copyData=true);
1011 explicit Mat_(const Point_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
1012 explicit Mat_(const Point3_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
1013 explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer);
1015 Mat_& operator = (const Mat& m);
1016 Mat_& operator = (const Mat_& m);
1017 //! set all the elements to s.
1018 Mat_& operator = (const _Tp& s);
1019 //! assign a matrix expression
1020 Mat_& operator = (const MatExpr& e);
1022 //! iterators; they are smart enough to skip gaps in the end of rows
1025 const_iterator begin() const;
1026 const_iterator end() const;
1028 //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type)
1029 void create(int _rows, int _cols);
1030 //! equivalent to Mat::create(_size, DataType<_Tp>::type)
1031 void create(Size _size);
1032 //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type)
1033 void create(int _ndims, const int* _sizes);
1035 Mat_ cross(const Mat_& m) const;
1036 //! data type conversion
1037 template<typename T2> operator Mat_<T2>() const;
1038 //! overridden forms of Mat::row() etc.
1039 Mat_ row(int y) const;
1040 Mat_ col(int x) const;
1041 Mat_ diag(int d=0) const;
1044 //! overridden forms of Mat::elemSize() etc.
1045 size_t elemSize() const;
1046 size_t elemSize1() const;
1049 int channels() const;
1050 size_t step1(int i=0) const;
1051 //! returns step()/sizeof(_Tp)
1052 size_t stepT(int i=0) const;
1054 //! overridden forms of Mat::zeros() etc. Data type is omitted, of course
1055 static MatExpr zeros(int rows, int cols);
1056 static MatExpr zeros(Size size);
1057 static MatExpr zeros(int _ndims, const int* _sizes);
1058 static MatExpr ones(int rows, int cols);
1059 static MatExpr ones(Size size);
1060 static MatExpr ones(int _ndims, const int* _sizes);
1061 static MatExpr eye(int rows, int cols);
1062 static MatExpr eye(Size size);
1064 //! some more overriden methods
1065 Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright );
1066 Mat_ operator()( const Range& rowRange, const Range& colRange ) const;
1067 Mat_ operator()( const Rect& roi ) const;
1068 Mat_ operator()( const Range* ranges ) const;
1070 //! more convenient forms of row and element access operators
1071 _Tp* operator [](int y);
1072 const _Tp* operator [](int y) const;
1074 //! returns reference to the specified element
1075 _Tp& operator ()(const int* idx);
1076 //! returns read-only reference to the specified element
1077 const _Tp& operator ()(const int* idx) const;
1079 //! returns reference to the specified element
1080 template<int n> _Tp& operator ()(const Vec<int, n>& idx);
1081 //! returns read-only reference to the specified element
1082 template<int n> const _Tp& operator ()(const Vec<int, n>& idx) const;
1084 //! returns reference to the specified element (1D case)
1085 _Tp& operator ()(int idx0);
1086 //! returns read-only reference to the specified element (1D case)
1087 const _Tp& operator ()(int idx0) const;
1088 //! returns reference to the specified element (2D case)
1089 _Tp& operator ()(int idx0, int idx1);
1090 //! returns read-only reference to the specified element (2D case)
1091 const _Tp& operator ()(int idx0, int idx1) const;
1092 //! returns reference to the specified element (3D case)
1093 _Tp& operator ()(int idx0, int idx1, int idx2);
1094 //! returns read-only reference to the specified element (3D case)
1095 const _Tp& operator ()(int idx0, int idx1, int idx2) const;
1097 _Tp& operator ()(Point pt);
1098 const _Tp& operator ()(Point pt) const;
1100 //! conversion to vector.
1101 operator std::vector<_Tp>() const;
1102 //! conversion to Vec
1103 template<int n> operator Vec<typename DataType<_Tp>::channel_type, n>() const;
1104 //! conversion to Matx
1105 template<int m, int n> operator Matx<typename DataType<_Tp>::channel_type, m, n>() const;
1108 typedef Mat_<uchar> Mat1b;
1109 typedef Mat_<Vec2b> Mat2b;
1110 typedef Mat_<Vec3b> Mat3b;
1111 typedef Mat_<Vec4b> Mat4b;
1113 typedef Mat_<short> Mat1s;
1114 typedef Mat_<Vec2s> Mat2s;
1115 typedef Mat_<Vec3s> Mat3s;
1116 typedef Mat_<Vec4s> Mat4s;
1118 typedef Mat_<ushort> Mat1w;
1119 typedef Mat_<Vec2w> Mat2w;
1120 typedef Mat_<Vec3w> Mat3w;
1121 typedef Mat_<Vec4w> Mat4w;
1123 typedef Mat_<int> Mat1i;
1124 typedef Mat_<Vec2i> Mat2i;
1125 typedef Mat_<Vec3i> Mat3i;
1126 typedef Mat_<Vec4i> Mat4i;
1128 typedef Mat_<float> Mat1f;
1129 typedef Mat_<Vec2f> Mat2f;
1130 typedef Mat_<Vec3f> Mat3f;
1131 typedef Mat_<Vec4f> Mat4f;
1133 typedef Mat_<double> Mat1d;
1134 typedef Mat_<Vec2d> Mat2d;
1135 typedef Mat_<Vec3d> Mat3d;
1136 typedef Mat_<Vec4d> Mat4d;
1139 class CV_EXPORTS UMatExpr;
1141 class CV_EXPORTS UMat
1144 //! default constructor
1146 //! constructs 2D matrix of the specified size and type
1147 // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
1148 UMat(int rows, int cols, int type);
1149 UMat(Size size, int type);
1150 //! constucts 2D matrix and fills it with the specified value _s.
1151 UMat(int rows, int cols, int type, const Scalar& s);
1152 UMat(Size size, int type, const Scalar& s);
1154 //! constructs n-dimensional matrix
1155 UMat(int ndims, const int* sizes, int type);
1156 UMat(int ndims, const int* sizes, int type, const Scalar& s);
1158 //! copy constructor
1159 UMat(const UMat& m);
1161 //! creates a matrix header for a part of the bigger matrix
1162 UMat(const UMat& m, const Range& rowRange, const Range& colRange=Range::all());
1163 UMat(const UMat& m, const Rect& roi);
1164 UMat(const UMat& m, const Range* ranges);
1165 //! builds matrix from std::vector with or without copying the data
1166 template<typename _Tp> explicit UMat(const std::vector<_Tp>& vec, bool copyData=false);
1167 //! builds matrix from cv::Vec; the data is copied by default
1168 template<typename _Tp, int n> explicit UMat(const Vec<_Tp, n>& vec, bool copyData=true);
1169 //! builds matrix from cv::Matx; the data is copied by default
1170 template<typename _Tp, int m, int n> explicit UMat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
1171 //! builds matrix from a 2D point
1172 template<typename _Tp> explicit UMat(const Point_<_Tp>& pt, bool copyData=true);
1173 //! builds matrix from a 3D point
1174 template<typename _Tp> explicit UMat(const Point3_<_Tp>& pt, bool copyData=true);
1175 //! builds matrix from comma initializer
1176 template<typename _Tp> explicit UMat(const MatCommaInitializer_<_Tp>& commaInitializer);
1178 //! destructor - calls release()
1180 //! assignment operators
1181 UMat& operator = (const UMat& m);
1182 UMat& operator = (const UMatExpr& expr);
1184 Mat getMat(int flags) const;
1186 //! returns a new matrix header for the specified row
1187 UMat row(int y) const;
1188 //! returns a new matrix header for the specified column
1189 UMat col(int x) const;
1190 //! ... for the specified row span
1191 UMat rowRange(int startrow, int endrow) const;
1192 UMat rowRange(const Range& r) const;
1193 //! ... for the specified column span
1194 UMat colRange(int startcol, int endcol) const;
1195 UMat colRange(const Range& r) const;
1196 //! ... for the specified diagonal
1197 // (d=0 - the main diagonal,
1198 // >0 - a diagonal from the lower half,
1199 // <0 - a diagonal from the upper half)
1200 UMat diag(int d=0) const;
1201 //! constructs a square diagonal matrix which main diagonal is vector "d"
1202 static UMat diag(const UMat& d);
1204 //! returns deep copy of the matrix, i.e. the data is copied
1206 //! copies the matrix content to "m".
1207 // It calls m.create(this->size(), this->type()).
1208 void copyTo( OutputArray m ) const;
1209 //! copies those matrix elements to "m" that are marked with non-zero mask elements.
1210 void copyTo( OutputArray m, InputArray mask ) const;
1211 //! converts matrix to another datatype with optional scalng. See cvConvertScale.
1212 void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
1214 void assignTo( UMat& m, int type=-1 ) const;
1216 //! sets every matrix element to s
1217 UMat& operator = (const Scalar& s);
1218 //! sets some of the matrix elements to s, according to the mask
1219 UMat& setTo(InputArray value, InputArray mask=noArray());
1220 //! creates alternative matrix header for the same data, with different
1221 // number of channels and/or different number of rows. see cvReshape.
1222 UMat reshape(int cn, int rows=0) const;
1223 UMat reshape(int cn, int newndims, const int* newsz) const;
1225 //! matrix transposition by means of matrix expressions
1227 //! matrix inversion by means of matrix expressions
1228 UMatExpr inv(int method=DECOMP_LU) const;
1229 //! per-element matrix multiplication by means of matrix expressions
1230 UMatExpr mul(InputArray m, double scale=1) const;
1232 //! computes cross-product of 2 3D vectors
1233 UMat cross(InputArray m) const;
1234 //! computes dot-product
1235 double dot(InputArray m) const;
1237 //! Matlab-style matrix initialization
1238 static UMatExpr zeros(int rows, int cols, int type);
1239 static UMatExpr zeros(Size size, int type);
1240 static UMatExpr zeros(int ndims, const int* sz, int type);
1241 static UMatExpr ones(int rows, int cols, int type);
1242 static UMatExpr ones(Size size, int type);
1243 static UMatExpr ones(int ndims, const int* sz, int type);
1244 static UMatExpr eye(int rows, int cols, int type);
1245 static UMatExpr eye(Size size, int type);
1247 //! allocates new matrix data unless the matrix already has specified size and type.
1248 // previous data is unreferenced if needed.
1249 void create(int rows, int cols, int type);
1250 void create(Size size, int type);
1251 void create(int ndims, const int* sizes, int type);
1253 //! increases the reference counter; use with care to avoid memleaks
1255 //! decreases reference counter;
1256 // deallocates the data when reference counter reaches 0.
1259 //! deallocates the matrix data
1261 //! internal use function; properly re-allocates _size, _step arrays
1262 void copySize(const UMat& m);
1264 //! locates matrix header within a parent matrix. See below
1265 void locateROI( Size& wholeSize, Point& ofs ) const;
1266 //! moves/resizes the current matrix ROI inside the parent matrix.
1267 UMat& adjustROI( int dtop, int dbottom, int dleft, int dright );
1268 //! extracts a rectangular sub-matrix
1269 // (this is a generalized form of row, rowRange etc.)
1270 UMat operator()( Range rowRange, Range colRange ) const;
1271 UMat operator()( const Rect& roi ) const;
1272 UMat operator()( const Range* ranges ) const;
1274 //! returns true iff the matrix data is continuous
1275 // (i.e. when there are no gaps between successive rows).
1276 // similar to CV_IS_MAT_CONT(cvmat->type)
1277 bool isContinuous() const;
1279 //! returns true if the matrix is a submatrix of another matrix
1280 bool isSubmatrix() const;
1282 //! returns element size in bytes,
1283 // similar to CV_ELEM_SIZE(cvmat->type)
1284 size_t elemSize() const;
1285 //! returns the size of element channel in bytes.
1286 size_t elemSize1() const;
1287 //! returns element type, similar to CV_MAT_TYPE(cvmat->type)
1289 //! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
1291 //! returns element type, similar to CV_MAT_CN(cvmat->type)
1292 int channels() const;
1293 //! returns step/elemSize1()
1294 size_t step1(int i=0) const;
1295 //! returns true if matrix data is NULL
1297 //! returns the total number of matrix elements
1298 size_t total() const;
1300 //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
1301 int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
1303 void* handle(int accessFlags) const;
1304 void ndoffset(size_t* ofs) const;
1306 enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
1307 enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
1309 /*! includes several bit-fields:
1310 - the magic signature
1313 - number of channels
1316 //! the matrix dimensionality, >= 2
1318 //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
1321 //! custom allocator
1322 MatAllocator* allocator;
1323 //! and the standard allocator
1324 static MatAllocator* getStdAllocator();
1326 // black-box container of UMat data
1329 // offset of the submatrix (or 0)
1339 /////////////////////////// multi-dimensional sparse matrix //////////////////////////
1342 Sparse matrix class.
1344 The class represents multi-dimensional sparse numerical arrays. Such a sparse array can store elements
1345 of any type that cv::Mat is able to store. "Sparse" means that only non-zero elements
1346 are stored (though, as a result of some operations on a sparse matrix, some of its stored elements
1347 can actually become 0. It's user responsibility to detect such elements and delete them using cv::SparseMat::erase().
1348 The non-zero elements are stored in a hash table that grows when it's filled enough,
1349 so that the search time remains O(1) in average. Elements can be accessed using the following methods:
1352 <li>Query operations: cv::SparseMat::ptr() and the higher-level cv::SparseMat::ref(),
1353 cv::SparseMat::value() and cv::SparseMat::find, for example:
1356 int size[] = {10, 10, 10, 10, 10};
1357 SparseMat sparse_mat(dims, size, CV_32F);
1358 for(int i = 0; i < 1000; i++)
1361 for(int k = 0; k < dims; k++)
1362 idx[k] = rand()%sparse_mat.size(k);
1363 sparse_mat.ref<float>(idx) += 1.f;
1367 <li>Sparse matrix iterators. Like cv::Mat iterators and unlike cv::Mat iterators, the sparse matrix iterators are STL-style,
1368 that is, the iteration is done as following:
1370 // prints elements of a sparse floating-point matrix and the sum of elements.
1371 SparseMatConstIterator_<float>
1372 it = sparse_mat.begin<float>(),
1373 it_end = sparse_mat.end<float>();
1375 int dims = sparse_mat.dims();
1376 for(; it != it_end; ++it)
1378 // print element indices and the element value
1379 const Node* n = it.node();
1381 for(int i = 0; i < dims; i++)
1382 printf("%3d%c", n->idx[i], i < dims-1 ? ',' : ')');
1383 printf(": %f\n", *it);
1386 printf("Element sum is %g\n", s);
1388 If you run this loop, you will notice that elements are enumerated
1389 in no any logical order (lexicographical etc.),
1390 they come in the same order as they stored in the hash table, i.e. semi-randomly.
1392 You may collect pointers to the nodes and sort them to get the proper ordering.
1393 Note, however, that pointers to the nodes may become invalid when you add more
1394 elements to the matrix; this is because of possible buffer reallocation.
1396 <li>A combination of the above 2 methods when you need to process 2 or more sparse
1397 matrices simultaneously, e.g. this is how you can compute unnormalized
1398 cross-correlation of the 2 floating-point sparse matrices:
1400 double crossCorr(const SparseMat& a, const SparseMat& b)
1402 const SparseMat *_a = &a, *_b = &b;
1403 // if b contains less elements than a,
1404 // it's faster to iterate through b
1405 if(_a->nzcount() > _b->nzcount())
1407 SparseMatConstIterator_<float> it = _a->begin<float>(),
1408 it_end = _a->end<float>();
1410 for(; it != it_end; ++it)
1412 // take the next element from the first matrix
1414 const Node* anode = it.node();
1415 // and try to find element with the same index in the second matrix.
1416 // since the hash value depends only on the element index,
1417 // we reuse hashvalue stored in the node
1418 float bvalue = _b->value<float>(anode->idx,&anode->hashval);
1419 ccorr += avalue*bvalue;
1426 class CV_EXPORTS SparseMat
1429 typedef SparseMatIterator iterator;
1430 typedef SparseMatConstIterator const_iterator;
1432 enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 };
1434 //! the sparse matrix header
1435 struct CV_EXPORTS Hdr
1437 Hdr(int _dims, const int* _sizes, int _type);
1445 std::vector<uchar> pool;
1446 std::vector<size_t> hashtab;
1450 //! sparse matrix node - element of a hash table
1451 struct CV_EXPORTS Node
1455 //! index of the next node in the same hash table entry
1457 //! index of the matrix element
1461 //! default constructor
1463 //! creates matrix of the specified size and type
1464 SparseMat(int dims, const int* _sizes, int _type);
1465 //! copy constructor
1466 SparseMat(const SparseMat& m);
1467 //! converts dense 2d matrix to the sparse form
1469 \param m the input matrix
1471 explicit SparseMat(const Mat& m);
1472 //! converts old-style sparse matrix to the new-style. All the data is copied
1473 //SparseMat(const CvSparseMat* m);
1477 //! assignment operator. This is O(1) operation, i.e. no data is copied
1478 SparseMat& operator = (const SparseMat& m);
1479 //! equivalent to the corresponding constructor
1480 SparseMat& operator = (const Mat& m);
1482 //! creates full copy of the matrix
1483 SparseMat clone() const;
1485 //! copies all the data to the destination matrix. All the previous content of m is erased
1486 void copyTo( SparseMat& m ) const;
1487 //! converts sparse matrix to dense matrix.
1488 void copyTo( Mat& m ) const;
1489 //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type
1490 void convertTo( SparseMat& m, int rtype, double alpha=1 ) const;
1491 //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling.
1493 \param rtype The output matrix data type. When it is =-1, the output array will have the same data type as (*this)
1494 \param alpha The scale factor
1495 \param beta The optional delta added to the scaled values before the conversion
1497 void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
1500 void assignTo( SparseMat& m, int type=-1 ) const;
1502 //! reallocates sparse matrix.
1504 If the matrix already had the proper size and type,
1505 it is simply cleared with clear(), otherwise,
1506 the old matrix is released (using release()) and the new one is allocated.
1508 void create(int dims, const int* _sizes, int _type);
1509 //! sets all the sparse matrix elements to 0, which means clearing the hash table.
1511 //! manually increments the reference counter to the header.
1513 // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated.
1516 //! converts sparse matrix to the old-style representation; all the elements are copied.
1517 //operator CvSparseMat*() const;
1518 //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements)
1519 size_t elemSize() const;
1520 //! returns elemSize()/channels()
1521 size_t elemSize1() const;
1523 //! returns type of sparse matrix elements
1525 //! returns the depth of sparse matrix elements
1527 //! returns the number of channels
1528 int channels() const;
1530 //! returns the array of sizes, or NULL if the matrix is not allocated
1531 const int* size() const;
1532 //! returns the size of i-th matrix dimension (or 0)
1533 int size(int i) const;
1534 //! returns the matrix dimensionality
1536 //! returns the number of non-zero elements (=the number of hash table nodes)
1537 size_t nzcount() const;
1539 //! computes the element hash value (1D case)
1540 size_t hash(int i0) const;
1541 //! computes the element hash value (2D case)
1542 size_t hash(int i0, int i1) const;
1543 //! computes the element hash value (3D case)
1544 size_t hash(int i0, int i1, int i2) const;
1545 //! computes the element hash value (nD case)
1546 size_t hash(const int* idx) const;
1550 specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case.
1552 return pointer to the matrix element.
1554 <li>if the element is there (it's non-zero), the pointer to it is returned
1555 <li>if it's not there and createMissing=false, NULL pointer is returned
1556 <li>if it's not there and createMissing=true, then the new element
1557 is created and initialized with 0. Pointer to it is returned
1558 <li>if the optional hashval pointer is not NULL, the element hash value is
1559 not computed, but *hashval is taken instead.
1562 //! returns pointer to the specified element (1D case)
1563 uchar* ptr(int i0, bool createMissing, size_t* hashval=0);
1564 //! returns pointer to the specified element (2D case)
1565 uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0);
1566 //! returns pointer to the specified element (3D case)
1567 uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0);
1568 //! returns pointer to the specified element (nD case)
1569 uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0);
1574 return read-write reference to the specified sparse matrix element.
1576 ref<_Tp>(i0,...[,hashval]) is equivalent to *(_Tp*)ptr(i0,...,true[,hashval]).
1577 The methods always return a valid reference.
1578 If the element did not exist, it is created and initialiazed with 0.
1580 //! returns reference to the specified element (1D case)
1581 template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0);
1582 //! returns reference to the specified element (2D case)
1583 template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0);
1584 //! returns reference to the specified element (3D case)
1585 template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
1586 //! returns reference to the specified element (nD case)
1587 template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0);
1592 return value of the specified sparse matrix element.
1594 value<_Tp>(i0,...[,hashval]) is equivalent
1597 { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); }
1600 That is, if the element did not exist, the methods return 0.
1602 //! returns value of the specified element (1D case)
1603 template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const;
1604 //! returns value of the specified element (2D case)
1605 template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const;
1606 //! returns value of the specified element (3D case)
1607 template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0) const;
1608 //! returns value of the specified element (nD case)
1609 template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const;
1614 Return pointer to the specified sparse matrix element if it exists
1616 find<_Tp>(i0,...[,hashval]) is equivalent to (_const Tp*)ptr(i0,...false[,hashval]).
1618 If the specified element does not exist, the methods return NULL.
1620 //! returns pointer to the specified element (1D case)
1621 template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const;
1622 //! returns pointer to the specified element (2D case)
1623 template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0) const;
1624 //! returns pointer to the specified element (3D case)
1625 template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const;
1626 //! returns pointer to the specified element (nD case)
1627 template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0) const;
1629 //! erases the specified element (2D case)
1630 void erase(int i0, int i1, size_t* hashval=0);
1631 //! erases the specified element (3D case)
1632 void erase(int i0, int i1, int i2, size_t* hashval=0);
1633 //! erases the specified element (nD case)
1634 void erase(const int* idx, size_t* hashval=0);
1638 return the sparse matrix iterator pointing to the first sparse matrix element
1640 //! returns the sparse matrix iterator at the matrix beginning
1641 SparseMatIterator begin();
1642 //! returns the sparse matrix iterator at the matrix beginning
1643 template<typename _Tp> SparseMatIterator_<_Tp> begin();
1644 //! returns the read-only sparse matrix iterator at the matrix beginning
1645 SparseMatConstIterator begin() const;
1646 //! returns the read-only sparse matrix iterator at the matrix beginning
1647 template<typename _Tp> SparseMatConstIterator_<_Tp> begin() const;
1650 return the sparse matrix iterator pointing to the element following the last sparse matrix element
1652 //! returns the sparse matrix iterator at the matrix end
1653 SparseMatIterator end();
1654 //! returns the read-only sparse matrix iterator at the matrix end
1655 SparseMatConstIterator end() const;
1656 //! returns the typed sparse matrix iterator at the matrix end
1657 template<typename _Tp> SparseMatIterator_<_Tp> end();
1658 //! returns the typed read-only sparse matrix iterator at the matrix end
1659 template<typename _Tp> SparseMatConstIterator_<_Tp> end() const;
1661 //! returns the value stored in the sparse martix node
1662 template<typename _Tp> _Tp& value(Node* n);
1663 //! returns the value stored in the sparse martix node
1664 template<typename _Tp> const _Tp& value(const Node* n) const;
1666 ////////////// some internal-use methods ///////////////
1667 Node* node(size_t nidx);
1668 const Node* node(size_t nidx) const;
1670 uchar* newNode(const int* idx, size_t hashval);
1671 void removeNode(size_t hidx, size_t nidx, size_t previdx);
1672 void resizeHashTab(size_t newsize);
1680 ///////////////////////////////// SparseMat_<_Tp> ////////////////////////////////////
1683 The Template Sparse Matrix class derived from cv::SparseMat
1685 The class provides slightly more convenient operations for accessing elements.
1690 SparseMat_<int> m_ = (SparseMat_<int>&)m;
1691 m_.ref(1)++; // equivalent to m.ref<int>(1)++;
1692 m_.ref(2) += m_(3); // equivalent to m.ref<int>(2) += m.value<int>(3);
1695 template<typename _Tp> class SparseMat_ : public SparseMat
1698 typedef SparseMatIterator_<_Tp> iterator;
1699 typedef SparseMatConstIterator_<_Tp> const_iterator;
1701 //! the default constructor
1703 //! the full constructor equivelent to SparseMat(dims, _sizes, DataType<_Tp>::type)
1704 SparseMat_(int dims, const int* _sizes);
1705 //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted
1706 SparseMat_(const SparseMat& m);
1707 //! the copy constructor. This is O(1) operation - no data is copied
1708 SparseMat_(const SparseMat_& m);
1709 //! converts dense matrix to the sparse form
1710 SparseMat_(const Mat& m);
1711 //! converts the old-style sparse matrix to the C++ class. All the elements are copied
1712 //SparseMat_(const CvSparseMat* m);
1713 //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted
1714 SparseMat_& operator = (const SparseMat& m);
1715 //! the assignment operator. This is O(1) operation - no data is copied
1716 SparseMat_& operator = (const SparseMat_& m);
1717 //! converts dense matrix to the sparse form
1718 SparseMat_& operator = (const Mat& m);
1720 //! makes full copy of the matrix. All the elements are duplicated
1721 SparseMat_ clone() const;
1722 //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type)
1723 void create(int dims, const int* _sizes);
1724 //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied
1725 //operator CvSparseMat*() const;
1727 //! returns type of the matrix elements
1729 //! returns depth of the matrix elements
1731 //! returns the number of channels in each matrix element
1732 int channels() const;
1734 //! equivalent to SparseMat::ref<_Tp>(i0, hashval)
1735 _Tp& ref(int i0, size_t* hashval=0);
1736 //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval)
1737 _Tp& ref(int i0, int i1, size_t* hashval=0);
1738 //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval)
1739 _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
1740 //! equivalent to SparseMat::ref<_Tp>(idx, hashval)
1741 _Tp& ref(const int* idx, size_t* hashval=0);
1743 //! equivalent to SparseMat::value<_Tp>(i0, hashval)
1744 _Tp operator()(int i0, size_t* hashval=0) const;
1745 //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval)
1746 _Tp operator()(int i0, int i1, size_t* hashval=0) const;
1747 //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval)
1748 _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const;
1749 //! equivalent to SparseMat::value<_Tp>(idx, hashval)
1750 _Tp operator()(const int* idx, size_t* hashval=0) const;
1752 //! returns sparse matrix iterator pointing to the first sparse matrix element
1753 SparseMatIterator_<_Tp> begin();
1754 //! returns read-only sparse matrix iterator pointing to the first sparse matrix element
1755 SparseMatConstIterator_<_Tp> begin() const;
1756 //! returns sparse matrix iterator pointing to the element following the last sparse matrix element
1757 SparseMatIterator_<_Tp> end();
1758 //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element
1759 SparseMatConstIterator_<_Tp> end() const;
1764 ////////////////////////////////// MatConstIterator //////////////////////////////////
1766 class CV_EXPORTS MatConstIterator
1769 typedef uchar* value_type;
1770 typedef ptrdiff_t difference_type;
1771 typedef const uchar** pointer;
1772 typedef uchar* reference;
1774 #ifndef OPENCV_NOSTL
1775 typedef std::random_access_iterator_tag iterator_category;
1778 //! default constructor
1780 //! constructor that sets the iterator to the beginning of the matrix
1781 MatConstIterator(const Mat* _m);
1782 //! constructor that sets the iterator to the specified element of the matrix
1783 MatConstIterator(const Mat* _m, int _row, int _col=0);
1784 //! constructor that sets the iterator to the specified element of the matrix
1785 MatConstIterator(const Mat* _m, Point _pt);
1786 //! constructor that sets the iterator to the specified element of the matrix
1787 MatConstIterator(const Mat* _m, const int* _idx);
1788 //! copy constructor
1789 MatConstIterator(const MatConstIterator& it);
1792 MatConstIterator& operator = (const MatConstIterator& it);
1793 //! returns the current matrix element
1794 uchar* operator *() const;
1795 //! returns the i-th matrix element, relative to the current
1796 uchar* operator [](ptrdiff_t i) const;
1798 //! shifts the iterator forward by the specified number of elements
1799 MatConstIterator& operator += (ptrdiff_t ofs);
1800 //! shifts the iterator backward by the specified number of elements
1801 MatConstIterator& operator -= (ptrdiff_t ofs);
1802 //! decrements the iterator
1803 MatConstIterator& operator --();
1804 //! decrements the iterator
1805 MatConstIterator operator --(int);
1806 //! increments the iterator
1807 MatConstIterator& operator ++();
1808 //! increments the iterator
1809 MatConstIterator operator ++(int);
1810 //! returns the current iterator position
1812 //! returns the current iterator position
1813 void pos(int* _idx) const;
1815 ptrdiff_t lpos() const;
1816 void seek(ptrdiff_t ofs, bool relative = false);
1817 void seek(const int* _idx, bool relative = false);
1828 ////////////////////////////////// MatConstIterator_ /////////////////////////////////
1831 Matrix read-only iterator
1833 template<typename _Tp>
1834 class MatConstIterator_ : public MatConstIterator
1837 typedef _Tp value_type;
1838 typedef ptrdiff_t difference_type;
1839 typedef const _Tp* pointer;
1840 typedef const _Tp& reference;
1842 #ifndef OPENCV_NOSTL
1843 typedef std::random_access_iterator_tag iterator_category;
1846 //! default constructor
1847 MatConstIterator_();
1848 //! constructor that sets the iterator to the beginning of the matrix
1849 MatConstIterator_(const Mat_<_Tp>* _m);
1850 //! constructor that sets the iterator to the specified element of the matrix
1851 MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0);
1852 //! constructor that sets the iterator to the specified element of the matrix
1853 MatConstIterator_(const Mat_<_Tp>* _m, Point _pt);
1854 //! constructor that sets the iterator to the specified element of the matrix
1855 MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx);
1856 //! copy constructor
1857 MatConstIterator_(const MatConstIterator_& it);
1860 MatConstIterator_& operator = (const MatConstIterator_& it);
1861 //! returns the current matrix element
1862 _Tp operator *() const;
1863 //! returns the i-th matrix element, relative to the current
1864 _Tp operator [](ptrdiff_t i) const;
1866 //! shifts the iterator forward by the specified number of elements
1867 MatConstIterator_& operator += (ptrdiff_t ofs);
1868 //! shifts the iterator backward by the specified number of elements
1869 MatConstIterator_& operator -= (ptrdiff_t ofs);
1870 //! decrements the iterator
1871 MatConstIterator_& operator --();
1872 //! decrements the iterator
1873 MatConstIterator_ operator --(int);
1874 //! increments the iterator
1875 MatConstIterator_& operator ++();
1876 //! increments the iterator
1877 MatConstIterator_ operator ++(int);
1878 //! returns the current iterator position
1884 //////////////////////////////////// MatIterator_ ////////////////////////////////////
1887 Matrix read-write iterator
1889 template<typename _Tp>
1890 class MatIterator_ : public MatConstIterator_<_Tp>
1893 typedef _Tp* pointer;
1894 typedef _Tp& reference;
1896 #ifndef OPENCV_NOSTL
1897 typedef std::random_access_iterator_tag iterator_category;
1900 //! the default constructor
1902 //! constructor that sets the iterator to the beginning of the matrix
1903 MatIterator_(Mat_<_Tp>* _m);
1904 //! constructor that sets the iterator to the specified element of the matrix
1905 MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0);
1906 //! constructor that sets the iterator to the specified element of the matrix
1907 MatIterator_(const Mat_<_Tp>* _m, Point _pt);
1908 //! constructor that sets the iterator to the specified element of the matrix
1909 MatIterator_(const Mat_<_Tp>* _m, const int* _idx);
1910 //! copy constructor
1911 MatIterator_(const MatIterator_& it);
1913 MatIterator_& operator = (const MatIterator_<_Tp>& it );
1915 //! returns the current matrix element
1916 _Tp& operator *() const;
1917 //! returns the i-th matrix element, relative to the current
1918 _Tp& operator [](ptrdiff_t i) const;
1920 //! shifts the iterator forward by the specified number of elements
1921 MatIterator_& operator += (ptrdiff_t ofs);
1922 //! shifts the iterator backward by the specified number of elements
1923 MatIterator_& operator -= (ptrdiff_t ofs);
1924 //! decrements the iterator
1925 MatIterator_& operator --();
1926 //! decrements the iterator
1927 MatIterator_ operator --(int);
1928 //! increments the iterator
1929 MatIterator_& operator ++();
1930 //! increments the iterator
1931 MatIterator_ operator ++(int);
1936 /////////////////////////////// SparseMatConstIterator ///////////////////////////////
1939 Read-Only Sparse Matrix Iterator.
1940 Here is how to use the iterator to compute the sum of floating-point sparse matrix elements:
1943 SparseMatConstIterator it = m.begin(), it_end = m.end();
1945 CV_Assert( m.type() == CV_32F );
1946 for( ; it != it_end; ++it )
1947 s += it.value<float>();
1950 class CV_EXPORTS SparseMatConstIterator
1953 //! the default constructor
1954 SparseMatConstIterator();
1955 //! the full constructor setting the iterator to the first sparse matrix element
1956 SparseMatConstIterator(const SparseMat* _m);
1957 //! the copy constructor
1958 SparseMatConstIterator(const SparseMatConstIterator& it);
1960 //! the assignment operator
1961 SparseMatConstIterator& operator = (const SparseMatConstIterator& it);
1963 //! template method returning the current matrix element
1964 template<typename _Tp> const _Tp& value() const;
1965 //! returns the current node of the sparse matrix. it.node->idx is the current element index
1966 const SparseMat::Node* node() const;
1968 //! moves iterator to the previous element
1969 SparseMatConstIterator& operator --();
1970 //! moves iterator to the previous element
1971 SparseMatConstIterator operator --(int);
1972 //! moves iterator to the next element
1973 SparseMatConstIterator& operator ++();
1974 //! moves iterator to the next element
1975 SparseMatConstIterator operator ++(int);
1977 //! moves iterator to the element after the last element
1987 ////////////////////////////////// SparseMatIterator /////////////////////////////////
1990 Read-write Sparse Matrix Iterator
1992 The class is similar to cv::SparseMatConstIterator,
1993 but can be used for in-place modification of the matrix elements.
1995 class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator
1998 //! the default constructor
1999 SparseMatIterator();
2000 //! the full constructor setting the iterator to the first sparse matrix element
2001 SparseMatIterator(SparseMat* _m);
2002 //! the full constructor setting the iterator to the specified sparse matrix element
2003 SparseMatIterator(SparseMat* _m, const int* idx);
2004 //! the copy constructor
2005 SparseMatIterator(const SparseMatIterator& it);
2007 //! the assignment operator
2008 SparseMatIterator& operator = (const SparseMatIterator& it);
2009 //! returns read-write reference to the current sparse matrix element
2010 template<typename _Tp> _Tp& value() const;
2011 //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!)
2012 SparseMat::Node* node() const;
2014 //! moves iterator to the next element
2015 SparseMatIterator& operator ++();
2016 //! moves iterator to the next element
2017 SparseMatIterator operator ++(int);
2022 /////////////////////////////// SparseMatConstIterator_ //////////////////////////////
2025 Template Read-Only Sparse Matrix Iterator Class.
2027 This is the derived from SparseMatConstIterator class that
2028 introduces more convenient operator *() for accessing the current element.
2030 template<typename _Tp> class SparseMatConstIterator_ : public SparseMatConstIterator
2034 #ifndef OPENCV_NOSTL
2035 typedef std::forward_iterator_tag iterator_category;
2038 //! the default constructor
2039 SparseMatConstIterator_();
2040 //! the full constructor setting the iterator to the first sparse matrix element
2041 SparseMatConstIterator_(const SparseMat_<_Tp>* _m);
2042 SparseMatConstIterator_(const SparseMat* _m);
2043 //! the copy constructor
2044 SparseMatConstIterator_(const SparseMatConstIterator_& it);
2046 //! the assignment operator
2047 SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it);
2048 //! the element access operator
2049 const _Tp& operator *() const;
2051 //! moves iterator to the next element
2052 SparseMatConstIterator_& operator ++();
2053 //! moves iterator to the next element
2054 SparseMatConstIterator_ operator ++(int);
2059 ///////////////////////////////// SparseMatIterator_ /////////////////////////////////
2062 Template Read-Write Sparse Matrix Iterator Class.
2064 This is the derived from cv::SparseMatConstIterator_ class that
2065 introduces more convenient operator *() for accessing the current element.
2067 template<typename _Tp> class SparseMatIterator_ : public SparseMatConstIterator_<_Tp>
2071 #ifndef OPENCV_NOSTL
2072 typedef std::forward_iterator_tag iterator_category;
2075 //! the default constructor
2076 SparseMatIterator_();
2077 //! the full constructor setting the iterator to the first sparse matrix element
2078 SparseMatIterator_(SparseMat_<_Tp>* _m);
2079 SparseMatIterator_(SparseMat* _m);
2080 //! the copy constructor
2081 SparseMatIterator_(const SparseMatIterator_& it);
2083 //! the assignment operator
2084 SparseMatIterator_& operator = (const SparseMatIterator_& it);
2085 //! returns the reference to the current element
2086 _Tp& operator *() const;
2088 //! moves the iterator to the next element
2089 SparseMatIterator_& operator ++();
2090 //! moves the iterator to the next element
2091 SparseMatIterator_ operator ++(int);
2096 /////////////////////////////////// NAryMatIterator //////////////////////////////////
2099 n-Dimensional Dense Matrix Iterator Class.
2101 The class cv::NAryMatIterator is used for iterating over one or more n-dimensional dense arrays (cv::Mat's).
2103 The iterator is completely different from cv::Mat_ and cv::SparseMat_ iterators.
2104 It iterates through the slices (or planes), not the elements, where "slice" is a continuous part of the arrays.
2106 Here is the example on how the iterator can be used to normalize 3D histogram:
2109 void normalizeColorHist(Mat& hist)
2112 // intialize iterator (the style is different from STL).
2113 // after initialization the iterator will contain
2114 // the number of slices or planes
2115 // the iterator will go through
2116 Mat* arrays[] = { &hist, 0 };
2118 NAryMatIterator it(arrays, planes);
2120 // iterate through the matrix. on each iteration
2121 // it.planes[i] (of type Mat) will be set to the current plane of
2122 // i-th n-dim matrix passed to the iterator constructor.
2123 for(int p = 0; p < it.nplanes; p++, ++it)
2124 s += sum(it.planes[0])[0];
2125 it = NAryMatIterator(hist);
2127 for(int p = 0; p < it.nplanes; p++, ++it)
2130 // this is a shorter implementation of the above
2131 // using built-in operations on Mat
2132 double s = sum(hist)[0];
2133 hist.convertTo(hist, hist.type(), 1./s, 0);
2135 // and this is even shorter one
2136 // (assuming that the histogram elements are non-negative)
2137 normalize(hist, hist, 1, 0, NORM_L1);
2142 You can iterate through several matrices simultaneously as long as they have the same geometry
2143 (dimensionality and all the dimension sizes are the same), which is useful for binary
2144 and n-ary operations on such matrices. Just pass those matrices to cv::MatNDIterator.
2145 Then, during the iteration it.planes[0], it.planes[1], ... will
2146 be the slices of the corresponding matrices
2148 class CV_EXPORTS NAryMatIterator
2151 //! the default constructor
2153 //! the full constructor taking arbitrary number of n-dim matrices
2154 NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1);
2155 //! the full constructor taking arbitrary number of n-dim matrices
2156 NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1);
2157 //! the separate iterator initialization method
2158 void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1);
2160 //! proceeds to the next plane of every iterated matrix
2161 NAryMatIterator& operator ++();
2162 //! proceeds to the next plane of every iterated matrix (postfix increment operator)
2163 NAryMatIterator operator ++(int);
2165 //! the iterated arrays
2167 //! the current planes
2171 //! the number of arrays
2173 //! the number of hyper-planes that the iterator steps through
2175 //! the size of each segment (in elements)
2184 ///////////////////////////////// Matrix Expressions /////////////////////////////////
2186 class CV_EXPORTS MatOp
2192 virtual bool elementWise(const MatExpr& expr) const;
2193 virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0;
2194 virtual void roi(const MatExpr& expr, const Range& rowRange,
2195 const Range& colRange, MatExpr& res) const;
2196 virtual void diag(const MatExpr& expr, int d, MatExpr& res) const;
2197 virtual void augAssignAdd(const MatExpr& expr, Mat& m) const;
2198 virtual void augAssignSubtract(const MatExpr& expr, Mat& m) const;
2199 virtual void augAssignMultiply(const MatExpr& expr, Mat& m) const;
2200 virtual void augAssignDivide(const MatExpr& expr, Mat& m) const;
2201 virtual void augAssignAnd(const MatExpr& expr, Mat& m) const;
2202 virtual void augAssignOr(const MatExpr& expr, Mat& m) const;
2203 virtual void augAssignXor(const MatExpr& expr, Mat& m) const;
2205 virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
2206 virtual void add(const MatExpr& expr1, const Scalar& s, MatExpr& res) const;
2208 virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
2209 virtual void subtract(const Scalar& s, const MatExpr& expr, MatExpr& res) const;
2211 virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
2212 virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const;
2214 virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
2215 virtual void divide(double s, const MatExpr& expr, MatExpr& res) const;
2217 virtual void abs(const MatExpr& expr, MatExpr& res) const;
2219 virtual void transpose(const MatExpr& expr, MatExpr& res) const;
2220 virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
2221 virtual void invert(const MatExpr& expr, int method, MatExpr& res) const;
2223 virtual Size size(const MatExpr& expr) const;
2224 virtual int type(const MatExpr& expr) const;
2228 class CV_EXPORTS MatExpr
2232 explicit MatExpr(const Mat& m);
2234 MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(),
2235 const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar& _s = Scalar());
2237 operator Mat() const;
2238 template<typename _Tp> operator Mat_<_Tp>() const;
2243 MatExpr row(int y) const;
2244 MatExpr col(int x) const;
2245 MatExpr diag(int d = 0) const;
2246 MatExpr operator()( const Range& rowRange, const Range& colRange ) const;
2247 MatExpr operator()( const Rect& roi ) const;
2250 MatExpr inv(int method = DECOMP_LU) const;
2251 MatExpr mul(const MatExpr& e, double scale=1) const;
2252 MatExpr mul(const Mat& m, double scale=1) const;
2254 Mat cross(const Mat& m) const;
2255 double dot(const Mat& m) const;
2266 CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b);
2267 CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s);
2268 CV_EXPORTS MatExpr operator + (const Scalar& s, const Mat& a);
2269 CV_EXPORTS MatExpr operator + (const MatExpr& e, const Mat& m);
2270 CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e);
2271 CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar& s);
2272 CV_EXPORTS MatExpr operator + (const Scalar& s, const MatExpr& e);
2273 CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2);
2275 CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b);
2276 CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar& s);
2277 CV_EXPORTS MatExpr operator - (const Scalar& s, const Mat& a);
2278 CV_EXPORTS MatExpr operator - (const MatExpr& e, const Mat& m);
2279 CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e);
2280 CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar& s);
2281 CV_EXPORTS MatExpr operator - (const Scalar& s, const MatExpr& e);
2282 CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2);
2284 CV_EXPORTS MatExpr operator - (const Mat& m);
2285 CV_EXPORTS MatExpr operator - (const MatExpr& e);
2287 CV_EXPORTS MatExpr operator * (const Mat& a, const Mat& b);
2288 CV_EXPORTS MatExpr operator * (const Mat& a, double s);
2289 CV_EXPORTS MatExpr operator * (double s, const Mat& a);
2290 CV_EXPORTS MatExpr operator * (const MatExpr& e, const Mat& m);
2291 CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e);
2292 CV_EXPORTS MatExpr operator * (const MatExpr& e, double s);
2293 CV_EXPORTS MatExpr operator * (double s, const MatExpr& e);
2294 CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2);
2296 CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b);
2297 CV_EXPORTS MatExpr operator / (const Mat& a, double s);
2298 CV_EXPORTS MatExpr operator / (double s, const Mat& a);
2299 CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m);
2300 CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e);
2301 CV_EXPORTS MatExpr operator / (const MatExpr& e, double s);
2302 CV_EXPORTS MatExpr operator / (double s, const MatExpr& e);
2303 CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2);
2305 CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b);
2306 CV_EXPORTS MatExpr operator < (const Mat& a, double s);
2307 CV_EXPORTS MatExpr operator < (double s, const Mat& a);
2309 CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b);
2310 CV_EXPORTS MatExpr operator <= (const Mat& a, double s);
2311 CV_EXPORTS MatExpr operator <= (double s, const Mat& a);
2313 CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b);
2314 CV_EXPORTS MatExpr operator == (const Mat& a, double s);
2315 CV_EXPORTS MatExpr operator == (double s, const Mat& a);
2317 CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b);
2318 CV_EXPORTS MatExpr operator != (const Mat& a, double s);
2319 CV_EXPORTS MatExpr operator != (double s, const Mat& a);
2321 CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b);
2322 CV_EXPORTS MatExpr operator >= (const Mat& a, double s);
2323 CV_EXPORTS MatExpr operator >= (double s, const Mat& a);
2325 CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b);
2326 CV_EXPORTS MatExpr operator > (const Mat& a, double s);
2327 CV_EXPORTS MatExpr operator > (double s, const Mat& a);
2329 CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b);
2330 CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s);
2331 CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a);
2333 CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b);
2334 CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar& s);
2335 CV_EXPORTS MatExpr operator | (const Scalar& s, const Mat& a);
2337 CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b);
2338 CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s);
2339 CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a);
2341 CV_EXPORTS MatExpr operator ~(const Mat& m);
2343 CV_EXPORTS MatExpr min(const Mat& a, const Mat& b);
2344 CV_EXPORTS MatExpr min(const Mat& a, double s);
2345 CV_EXPORTS MatExpr min(double s, const Mat& a);
2347 CV_EXPORTS MatExpr max(const Mat& a, const Mat& b);
2348 CV_EXPORTS MatExpr max(const Mat& a, double s);
2349 CV_EXPORTS MatExpr max(double s, const Mat& a);
2351 CV_EXPORTS MatExpr abs(const Mat& m);
2352 CV_EXPORTS MatExpr abs(const MatExpr& e);
2356 #include "opencv2/core/mat.inl.hpp"
2358 #endif // __OPENCV_CORE_MAT_HPP__