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 UMAT =10 << KIND_SHIFT,
89 STD_VECTOR_UMAT =11 << KIND_SHIFT
93 _InputArray(int _flags, void* _obj);
94 _InputArray(const Mat& m);
95 _InputArray(const MatExpr& expr);
96 _InputArray(const std::vector<Mat>& vec);
97 template<typename _Tp> _InputArray(const Mat_<_Tp>& m);
98 template<typename _Tp> _InputArray(const std::vector<_Tp>& vec);
99 template<typename _Tp> _InputArray(const std::vector<std::vector<_Tp> >& vec);
100 template<typename _Tp> _InputArray(const std::vector<Mat_<_Tp> >& vec);
101 template<typename _Tp> _InputArray(const _Tp* vec, int n);
102 template<typename _Tp, int m, int n> _InputArray(const Matx<_Tp, m, n>& matx);
103 _InputArray(const double& val);
104 _InputArray(const cuda::GpuMat& d_mat);
105 _InputArray(const ogl::Buffer& buf);
106 _InputArray(const cuda::CudaMem& cuda_mem);
107 template<typename _Tp> _InputArray(const cudev::GpuMat_<_Tp>& m);
108 _InputArray(const UMat& um);
109 _InputArray(const std::vector<UMat>& umv);
111 virtual Mat getMat(int idx=-1) const;
112 virtual UMat getUMat(int idx=-1) const;
113 virtual void getMatVector(std::vector<Mat>& mv) const;
114 virtual void getUMatVector(std::vector<UMat>& umv) const;
115 virtual cuda::GpuMat getGpuMat() const;
116 virtual ogl::Buffer getOGlBuffer() const;
117 void* getObj() const;
119 virtual int kind() const;
120 virtual int dims(int i=-1) const;
121 virtual Size size(int i=-1) const;
122 virtual int sizend(int* sz, int i=-1) const;
123 virtual bool sameSize(const _InputArray& arr) const;
124 virtual size_t total(int i=-1) const;
125 virtual int type(int i=-1) const;
126 virtual int depth(int i=-1) const;
127 virtual int channels(int i=-1) const;
128 virtual bool isContinuous(int i=-1) const;
129 virtual bool isSubmatrix(int i=-1) const;
130 virtual bool empty() const;
131 virtual void copyTo(const _OutputArray& arr) const;
132 virtual size_t offset(int i=-1) const;
133 virtual size_t step(int i=-1) const;
136 bool isMatVector() const;
137 bool isUMatVector() const;
140 virtual ~_InputArray();
147 void init(int _flags, const void* _obj);
148 void init(int _flags, const void* _obj, Size _sz);
153 Proxy datatype for passing Mat's and vector<>'s as input parameters
155 class CV_EXPORTS _OutputArray : public _InputArray
160 DEPTH_MASK_8U = 1 << CV_8U,
161 DEPTH_MASK_8S = 1 << CV_8S,
162 DEPTH_MASK_16U = 1 << CV_16U,
163 DEPTH_MASK_16S = 1 << CV_16S,
164 DEPTH_MASK_32S = 1 << CV_32S,
165 DEPTH_MASK_32F = 1 << CV_32F,
166 DEPTH_MASK_64F = 1 << CV_64F,
167 DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1,
168 DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S,
169 DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F
173 _OutputArray(int _flags, void* _obj);
174 _OutputArray(Mat& m);
175 _OutputArray(std::vector<Mat>& vec);
176 _OutputArray(cuda::GpuMat& d_mat);
177 _OutputArray(ogl::Buffer& buf);
178 _OutputArray(cuda::CudaMem& cuda_mem);
179 template<typename _Tp> _OutputArray(cudev::GpuMat_<_Tp>& m);
180 template<typename _Tp> _OutputArray(std::vector<_Tp>& vec);
181 template<typename _Tp> _OutputArray(std::vector<std::vector<_Tp> >& vec);
182 template<typename _Tp> _OutputArray(std::vector<Mat_<_Tp> >& vec);
183 template<typename _Tp> _OutputArray(Mat_<_Tp>& m);
184 template<typename _Tp> _OutputArray(_Tp* vec, int n);
185 template<typename _Tp, int m, int n> _OutputArray(Matx<_Tp, m, n>& matx);
186 _OutputArray(UMat& m);
187 _OutputArray(std::vector<UMat>& vec);
189 _OutputArray(const Mat& m);
190 _OutputArray(const std::vector<Mat>& vec);
191 _OutputArray(const cuda::GpuMat& d_mat);
192 _OutputArray(const ogl::Buffer& buf);
193 _OutputArray(const cuda::CudaMem& cuda_mem);
194 template<typename _Tp> _OutputArray(const cudev::GpuMat_<_Tp>& m);
195 template<typename _Tp> _OutputArray(const std::vector<_Tp>& vec);
196 template<typename _Tp> _OutputArray(const std::vector<std::vector<_Tp> >& vec);
197 template<typename _Tp> _OutputArray(const std::vector<Mat_<_Tp> >& vec);
198 template<typename _Tp> _OutputArray(const Mat_<_Tp>& m);
199 template<typename _Tp> _OutputArray(const _Tp* vec, int n);
200 template<typename _Tp, int m, int n> _OutputArray(const Matx<_Tp, m, n>& matx);
201 _OutputArray(const UMat& m);
202 _OutputArray(const std::vector<UMat>& vec);
204 virtual bool fixedSize() const;
205 virtual bool fixedType() const;
206 virtual bool needed() const;
207 virtual Mat& getMatRef(int i=-1) const;
208 virtual UMat& getUMatRef(int i=-1) const;
209 virtual cuda::GpuMat& getGpuMatRef() const;
210 virtual ogl::Buffer& getOGlBufferRef() const;
211 virtual cuda::CudaMem& getCudaMemRef() const;
212 virtual void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
213 virtual void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
214 virtual void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
215 virtual void createSameSize(const _InputArray& arr, int mtype) const;
216 virtual void release() const;
217 virtual void clear() const;
218 virtual void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const;
222 class CV_EXPORTS _InputOutputArray : public _OutputArray
226 _InputOutputArray(int _flags, void* _obj);
227 _InputOutputArray(Mat& m);
228 _InputOutputArray(std::vector<Mat>& vec);
229 _InputOutputArray(cuda::GpuMat& d_mat);
230 _InputOutputArray(ogl::Buffer& buf);
231 _InputOutputArray(cuda::CudaMem& cuda_mem);
232 template<typename _Tp> _InputOutputArray(cudev::GpuMat_<_Tp>& m);
233 template<typename _Tp> _InputOutputArray(std::vector<_Tp>& vec);
234 template<typename _Tp> _InputOutputArray(std::vector<std::vector<_Tp> >& vec);
235 template<typename _Tp> _InputOutputArray(std::vector<Mat_<_Tp> >& vec);
236 template<typename _Tp> _InputOutputArray(Mat_<_Tp>& m);
237 template<typename _Tp> _InputOutputArray(_Tp* vec, int n);
238 template<typename _Tp, int m, int n> _InputOutputArray(Matx<_Tp, m, n>& matx);
239 _InputOutputArray(UMat& m);
240 _InputOutputArray(std::vector<UMat>& vec);
242 _InputOutputArray(const Mat& m);
243 _InputOutputArray(const std::vector<Mat>& vec);
244 _InputOutputArray(const cuda::GpuMat& d_mat);
245 _InputOutputArray(const ogl::Buffer& buf);
246 _InputOutputArray(const cuda::CudaMem& cuda_mem);
247 template<typename _Tp> _InputOutputArray(const cudev::GpuMat_<_Tp>& m);
248 template<typename _Tp> _InputOutputArray(const std::vector<_Tp>& vec);
249 template<typename _Tp> _InputOutputArray(const std::vector<std::vector<_Tp> >& vec);
250 template<typename _Tp> _InputOutputArray(const std::vector<Mat_<_Tp> >& vec);
251 template<typename _Tp> _InputOutputArray(const Mat_<_Tp>& m);
252 template<typename _Tp> _InputOutputArray(const _Tp* vec, int n);
253 template<typename _Tp, int m, int n> _InputOutputArray(const Matx<_Tp, m, n>& matx);
254 _InputOutputArray(const UMat& m);
255 _InputOutputArray(const std::vector<UMat>& vec);
258 typedef const _InputArray& InputArray;
259 typedef InputArray InputArrayOfArrays;
260 typedef const _OutputArray& OutputArray;
261 typedef OutputArray OutputArrayOfArrays;
262 typedef const _InputOutputArray& InputOutputArray;
263 typedef InputOutputArray InputOutputArrayOfArrays;
265 CV_EXPORTS InputOutputArray noArray();
267 /////////////////////////////////// MatAllocator //////////////////////////////////////
269 //! Usage flags for allocator
274 // default allocation policy is platform and usage specific
275 USAGE_ALLOCATE_HOST_MEMORY = 1 << 0,
276 USAGE_ALLOCATE_DEVICE_MEMORY = 1 << 1,
278 __UMAT_USAGE_FLAGS_32BIT = 0x7fffffff // Binary compatibility hint
281 struct CV_EXPORTS UMatData;
284 Custom array allocator
287 class CV_EXPORTS MatAllocator
291 virtual ~MatAllocator() {}
293 // let's comment it off for now to detect and fix all the uses of allocator
294 //virtual void allocate(int dims, const int* sizes, int type, int*& refcount,
295 // uchar*& datastart, uchar*& data, size_t* step) = 0;
296 //virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0;
297 virtual UMatData* allocate(int dims, const int* sizes, int type,
298 void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const = 0;
299 virtual bool allocate(UMatData* data, int accessflags, UMatUsageFlags usageFlags) const = 0;
300 virtual void deallocate(UMatData* data) const = 0;
301 virtual void map(UMatData* data, int accessflags) const;
302 virtual void unmap(UMatData* data) const;
303 virtual void download(UMatData* data, void* dst, int dims, const size_t sz[],
304 const size_t srcofs[], const size_t srcstep[],
305 const size_t dststep[]) const;
306 virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[],
307 const size_t dstofs[], const size_t dststep[],
308 const size_t srcstep[]) const;
309 virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[],
310 const size_t srcofs[], const size_t srcstep[],
311 const size_t dstofs[], const size_t dststep[], bool sync) const;
313 // default implementation returns DummyBufferPoolController
314 virtual BufferPoolController* getBufferPoolController() const;
318 //////////////////////////////// MatCommaInitializer //////////////////////////////////
321 Comma-separated Matrix Initializer
323 The class instances are usually not created explicitly.
324 Instead, they are created on "matrix << firstValue" operator.
326 The sample below initializes 2x2 rotation matrix:
329 double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180);
330 Mat R = (Mat_<double>(2,2) << a, -b, b, a);
333 template<typename _Tp> class MatCommaInitializer_
336 //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat
337 MatCommaInitializer_(Mat_<_Tp>* _m);
338 //! the operator that takes the next value and put it to the matrix
339 template<typename T2> MatCommaInitializer_<_Tp>& operator , (T2 v);
340 //! another form of conversion operator
341 operator Mat_<_Tp>() const;
343 MatIterator_<_Tp> it;
347 /////////////////////////////////////// Mat ///////////////////////////////////////////
349 // note that umatdata might be allocated together
350 // with the matrix data, not as a separate object.
351 // therefore, it does not have constructor or destructor;
352 // it should be explicitly initialized using init().
353 struct CV_EXPORTS UMatData
355 enum { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2,
356 DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24,
358 UMatData(const MatAllocator* allocator);
361 // provide atomic access to the structure
365 bool hostCopyObsolete() const;
366 bool deviceCopyObsolete() const;
367 bool copyOnMap() const;
368 bool tempUMat() const;
369 bool tempCopiedUMat() const;
370 void markHostCopyObsolete(bool flag);
371 void markDeviceCopyObsolete(bool flag);
373 const MatAllocator* prevAllocator;
374 const MatAllocator* currAllocator;
379 size_t size, capacity;
388 struct CV_EXPORTS UMatDataAutoLock
390 UMatDataAutoLock(UMatData* u);
396 struct CV_EXPORTS MatSize
399 Size operator()() const;
400 const int& operator[](int i) const;
401 int& operator[](int i);
402 operator const int*() const;
403 bool operator == (const MatSize& sz) const;
404 bool operator != (const MatSize& sz) const;
409 struct CV_EXPORTS MatStep
413 const size_t& operator[](int i) const;
414 size_t& operator[](int i);
415 operator size_t() const;
416 MatStep& operator = (size_t s);
421 MatStep& operator = (const MatStep&);
425 The n-dimensional matrix class.
427 The class represents an n-dimensional dense numerical array that can act as
428 a matrix, image, optical flow map, 3-focal tensor etc.
429 It is very similar to CvMat and CvMatND types from earlier versions of OpenCV,
430 and similarly to those types, the matrix can be multi-channel. It also fully supports ROI mechanism.
432 There are many different ways to create cv::Mat object. Here are the some popular ones:
434 <li> using cv::Mat::create(nrows, ncols, type) method or
435 the similar constructor cv::Mat::Mat(nrows, ncols, type[, fill_value]) constructor.
436 A new matrix of the specified size and specifed type will be allocated.
437 "type" has the same meaning as in cvCreateMat function,
438 e.g. CV_8UC1 means 8-bit single-channel matrix, CV_32FC2 means 2-channel (i.e. complex)
439 floating-point matrix etc:
442 // make 7x7 complex matrix filled with 1+3j.
443 cv::Mat M(7,7,CV_32FC2,Scalar(1,3));
444 // and now turn M to 100x60 15-channel 8-bit matrix.
445 // The old content will be deallocated
446 M.create(100,60,CV_8UC(15));
449 As noted in the introduction of this chapter, Mat::create()
450 will only allocate a new matrix when the current matrix dimensionality
451 or type are different from the specified.
453 <li> by using a copy constructor or assignment operator, where on the right side it can
454 be a matrix or expression, see below. Again, as noted in the introduction,
455 matrix assignment is O(1) operation because it only copies the header
456 and increases the reference counter. cv::Mat::clone() method can be used to get a full
457 (a.k.a. deep) copy of the matrix when you need it.
459 <li> by constructing a header for a part of another matrix. It can be a single row, single column,
460 several rows, several columns, rectangular region in the matrix (called a minor in algebra) or
461 a diagonal. Such operations are also O(1), because the new header will reference the same data.
462 You can actually modify a part of the matrix using this feature, e.g.
465 // add 5-th row, multiplied by 3 to the 3rd row
466 M.row(3) = M.row(3) + M.row(5)*3;
468 // now copy 7-th column to the 1-st column
469 // M.col(1) = M.col(7); // this will not work
473 // create new 320x240 image
474 cv::Mat img(Size(320,240),CV_8UC3);
476 cv::Mat roi(img, Rect(10,10,100,100));
477 // fill the ROI with (0,255,0) (which is green in RGB space);
478 // the original 320x240 image will be modified
479 roi = Scalar(0,255,0);
482 Thanks to the additional cv::Mat::datastart and cv::Mat::dataend members, it is possible to
483 compute the relative sub-matrix position in the main "container" matrix using cv::Mat::locateROI():
486 Mat A = Mat::eye(10, 10, CV_32S);
487 // extracts A columns, 1 (inclusive) to 3 (exclusive).
488 Mat B = A(Range::all(), Range(1, 3));
489 // extracts B rows, 5 (inclusive) to 9 (exclusive).
490 // that is, C ~ A(Range(5, 9), Range(1, 3))
491 Mat C = B(Range(5, 9), Range::all());
492 Size size; Point ofs;
493 C.locateROI(size, ofs);
494 // size will be (width=10,height=10) and the ofs will be (x=1, y=5)
497 As in the case of whole matrices, if you need a deep copy, use cv::Mat::clone() method
498 of the extracted sub-matrices.
500 <li> by making a header for user-allocated-data. It can be useful for
502 <li> processing "foreign" data using OpenCV (e.g. when you implement
503 a DirectShow filter or a processing module for gstreamer etc.), e.g.
506 void process_video_frame(const unsigned char* pixels,
507 int width, int height, int step)
509 cv::Mat img(height, width, CV_8UC3, pixels, step);
510 cv::GaussianBlur(img, img, cv::Size(7,7), 1.5, 1.5);
514 <li> for quick initialization of small matrices and/or super-fast element access
517 double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
518 cv::Mat M = cv::Mat(3, 3, CV_64F, m).inv();
522 partial yet very common cases of this "user-allocated data" case are conversions
523 from CvMat and IplImage to cv::Mat. For this purpose there are special constructors
524 taking pointers to CvMat or IplImage and the optional
525 flag indicating whether to copy the data or not.
527 Backward conversion from cv::Mat to CvMat or IplImage is provided via cast operators
528 cv::Mat::operator CvMat() an cv::Mat::operator IplImage().
529 The operators do not copy the data.
533 IplImage* img = cvLoadImage("greatwave.jpg", 1);
534 Mat mtx(img); // convert IplImage* -> cv::Mat
535 CvMat oldmat = mtx; // convert cv::Mat -> CvMat
536 CV_Assert(oldmat.cols == img->width && oldmat.rows == img->height &&
537 oldmat.data.ptr == (uchar*)img->imageData && oldmat.step == img->widthStep);
540 <li> by using MATLAB-style matrix initializers, cv::Mat::zeros(), cv::Mat::ones(), cv::Mat::eye(), e.g.:
543 // create a double-precision identity martix and add it to M.
544 M += Mat::eye(M.rows, M.cols, CV_64F);
547 <li> by using comma-separated initializer:
550 // create 3x3 double-precision identity matrix
551 Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
554 here we first call constructor of cv::Mat_ class (that we describe further) with the proper matrix,
555 and then we just put "<<" operator followed by comma-separated values that can be constants,
556 variables, expressions etc. Also, note the extra parentheses that are needed to avoid compiler errors.
560 Once matrix is created, it will be automatically managed by using reference-counting mechanism
561 (unless the matrix header is built on top of user-allocated data,
562 in which case you should handle the data by yourself).
563 The matrix data will be deallocated when no one points to it;
564 if you want to release the data pointed by a matrix header before the matrix destructor is called,
565 use cv::Mat::release().
567 The next important thing to learn about the matrix class is element access. Here is how the matrix is stored.
568 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,
569 cv::Mat::rows contains the number of matrix rows and cv::Mat::cols - the number of matrix columns. There is yet another member,
570 cv::Mat::step that is used to actually compute address of a matrix element. cv::Mat::step is needed because the matrix can be
571 a part of another matrix or because there can some padding space in the end of each row for a proper alignment.
575 Given these parameters, address of the matrix element M_{ij} is computed as following:
577 addr(M_{ij})=M.data + M.step*i + j*M.elemSize()
579 if you know the matrix element type, e.g. it is float, then you can use cv::Mat::at() method:
581 addr(M_{ij})=&M.at<float>(i,j)
583 (where & is used to convert the reference returned by cv::Mat::at() to a pointer).
584 if you need to process a whole row of matrix, the most efficient way is to get
585 the pointer to the row first, and then just use plain C operator []:
588 // compute sum of positive matrix elements
589 // (assuming that M is double-precision matrix)
591 for(int i = 0; i < M.rows; i++)
593 const double* Mi = M.ptr<double>(i);
594 for(int j = 0; j < M.cols; j++)
595 sum += std::max(Mi[j], 0.);
599 Some operations, like the above one, do not actually depend on the matrix shape,
600 they just process elements of a matrix one by one (or elements from multiple matrices
601 that are sitting in the same place, e.g. matrix addition). Such operations are called
602 element-wise and it makes sense to check whether all the input/output matrices are continuous,
603 i.e. have no gaps in the end of each row, and if yes, process them as a single long row:
606 // compute sum of positive matrix elements, optimized variant
608 int cols = M.cols, rows = M.rows;
614 for(int i = 0; i < rows; i++)
616 const double* Mi = M.ptr<double>(i);
617 for(int j = 0; j < cols; j++)
618 sum += std::max(Mi[j], 0.);
621 in the case of continuous matrix the outer loop body will be executed just once,
622 so the overhead will be smaller, which will be especially noticeable in the case of small matrices.
624 Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:
626 // compute sum of positive matrix elements, iterator-based variant
628 MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
629 for(; it != it_end; ++it)
630 sum += std::max(*it, 0.);
633 The matrix iterators are random-access iterators, so they can be passed
634 to any STL algorithm, including std::sort().
639 //! default constructor
641 //! constructs 2D matrix of the specified size and type
642 // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
643 Mat(int rows, int cols, int type);
644 Mat(Size size, int type);
645 //! constucts 2D matrix and fills it with the specified value _s.
646 Mat(int rows, int cols, int type, const Scalar& s);
647 Mat(Size size, int type, const Scalar& s);
649 //! constructs n-dimensional matrix
650 Mat(int ndims, const int* sizes, int type);
651 Mat(int ndims, const int* sizes, int type, const Scalar& s);
655 //! constructor for matrix headers pointing to user-allocated data
656 Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP);
657 Mat(Size size, int type, void* data, size_t step=AUTO_STEP);
658 Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0);
660 //! creates a matrix header for a part of the bigger matrix
661 Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all());
662 Mat(const Mat& m, const Rect& roi);
663 Mat(const Mat& m, const Range* ranges);
664 //! builds matrix from std::vector with or without copying the data
665 template<typename _Tp> explicit Mat(const std::vector<_Tp>& vec, bool copyData=false);
666 //! builds matrix from cv::Vec; the data is copied by default
667 template<typename _Tp, int n> explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true);
668 //! builds matrix from cv::Matx; the data is copied by default
669 template<typename _Tp, int m, int n> explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
670 //! builds matrix from a 2D point
671 template<typename _Tp> explicit Mat(const Point_<_Tp>& pt, bool copyData=true);
672 //! builds matrix from a 3D point
673 template<typename _Tp> explicit Mat(const Point3_<_Tp>& pt, bool copyData=true);
674 //! builds matrix from comma initializer
675 template<typename _Tp> explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer);
677 //! download data from GpuMat
678 explicit Mat(const cuda::GpuMat& m);
680 //! destructor - calls release()
682 //! assignment operators
683 Mat& operator = (const Mat& m);
684 Mat& operator = (const MatExpr& expr);
686 //! retrieve UMat from Mat
687 UMat getUMat(int accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const;
689 //! returns a new matrix header for the specified row
690 Mat row(int y) const;
691 //! returns a new matrix header for the specified column
692 Mat col(int x) const;
693 //! ... for the specified row span
694 Mat rowRange(int startrow, int endrow) const;
695 Mat rowRange(const Range& r) const;
696 //! ... for the specified column span
697 Mat colRange(int startcol, int endcol) const;
698 Mat colRange(const Range& r) const;
699 //! ... for the specified diagonal
700 // (d=0 - the main diagonal,
701 // >0 - a diagonal from the lower half,
702 // <0 - a diagonal from the upper half)
703 Mat diag(int d=0) const;
704 //! constructs a square diagonal matrix which main diagonal is vector "d"
705 static Mat diag(const Mat& d);
707 //! returns deep copy of the matrix, i.e. the data is copied
709 //! copies the matrix content to "m".
710 // It calls m.create(this->size(), this->type()).
711 void copyTo( OutputArray m ) const;
712 //! copies those matrix elements to "m" that are marked with non-zero mask elements.
713 void copyTo( OutputArray m, InputArray mask ) const;
714 //! converts matrix to another datatype with optional scalng. See cvConvertScale.
715 void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
717 void assignTo( Mat& m, int type=-1 ) const;
719 //! sets every matrix element to s
720 Mat& operator = (const Scalar& s);
721 //! sets some of the matrix elements to s, according to the mask
722 Mat& setTo(InputArray value, InputArray mask=noArray());
723 //! creates alternative matrix header for the same data, with different
724 // number of channels and/or different number of rows. see cvReshape.
725 Mat reshape(int cn, int rows=0) const;
726 Mat reshape(int cn, int newndims, const int* newsz) const;
728 //! matrix transposition by means of matrix expressions
730 //! matrix inversion by means of matrix expressions
731 MatExpr inv(int method=DECOMP_LU) const;
732 //! per-element matrix multiplication by means of matrix expressions
733 MatExpr mul(InputArray m, double scale=1) const;
735 //! computes cross-product of 2 3D vectors
736 Mat cross(InputArray m) const;
737 //! computes dot-product
738 double dot(InputArray m) const;
740 //! Matlab-style matrix initialization
741 static MatExpr zeros(int rows, int cols, int type);
742 static MatExpr zeros(Size size, int type);
743 static MatExpr zeros(int ndims, const int* sz, int type);
744 static MatExpr ones(int rows, int cols, int type);
745 static MatExpr ones(Size size, int type);
746 static MatExpr ones(int ndims, const int* sz, int type);
747 static MatExpr eye(int rows, int cols, int type);
748 static MatExpr eye(Size size, int type);
750 //! allocates new matrix data unless the matrix already has specified size and type.
751 // previous data is unreferenced if needed.
752 void create(int rows, int cols, int type);
753 void create(Size size, int type);
754 void create(int ndims, const int* sizes, int type);
756 //! increases the reference counter; use with care to avoid memleaks
758 //! decreases reference counter;
759 // deallocates the data when reference counter reaches 0.
762 //! deallocates the matrix data
764 //! internal use function; properly re-allocates _size, _step arrays
765 void copySize(const Mat& m);
767 //! reserves enough space to fit sz hyper-planes
768 void reserve(size_t sz);
769 //! resizes matrix to the specified number of hyper-planes
770 void resize(size_t sz);
771 //! resizes matrix to the specified number of hyper-planes; initializes the newly added elements
772 void resize(size_t sz, const Scalar& s);
773 //! internal function
774 void push_back_(const void* elem);
775 //! adds element to the end of 1d matrix (or possibly multiple elements when _Tp=Mat)
776 template<typename _Tp> void push_back(const _Tp& elem);
777 template<typename _Tp> void push_back(const Mat_<_Tp>& elem);
778 void push_back(const Mat& m);
779 //! removes several hyper-planes from bottom of the matrix
780 void pop_back(size_t nelems=1);
782 //! locates matrix header within a parent matrix. See below
783 void locateROI( Size& wholeSize, Point& ofs ) const;
784 //! moves/resizes the current matrix ROI inside the parent matrix.
785 Mat& adjustROI( int dtop, int dbottom, int dleft, int dright );
786 //! extracts a rectangular sub-matrix
787 // (this is a generalized form of row, rowRange etc.)
788 Mat operator()( Range rowRange, Range colRange ) const;
789 Mat operator()( const Rect& roi ) const;
790 Mat operator()( const Range* ranges ) const;
792 // //! converts header to CvMat; no data is copied
793 // operator CvMat() const;
794 // //! converts header to CvMatND; no data is copied
795 // operator CvMatND() const;
796 // //! converts header to IplImage; no data is copied
797 // operator IplImage() const;
799 template<typename _Tp> operator std::vector<_Tp>() const;
800 template<typename _Tp, int n> operator Vec<_Tp, n>() const;
801 template<typename _Tp, int m, int n> operator Matx<_Tp, m, n>() const;
803 //! returns true iff the matrix data is continuous
804 // (i.e. when there are no gaps between successive rows).
805 // similar to CV_IS_MAT_CONT(cvmat->type)
806 bool isContinuous() const;
808 //! returns true if the matrix is a submatrix of another matrix
809 bool isSubmatrix() const;
811 //! returns element size in bytes,
812 // similar to CV_ELEM_SIZE(cvmat->type)
813 size_t elemSize() const;
814 //! returns the size of element channel in bytes.
815 size_t elemSize1() const;
816 //! returns element type, similar to CV_MAT_TYPE(cvmat->type)
818 //! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
820 //! returns element type, similar to CV_MAT_CN(cvmat->type)
821 int channels() const;
822 //! returns step/elemSize1()
823 size_t step1(int i=0) const;
824 //! returns true if matrix data is NULL
826 //! returns the total number of matrix elements
827 size_t total() const;
829 //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
830 int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
832 //! returns pointer to i0-th submatrix along the dimension #0
833 uchar* ptr(int i0=0);
834 const uchar* ptr(int i0=0) const;
836 //! returns pointer to (i0,i1) submatrix along the dimensions #0 and #1
837 uchar* ptr(int i0, int i1);
838 const uchar* ptr(int i0, int i1) const;
840 //! returns pointer to (i0,i1,i3) submatrix along the dimensions #0, #1, #2
841 uchar* ptr(int i0, int i1, int i2);
842 const uchar* ptr(int i0, int i1, int i2) const;
844 //! returns pointer to the matrix element
845 uchar* ptr(const int* idx);
846 //! returns read-only pointer to the matrix element
847 const uchar* ptr(const int* idx) const;
849 template<int n> uchar* ptr(const Vec<int, n>& idx);
850 template<int n> const uchar* ptr(const Vec<int, n>& idx) const;
852 //! template version of the above method
853 template<typename _Tp> _Tp* ptr(int i0=0);
854 template<typename _Tp> const _Tp* ptr(int i0=0) const;
856 template<typename _Tp> _Tp* ptr(int i0, int i1);
857 template<typename _Tp> const _Tp* ptr(int i0, int i1) const;
859 template<typename _Tp> _Tp* ptr(int i0, int i1, int i2);
860 template<typename _Tp> const _Tp* ptr(int i0, int i1, int i2) const;
862 template<typename _Tp> _Tp* ptr(const int* idx);
863 template<typename _Tp> const _Tp* ptr(const int* idx) const;
865 template<typename _Tp, int n> _Tp* ptr(const Vec<int, n>& idx);
866 template<typename _Tp, int n> const _Tp* ptr(const Vec<int, n>& idx) const;
868 //! the same as above, with the pointer dereferencing
869 template<typename _Tp> _Tp& at(int i0=0);
870 template<typename _Tp> const _Tp& at(int i0=0) const;
872 template<typename _Tp> _Tp& at(int i0, int i1);
873 template<typename _Tp> const _Tp& at(int i0, int i1) const;
875 template<typename _Tp> _Tp& at(int i0, int i1, int i2);
876 template<typename _Tp> const _Tp& at(int i0, int i1, int i2) const;
878 template<typename _Tp> _Tp& at(const int* idx);
879 template<typename _Tp> const _Tp& at(const int* idx) const;
881 template<typename _Tp, int n> _Tp& at(const Vec<int, n>& idx);
882 template<typename _Tp, int n> const _Tp& at(const Vec<int, n>& idx) const;
884 //! special versions for 2D arrays (especially convenient for referencing image pixels)
885 template<typename _Tp> _Tp& at(Point pt);
886 template<typename _Tp> const _Tp& at(Point pt) const;
888 //! template methods for iteration over matrix elements.
889 // the iterators take care of skipping gaps in the end of rows (if any)
890 template<typename _Tp> MatIterator_<_Tp> begin();
891 template<typename _Tp> MatIterator_<_Tp> end();
892 template<typename _Tp> MatConstIterator_<_Tp> begin() const;
893 template<typename _Tp> MatConstIterator_<_Tp> end() const;
895 enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
896 enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
898 /*! includes several bit-fields:
899 - the magic signature
905 //! the matrix dimensionality, >= 2
907 //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
909 //! pointer to the data
912 //! helper fields used in locateROI and adjustROI
918 MatAllocator* allocator;
919 //! and the standard allocator
920 static MatAllocator* getStdAllocator();
922 //! interaction with UMat
932 ///////////////////////////////// Mat_<_Tp> ////////////////////////////////////
935 Template matrix class derived from Mat
937 The class Mat_ is a "thin" template wrapper on top of cv::Mat. It does not have any extra data fields,
938 nor it or cv::Mat have any virtual methods and thus references or pointers to these two classes
939 can be safely converted one to another. But do it with care, for example:
942 // create 100x100 8-bit matrix
943 Mat M(100,100,CV_8U);
944 // this will compile fine. no any data conversion will be done.
945 Mat_<float>& M1 = (Mat_<float>&)M;
946 // the program will likely crash at the statement below
950 While cv::Mat is sufficient in most cases, cv::Mat_ can be more convenient if you use a lot of element
951 access operations and if you know matrix type at compile time.
952 Note that cv::Mat::at<_Tp>(int y, int x) and cv::Mat_<_Tp>::operator ()(int y, int x) do absolutely the
953 same thing and run at the same speed, but the latter is certainly shorter:
956 Mat_<double> M(20,20);
957 for(int i = 0; i < M.rows; i++)
958 for(int j = 0; j < M.cols; j++)
962 cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
965 It is easy to use Mat_ for multi-channel images/matrices - just pass cv::Vec as cv::Mat_ template parameter:
968 // allocate 320x240 color image and fill it with green (in RGB space)
969 Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
970 // now draw a diagonal white line
971 for(int i = 0; i < 100; i++)
972 img(i,i)=Vec3b(255,255,255);
973 // and now modify the 2nd (red) channel of each pixel
974 for(int i = 0; i < img.rows; i++)
975 for(int j = 0; j < img.cols; j++)
976 img(i,j)[2] ^= (uchar)(i ^ j); // img(y,x)[c] accesses c-th channel of the pixel (x,y)
979 template<typename _Tp> class Mat_ : public Mat
982 typedef _Tp value_type;
983 typedef typename DataType<_Tp>::channel_type channel_type;
984 typedef MatIterator_<_Tp> iterator;
985 typedef MatConstIterator_<_Tp> const_iterator;
987 //! default constructor
989 //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type)
990 Mat_(int _rows, int _cols);
991 //! constructor that sets each matrix element to specified value
992 Mat_(int _rows, int _cols, const _Tp& value);
993 //! equivalent to Mat(_size, DataType<_Tp>::type)
994 explicit Mat_(Size _size);
995 //! constructor that sets each matrix element to specified value
996 Mat_(Size _size, const _Tp& value);
997 //! n-dim array constructor
998 Mat_(int _ndims, const int* _sizes);
999 //! n-dim array constructor that sets each matrix element to specified value
1000 Mat_(int _ndims, const int* _sizes, const _Tp& value);
1001 //! copy/conversion contructor. If m is of different type, it's converted
1003 //! copy constructor
1004 Mat_(const Mat_& m);
1005 //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type
1006 Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP);
1007 //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type
1008 Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0);
1009 //! selects a submatrix
1010 Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all());
1011 //! selects a submatrix
1012 Mat_(const Mat_& m, const Rect& roi);
1013 //! selects a submatrix, n-dim version
1014 Mat_(const Mat_& m, const Range* ranges);
1015 //! from a matrix expression
1016 explicit Mat_(const MatExpr& e);
1017 //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column
1018 explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false);
1019 template<int n> explicit Mat_(const Vec<typename DataType<_Tp>::channel_type, n>& vec, bool copyData=true);
1020 template<int m, int n> explicit Mat_(const Matx<typename DataType<_Tp>::channel_type, m, n>& mtx, bool copyData=true);
1021 explicit Mat_(const Point_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
1022 explicit Mat_(const Point3_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
1023 explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer);
1025 Mat_& operator = (const Mat& m);
1026 Mat_& operator = (const Mat_& m);
1027 //! set all the elements to s.
1028 Mat_& operator = (const _Tp& s);
1029 //! assign a matrix expression
1030 Mat_& operator = (const MatExpr& e);
1032 //! iterators; they are smart enough to skip gaps in the end of rows
1035 const_iterator begin() const;
1036 const_iterator end() const;
1038 //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type)
1039 void create(int _rows, int _cols);
1040 //! equivalent to Mat::create(_size, DataType<_Tp>::type)
1041 void create(Size _size);
1042 //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type)
1043 void create(int _ndims, const int* _sizes);
1045 Mat_ cross(const Mat_& m) const;
1046 //! data type conversion
1047 template<typename T2> operator Mat_<T2>() const;
1048 //! overridden forms of Mat::row() etc.
1049 Mat_ row(int y) const;
1050 Mat_ col(int x) const;
1051 Mat_ diag(int d=0) const;
1054 //! overridden forms of Mat::elemSize() etc.
1055 size_t elemSize() const;
1056 size_t elemSize1() const;
1059 int channels() const;
1060 size_t step1(int i=0) const;
1061 //! returns step()/sizeof(_Tp)
1062 size_t stepT(int i=0) const;
1064 //! overridden forms of Mat::zeros() etc. Data type is omitted, of course
1065 static MatExpr zeros(int rows, int cols);
1066 static MatExpr zeros(Size size);
1067 static MatExpr zeros(int _ndims, const int* _sizes);
1068 static MatExpr ones(int rows, int cols);
1069 static MatExpr ones(Size size);
1070 static MatExpr ones(int _ndims, const int* _sizes);
1071 static MatExpr eye(int rows, int cols);
1072 static MatExpr eye(Size size);
1074 //! some more overriden methods
1075 Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright );
1076 Mat_ operator()( const Range& rowRange, const Range& colRange ) const;
1077 Mat_ operator()( const Rect& roi ) const;
1078 Mat_ operator()( const Range* ranges ) const;
1080 //! more convenient forms of row and element access operators
1081 _Tp* operator [](int y);
1082 const _Tp* operator [](int y) const;
1084 //! returns reference to the specified element
1085 _Tp& operator ()(const int* idx);
1086 //! returns read-only reference to the specified element
1087 const _Tp& operator ()(const int* idx) const;
1089 //! returns reference to the specified element
1090 template<int n> _Tp& operator ()(const Vec<int, n>& idx);
1091 //! returns read-only reference to the specified element
1092 template<int n> const _Tp& operator ()(const Vec<int, n>& idx) const;
1094 //! returns reference to the specified element (1D case)
1095 _Tp& operator ()(int idx0);
1096 //! returns read-only reference to the specified element (1D case)
1097 const _Tp& operator ()(int idx0) const;
1098 //! returns reference to the specified element (2D case)
1099 _Tp& operator ()(int idx0, int idx1);
1100 //! returns read-only reference to the specified element (2D case)
1101 const _Tp& operator ()(int idx0, int idx1) const;
1102 //! returns reference to the specified element (3D case)
1103 _Tp& operator ()(int idx0, int idx1, int idx2);
1104 //! returns read-only reference to the specified element (3D case)
1105 const _Tp& operator ()(int idx0, int idx1, int idx2) const;
1107 _Tp& operator ()(Point pt);
1108 const _Tp& operator ()(Point pt) const;
1110 //! conversion to vector.
1111 operator std::vector<_Tp>() const;
1112 //! conversion to Vec
1113 template<int n> operator Vec<typename DataType<_Tp>::channel_type, n>() const;
1114 //! conversion to Matx
1115 template<int m, int n> operator Matx<typename DataType<_Tp>::channel_type, m, n>() const;
1118 typedef Mat_<uchar> Mat1b;
1119 typedef Mat_<Vec2b> Mat2b;
1120 typedef Mat_<Vec3b> Mat3b;
1121 typedef Mat_<Vec4b> Mat4b;
1123 typedef Mat_<short> Mat1s;
1124 typedef Mat_<Vec2s> Mat2s;
1125 typedef Mat_<Vec3s> Mat3s;
1126 typedef Mat_<Vec4s> Mat4s;
1128 typedef Mat_<ushort> Mat1w;
1129 typedef Mat_<Vec2w> Mat2w;
1130 typedef Mat_<Vec3w> Mat3w;
1131 typedef Mat_<Vec4w> Mat4w;
1133 typedef Mat_<int> Mat1i;
1134 typedef Mat_<Vec2i> Mat2i;
1135 typedef Mat_<Vec3i> Mat3i;
1136 typedef Mat_<Vec4i> Mat4i;
1138 typedef Mat_<float> Mat1f;
1139 typedef Mat_<Vec2f> Mat2f;
1140 typedef Mat_<Vec3f> Mat3f;
1141 typedef Mat_<Vec4f> Mat4f;
1143 typedef Mat_<double> Mat1d;
1144 typedef Mat_<Vec2d> Mat2d;
1145 typedef Mat_<Vec3d> Mat3d;
1146 typedef Mat_<Vec4d> Mat4d;
1148 class CV_EXPORTS UMat
1151 //! default constructor
1152 UMat(UMatUsageFlags usageFlags = USAGE_DEFAULT);
1153 //! constructs 2D matrix of the specified size and type
1154 // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
1155 UMat(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1156 UMat(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1157 //! constucts 2D matrix and fills it with the specified value _s.
1158 UMat(int rows, int cols, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1159 UMat(Size size, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1161 //! constructs n-dimensional matrix
1162 UMat(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1163 UMat(int ndims, const int* sizes, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1165 //! copy constructor
1166 UMat(const UMat& m);
1168 //! creates a matrix header for a part of the bigger matrix
1169 UMat(const UMat& m, const Range& rowRange, const Range& colRange=Range::all());
1170 UMat(const UMat& m, const Rect& roi);
1171 UMat(const UMat& m, const Range* ranges);
1172 //! builds matrix from std::vector with or without copying the data
1173 template<typename _Tp> explicit UMat(const std::vector<_Tp>& vec, bool copyData=false);
1174 //! builds matrix from cv::Vec; the data is copied by default
1175 template<typename _Tp, int n> explicit UMat(const Vec<_Tp, n>& vec, bool copyData=true);
1176 //! builds matrix from cv::Matx; the data is copied by default
1177 template<typename _Tp, int m, int n> explicit UMat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
1178 //! builds matrix from a 2D point
1179 template<typename _Tp> explicit UMat(const Point_<_Tp>& pt, bool copyData=true);
1180 //! builds matrix from a 3D point
1181 template<typename _Tp> explicit UMat(const Point3_<_Tp>& pt, bool copyData=true);
1182 //! builds matrix from comma initializer
1183 template<typename _Tp> explicit UMat(const MatCommaInitializer_<_Tp>& commaInitializer);
1185 //! destructor - calls release()
1187 //! assignment operators
1188 UMat& operator = (const UMat& m);
1190 Mat getMat(int flags) const;
1192 //! returns a new matrix header for the specified row
1193 UMat row(int y) const;
1194 //! returns a new matrix header for the specified column
1195 UMat col(int x) const;
1196 //! ... for the specified row span
1197 UMat rowRange(int startrow, int endrow) const;
1198 UMat rowRange(const Range& r) const;
1199 //! ... for the specified column span
1200 UMat colRange(int startcol, int endcol) const;
1201 UMat colRange(const Range& r) const;
1202 //! ... for the specified diagonal
1203 // (d=0 - the main diagonal,
1204 // >0 - a diagonal from the lower half,
1205 // <0 - a diagonal from the upper half)
1206 UMat diag(int d=0) const;
1207 //! constructs a square diagonal matrix which main diagonal is vector "d"
1208 static UMat diag(const UMat& d);
1210 //! returns deep copy of the matrix, i.e. the data is copied
1212 //! copies the matrix content to "m".
1213 // It calls m.create(this->size(), this->type()).
1214 void copyTo( OutputArray m ) const;
1215 //! copies those matrix elements to "m" that are marked with non-zero mask elements.
1216 void copyTo( OutputArray m, InputArray mask ) const;
1217 //! converts matrix to another datatype with optional scalng. See cvConvertScale.
1218 void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
1220 void assignTo( UMat& m, int type=-1 ) const;
1222 //! sets every matrix element to s
1223 UMat& operator = (const Scalar& s);
1224 //! sets some of the matrix elements to s, according to the mask
1225 UMat& setTo(InputArray value, InputArray mask=noArray());
1226 //! creates alternative matrix header for the same data, with different
1227 // number of channels and/or different number of rows. see cvReshape.
1228 UMat reshape(int cn, int rows=0) const;
1229 UMat reshape(int cn, int newndims, const int* newsz) const;
1231 //! matrix transposition by means of matrix expressions
1233 //! matrix inversion by means of matrix expressions
1234 UMat inv(int method=DECOMP_LU) const;
1235 //! per-element matrix multiplication by means of matrix expressions
1236 UMat mul(InputArray m, double scale=1) const;
1238 //! computes dot-product
1239 double dot(InputArray m) const;
1241 //! Matlab-style matrix initialization
1242 static UMat zeros(int rows, int cols, int type);
1243 static UMat zeros(Size size, int type);
1244 static UMat zeros(int ndims, const int* sz, int type);
1245 static UMat ones(int rows, int cols, int type);
1246 static UMat ones(Size size, int type);
1247 static UMat ones(int ndims, const int* sz, int type);
1248 static UMat eye(int rows, int cols, int type);
1249 static UMat eye(Size size, int type);
1251 //! allocates new matrix data unless the matrix already has specified size and type.
1252 // previous data is unreferenced if needed.
1253 void create(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1254 void create(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1255 void create(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1257 //! increases the reference counter; use with care to avoid memleaks
1259 //! decreases reference counter;
1260 // deallocates the data when reference counter reaches 0.
1263 //! deallocates the matrix data
1265 //! internal use function; properly re-allocates _size, _step arrays
1266 void copySize(const UMat& m);
1268 //! locates matrix header within a parent matrix. See below
1269 void locateROI( Size& wholeSize, Point& ofs ) const;
1270 //! moves/resizes the current matrix ROI inside the parent matrix.
1271 UMat& adjustROI( int dtop, int dbottom, int dleft, int dright );
1272 //! extracts a rectangular sub-matrix
1273 // (this is a generalized form of row, rowRange etc.)
1274 UMat operator()( Range rowRange, Range colRange ) const;
1275 UMat operator()( const Rect& roi ) const;
1276 UMat operator()( const Range* ranges ) const;
1278 //! returns true iff the matrix data is continuous
1279 // (i.e. when there are no gaps between successive rows).
1280 // similar to CV_IS_MAT_CONT(cvmat->type)
1281 bool isContinuous() const;
1283 //! returns true if the matrix is a submatrix of another matrix
1284 bool isSubmatrix() const;
1286 //! returns element size in bytes,
1287 // similar to CV_ELEM_SIZE(cvmat->type)
1288 size_t elemSize() const;
1289 //! returns the size of element channel in bytes.
1290 size_t elemSize1() const;
1291 //! returns element type, similar to CV_MAT_TYPE(cvmat->type)
1293 //! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
1295 //! returns element type, similar to CV_MAT_CN(cvmat->type)
1296 int channels() const;
1297 //! returns step/elemSize1()
1298 size_t step1(int i=0) const;
1299 //! returns true if matrix data is NULL
1301 //! returns the total number of matrix elements
1302 size_t total() const;
1304 //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
1305 int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
1307 void* handle(int accessFlags) const;
1308 void ndoffset(size_t* ofs) const;
1310 enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
1311 enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
1313 /*! includes several bit-fields:
1314 - the magic signature
1317 - number of channels
1320 //! the matrix dimensionality, >= 2
1322 //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
1325 //! custom allocator
1326 MatAllocator* allocator;
1327 UMatUsageFlags usageFlags; // usage flags for allocator
1328 //! and the standard allocator
1329 static MatAllocator* getStdAllocator();
1331 // black-box container of UMat data
1334 // offset of the submatrix (or 0)
1344 /////////////////////////// multi-dimensional sparse matrix //////////////////////////
1347 Sparse matrix class.
1349 The class represents multi-dimensional sparse numerical arrays. Such a sparse array can store elements
1350 of any type that cv::Mat is able to store. "Sparse" means that only non-zero elements
1351 are stored (though, as a result of some operations on a sparse matrix, some of its stored elements
1352 can actually become 0. It's user responsibility to detect such elements and delete them using cv::SparseMat::erase().
1353 The non-zero elements are stored in a hash table that grows when it's filled enough,
1354 so that the search time remains O(1) in average. Elements can be accessed using the following methods:
1357 <li>Query operations: cv::SparseMat::ptr() and the higher-level cv::SparseMat::ref(),
1358 cv::SparseMat::value() and cv::SparseMat::find, for example:
1361 int size[] = {10, 10, 10, 10, 10};
1362 SparseMat sparse_mat(dims, size, CV_32F);
1363 for(int i = 0; i < 1000; i++)
1366 for(int k = 0; k < dims; k++)
1367 idx[k] = rand()%sparse_mat.size(k);
1368 sparse_mat.ref<float>(idx) += 1.f;
1372 <li>Sparse matrix iterators. Like cv::Mat iterators and unlike cv::Mat iterators, the sparse matrix iterators are STL-style,
1373 that is, the iteration is done as following:
1375 // prints elements of a sparse floating-point matrix and the sum of elements.
1376 SparseMatConstIterator_<float>
1377 it = sparse_mat.begin<float>(),
1378 it_end = sparse_mat.end<float>();
1380 int dims = sparse_mat.dims();
1381 for(; it != it_end; ++it)
1383 // print element indices and the element value
1384 const Node* n = it.node();
1386 for(int i = 0; i < dims; i++)
1387 printf("%3d%c", n->idx[i], i < dims-1 ? ',' : ')');
1388 printf(": %f\n", *it);
1391 printf("Element sum is %g\n", s);
1393 If you run this loop, you will notice that elements are enumerated
1394 in no any logical order (lexicographical etc.),
1395 they come in the same order as they stored in the hash table, i.e. semi-randomly.
1397 You may collect pointers to the nodes and sort them to get the proper ordering.
1398 Note, however, that pointers to the nodes may become invalid when you add more
1399 elements to the matrix; this is because of possible buffer reallocation.
1401 <li>A combination of the above 2 methods when you need to process 2 or more sparse
1402 matrices simultaneously, e.g. this is how you can compute unnormalized
1403 cross-correlation of the 2 floating-point sparse matrices:
1405 double crossCorr(const SparseMat& a, const SparseMat& b)
1407 const SparseMat *_a = &a, *_b = &b;
1408 // if b contains less elements than a,
1409 // it's faster to iterate through b
1410 if(_a->nzcount() > _b->nzcount())
1412 SparseMatConstIterator_<float> it = _a->begin<float>(),
1413 it_end = _a->end<float>();
1415 for(; it != it_end; ++it)
1417 // take the next element from the first matrix
1419 const Node* anode = it.node();
1420 // and try to find element with the same index in the second matrix.
1421 // since the hash value depends only on the element index,
1422 // we reuse hashvalue stored in the node
1423 float bvalue = _b->value<float>(anode->idx,&anode->hashval);
1424 ccorr += avalue*bvalue;
1431 class CV_EXPORTS SparseMat
1434 typedef SparseMatIterator iterator;
1435 typedef SparseMatConstIterator const_iterator;
1437 enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 };
1439 //! the sparse matrix header
1440 struct CV_EXPORTS Hdr
1442 Hdr(int _dims, const int* _sizes, int _type);
1450 std::vector<uchar> pool;
1451 std::vector<size_t> hashtab;
1455 //! sparse matrix node - element of a hash table
1456 struct CV_EXPORTS Node
1460 //! index of the next node in the same hash table entry
1462 //! index of the matrix element
1466 //! default constructor
1468 //! creates matrix of the specified size and type
1469 SparseMat(int dims, const int* _sizes, int _type);
1470 //! copy constructor
1471 SparseMat(const SparseMat& m);
1472 //! converts dense 2d matrix to the sparse form
1474 \param m the input matrix
1476 explicit SparseMat(const Mat& m);
1477 //! converts old-style sparse matrix to the new-style. All the data is copied
1478 //SparseMat(const CvSparseMat* m);
1482 //! assignment operator. This is O(1) operation, i.e. no data is copied
1483 SparseMat& operator = (const SparseMat& m);
1484 //! equivalent to the corresponding constructor
1485 SparseMat& operator = (const Mat& m);
1487 //! creates full copy of the matrix
1488 SparseMat clone() const;
1490 //! copies all the data to the destination matrix. All the previous content of m is erased
1491 void copyTo( SparseMat& m ) const;
1492 //! converts sparse matrix to dense matrix.
1493 void copyTo( Mat& m ) const;
1494 //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type
1495 void convertTo( SparseMat& m, int rtype, double alpha=1 ) const;
1496 //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling.
1498 \param rtype The output matrix data type. When it is =-1, the output array will have the same data type as (*this)
1499 \param alpha The scale factor
1500 \param beta The optional delta added to the scaled values before the conversion
1502 void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
1505 void assignTo( SparseMat& m, int type=-1 ) const;
1507 //! reallocates sparse matrix.
1509 If the matrix already had the proper size and type,
1510 it is simply cleared with clear(), otherwise,
1511 the old matrix is released (using release()) and the new one is allocated.
1513 void create(int dims, const int* _sizes, int _type);
1514 //! sets all the sparse matrix elements to 0, which means clearing the hash table.
1516 //! manually increments the reference counter to the header.
1518 // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated.
1521 //! converts sparse matrix to the old-style representation; all the elements are copied.
1522 //operator CvSparseMat*() const;
1523 //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements)
1524 size_t elemSize() const;
1525 //! returns elemSize()/channels()
1526 size_t elemSize1() const;
1528 //! returns type of sparse matrix elements
1530 //! returns the depth of sparse matrix elements
1532 //! returns the number of channels
1533 int channels() const;
1535 //! returns the array of sizes, or NULL if the matrix is not allocated
1536 const int* size() const;
1537 //! returns the size of i-th matrix dimension (or 0)
1538 int size(int i) const;
1539 //! returns the matrix dimensionality
1541 //! returns the number of non-zero elements (=the number of hash table nodes)
1542 size_t nzcount() const;
1544 //! computes the element hash value (1D case)
1545 size_t hash(int i0) const;
1546 //! computes the element hash value (2D case)
1547 size_t hash(int i0, int i1) const;
1548 //! computes the element hash value (3D case)
1549 size_t hash(int i0, int i1, int i2) const;
1550 //! computes the element hash value (nD case)
1551 size_t hash(const int* idx) const;
1555 specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case.
1557 return pointer to the matrix element.
1559 <li>if the element is there (it's non-zero), the pointer to it is returned
1560 <li>if it's not there and createMissing=false, NULL pointer is returned
1561 <li>if it's not there and createMissing=true, then the new element
1562 is created and initialized with 0. Pointer to it is returned
1563 <li>if the optional hashval pointer is not NULL, the element hash value is
1564 not computed, but *hashval is taken instead.
1567 //! returns pointer to the specified element (1D case)
1568 uchar* ptr(int i0, bool createMissing, size_t* hashval=0);
1569 //! returns pointer to the specified element (2D case)
1570 uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0);
1571 //! returns pointer to the specified element (3D case)
1572 uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0);
1573 //! returns pointer to the specified element (nD case)
1574 uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0);
1579 return read-write reference to the specified sparse matrix element.
1581 ref<_Tp>(i0,...[,hashval]) is equivalent to *(_Tp*)ptr(i0,...,true[,hashval]).
1582 The methods always return a valid reference.
1583 If the element did not exist, it is created and initialiazed with 0.
1585 //! returns reference to the specified element (1D case)
1586 template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0);
1587 //! returns reference to the specified element (2D case)
1588 template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0);
1589 //! returns reference to the specified element (3D case)
1590 template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
1591 //! returns reference to the specified element (nD case)
1592 template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0);
1597 return value of the specified sparse matrix element.
1599 value<_Tp>(i0,...[,hashval]) is equivalent
1602 { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); }
1605 That is, if the element did not exist, the methods return 0.
1607 //! returns value of the specified element (1D case)
1608 template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const;
1609 //! returns value of the specified element (2D case)
1610 template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const;
1611 //! returns value of the specified element (3D case)
1612 template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0) const;
1613 //! returns value of the specified element (nD case)
1614 template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const;
1619 Return pointer to the specified sparse matrix element if it exists
1621 find<_Tp>(i0,...[,hashval]) is equivalent to (_const Tp*)ptr(i0,...false[,hashval]).
1623 If the specified element does not exist, the methods return NULL.
1625 //! returns pointer to the specified element (1D case)
1626 template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const;
1627 //! returns pointer to the specified element (2D case)
1628 template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0) const;
1629 //! returns pointer to the specified element (3D case)
1630 template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const;
1631 //! returns pointer to the specified element (nD case)
1632 template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0) const;
1634 //! erases the specified element (2D case)
1635 void erase(int i0, int i1, size_t* hashval=0);
1636 //! erases the specified element (3D case)
1637 void erase(int i0, int i1, int i2, size_t* hashval=0);
1638 //! erases the specified element (nD case)
1639 void erase(const int* idx, size_t* hashval=0);
1643 return the sparse matrix iterator pointing to the first sparse matrix element
1645 //! returns the sparse matrix iterator at the matrix beginning
1646 SparseMatIterator begin();
1647 //! returns the sparse matrix iterator at the matrix beginning
1648 template<typename _Tp> SparseMatIterator_<_Tp> begin();
1649 //! returns the read-only sparse matrix iterator at the matrix beginning
1650 SparseMatConstIterator begin() const;
1651 //! returns the read-only sparse matrix iterator at the matrix beginning
1652 template<typename _Tp> SparseMatConstIterator_<_Tp> begin() const;
1655 return the sparse matrix iterator pointing to the element following the last sparse matrix element
1657 //! returns the sparse matrix iterator at the matrix end
1658 SparseMatIterator end();
1659 //! returns the read-only sparse matrix iterator at the matrix end
1660 SparseMatConstIterator end() const;
1661 //! returns the typed sparse matrix iterator at the matrix end
1662 template<typename _Tp> SparseMatIterator_<_Tp> end();
1663 //! returns the typed read-only sparse matrix iterator at the matrix end
1664 template<typename _Tp> SparseMatConstIterator_<_Tp> end() const;
1666 //! returns the value stored in the sparse martix node
1667 template<typename _Tp> _Tp& value(Node* n);
1668 //! returns the value stored in the sparse martix node
1669 template<typename _Tp> const _Tp& value(const Node* n) const;
1671 ////////////// some internal-use methods ///////////////
1672 Node* node(size_t nidx);
1673 const Node* node(size_t nidx) const;
1675 uchar* newNode(const int* idx, size_t hashval);
1676 void removeNode(size_t hidx, size_t nidx, size_t previdx);
1677 void resizeHashTab(size_t newsize);
1685 ///////////////////////////////// SparseMat_<_Tp> ////////////////////////////////////
1688 The Template Sparse Matrix class derived from cv::SparseMat
1690 The class provides slightly more convenient operations for accessing elements.
1695 SparseMat_<int> m_ = (SparseMat_<int>&)m;
1696 m_.ref(1)++; // equivalent to m.ref<int>(1)++;
1697 m_.ref(2) += m_(3); // equivalent to m.ref<int>(2) += m.value<int>(3);
1700 template<typename _Tp> class SparseMat_ : public SparseMat
1703 typedef SparseMatIterator_<_Tp> iterator;
1704 typedef SparseMatConstIterator_<_Tp> const_iterator;
1706 //! the default constructor
1708 //! the full constructor equivelent to SparseMat(dims, _sizes, DataType<_Tp>::type)
1709 SparseMat_(int dims, const int* _sizes);
1710 //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted
1711 SparseMat_(const SparseMat& m);
1712 //! the copy constructor. This is O(1) operation - no data is copied
1713 SparseMat_(const SparseMat_& m);
1714 //! converts dense matrix to the sparse form
1715 SparseMat_(const Mat& m);
1716 //! converts the old-style sparse matrix to the C++ class. All the elements are copied
1717 //SparseMat_(const CvSparseMat* m);
1718 //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted
1719 SparseMat_& operator = (const SparseMat& m);
1720 //! the assignment operator. This is O(1) operation - no data is copied
1721 SparseMat_& operator = (const SparseMat_& m);
1722 //! converts dense matrix to the sparse form
1723 SparseMat_& operator = (const Mat& m);
1725 //! makes full copy of the matrix. All the elements are duplicated
1726 SparseMat_ clone() const;
1727 //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type)
1728 void create(int dims, const int* _sizes);
1729 //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied
1730 //operator CvSparseMat*() const;
1732 //! returns type of the matrix elements
1734 //! returns depth of the matrix elements
1736 //! returns the number of channels in each matrix element
1737 int channels() const;
1739 //! equivalent to SparseMat::ref<_Tp>(i0, hashval)
1740 _Tp& ref(int i0, size_t* hashval=0);
1741 //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval)
1742 _Tp& ref(int i0, int i1, size_t* hashval=0);
1743 //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval)
1744 _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
1745 //! equivalent to SparseMat::ref<_Tp>(idx, hashval)
1746 _Tp& ref(const int* idx, size_t* hashval=0);
1748 //! equivalent to SparseMat::value<_Tp>(i0, hashval)
1749 _Tp operator()(int i0, size_t* hashval=0) const;
1750 //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval)
1751 _Tp operator()(int i0, int i1, size_t* hashval=0) const;
1752 //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval)
1753 _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const;
1754 //! equivalent to SparseMat::value<_Tp>(idx, hashval)
1755 _Tp operator()(const int* idx, size_t* hashval=0) const;
1757 //! returns sparse matrix iterator pointing to the first sparse matrix element
1758 SparseMatIterator_<_Tp> begin();
1759 //! returns read-only sparse matrix iterator pointing to the first sparse matrix element
1760 SparseMatConstIterator_<_Tp> begin() const;
1761 //! returns sparse matrix iterator pointing to the element following the last sparse matrix element
1762 SparseMatIterator_<_Tp> end();
1763 //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element
1764 SparseMatConstIterator_<_Tp> end() const;
1769 ////////////////////////////////// MatConstIterator //////////////////////////////////
1771 class CV_EXPORTS MatConstIterator
1774 typedef uchar* value_type;
1775 typedef ptrdiff_t difference_type;
1776 typedef const uchar** pointer;
1777 typedef uchar* reference;
1779 #ifndef OPENCV_NOSTL
1780 typedef std::random_access_iterator_tag iterator_category;
1783 //! default constructor
1785 //! constructor that sets the iterator to the beginning of the matrix
1786 MatConstIterator(const Mat* _m);
1787 //! constructor that sets the iterator to the specified element of the matrix
1788 MatConstIterator(const Mat* _m, int _row, int _col=0);
1789 //! constructor that sets the iterator to the specified element of the matrix
1790 MatConstIterator(const Mat* _m, Point _pt);
1791 //! constructor that sets the iterator to the specified element of the matrix
1792 MatConstIterator(const Mat* _m, const int* _idx);
1793 //! copy constructor
1794 MatConstIterator(const MatConstIterator& it);
1797 MatConstIterator& operator = (const MatConstIterator& it);
1798 //! returns the current matrix element
1799 uchar* operator *() const;
1800 //! returns the i-th matrix element, relative to the current
1801 uchar* operator [](ptrdiff_t i) const;
1803 //! shifts the iterator forward by the specified number of elements
1804 MatConstIterator& operator += (ptrdiff_t ofs);
1805 //! shifts the iterator backward by the specified number of elements
1806 MatConstIterator& operator -= (ptrdiff_t ofs);
1807 //! decrements the iterator
1808 MatConstIterator& operator --();
1809 //! decrements the iterator
1810 MatConstIterator operator --(int);
1811 //! increments the iterator
1812 MatConstIterator& operator ++();
1813 //! increments the iterator
1814 MatConstIterator operator ++(int);
1815 //! returns the current iterator position
1817 //! returns the current iterator position
1818 void pos(int* _idx) const;
1820 ptrdiff_t lpos() const;
1821 void seek(ptrdiff_t ofs, bool relative = false);
1822 void seek(const int* _idx, bool relative = false);
1833 ////////////////////////////////// MatConstIterator_ /////////////////////////////////
1836 Matrix read-only iterator
1838 template<typename _Tp>
1839 class MatConstIterator_ : public MatConstIterator
1842 typedef _Tp value_type;
1843 typedef ptrdiff_t difference_type;
1844 typedef const _Tp* pointer;
1845 typedef const _Tp& reference;
1847 #ifndef OPENCV_NOSTL
1848 typedef std::random_access_iterator_tag iterator_category;
1851 //! default constructor
1852 MatConstIterator_();
1853 //! constructor that sets the iterator to the beginning of the matrix
1854 MatConstIterator_(const Mat_<_Tp>* _m);
1855 //! constructor that sets the iterator to the specified element of the matrix
1856 MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0);
1857 //! constructor that sets the iterator to the specified element of the matrix
1858 MatConstIterator_(const Mat_<_Tp>* _m, Point _pt);
1859 //! constructor that sets the iterator to the specified element of the matrix
1860 MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx);
1861 //! copy constructor
1862 MatConstIterator_(const MatConstIterator_& it);
1865 MatConstIterator_& operator = (const MatConstIterator_& it);
1866 //! returns the current matrix element
1867 _Tp operator *() const;
1868 //! returns the i-th matrix element, relative to the current
1869 _Tp operator [](ptrdiff_t i) const;
1871 //! shifts the iterator forward by the specified number of elements
1872 MatConstIterator_& operator += (ptrdiff_t ofs);
1873 //! shifts the iterator backward by the specified number of elements
1874 MatConstIterator_& operator -= (ptrdiff_t ofs);
1875 //! decrements the iterator
1876 MatConstIterator_& operator --();
1877 //! decrements the iterator
1878 MatConstIterator_ operator --(int);
1879 //! increments the iterator
1880 MatConstIterator_& operator ++();
1881 //! increments the iterator
1882 MatConstIterator_ operator ++(int);
1883 //! returns the current iterator position
1889 //////////////////////////////////// MatIterator_ ////////////////////////////////////
1892 Matrix read-write iterator
1894 template<typename _Tp>
1895 class MatIterator_ : public MatConstIterator_<_Tp>
1898 typedef _Tp* pointer;
1899 typedef _Tp& reference;
1901 #ifndef OPENCV_NOSTL
1902 typedef std::random_access_iterator_tag iterator_category;
1905 //! the default constructor
1907 //! constructor that sets the iterator to the beginning of the matrix
1908 MatIterator_(Mat_<_Tp>* _m);
1909 //! constructor that sets the iterator to the specified element of the matrix
1910 MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0);
1911 //! constructor that sets the iterator to the specified element of the matrix
1912 MatIterator_(const Mat_<_Tp>* _m, Point _pt);
1913 //! constructor that sets the iterator to the specified element of the matrix
1914 MatIterator_(const Mat_<_Tp>* _m, const int* _idx);
1915 //! copy constructor
1916 MatIterator_(const MatIterator_& it);
1918 MatIterator_& operator = (const MatIterator_<_Tp>& it );
1920 //! returns the current matrix element
1921 _Tp& operator *() const;
1922 //! returns the i-th matrix element, relative to the current
1923 _Tp& operator [](ptrdiff_t i) const;
1925 //! shifts the iterator forward by the specified number of elements
1926 MatIterator_& operator += (ptrdiff_t ofs);
1927 //! shifts the iterator backward by the specified number of elements
1928 MatIterator_& operator -= (ptrdiff_t ofs);
1929 //! decrements the iterator
1930 MatIterator_& operator --();
1931 //! decrements the iterator
1932 MatIterator_ operator --(int);
1933 //! increments the iterator
1934 MatIterator_& operator ++();
1935 //! increments the iterator
1936 MatIterator_ operator ++(int);
1941 /////////////////////////////// SparseMatConstIterator ///////////////////////////////
1944 Read-Only Sparse Matrix Iterator.
1945 Here is how to use the iterator to compute the sum of floating-point sparse matrix elements:
1948 SparseMatConstIterator it = m.begin(), it_end = m.end();
1950 CV_Assert( m.type() == CV_32F );
1951 for( ; it != it_end; ++it )
1952 s += it.value<float>();
1955 class CV_EXPORTS SparseMatConstIterator
1958 //! the default constructor
1959 SparseMatConstIterator();
1960 //! the full constructor setting the iterator to the first sparse matrix element
1961 SparseMatConstIterator(const SparseMat* _m);
1962 //! the copy constructor
1963 SparseMatConstIterator(const SparseMatConstIterator& it);
1965 //! the assignment operator
1966 SparseMatConstIterator& operator = (const SparseMatConstIterator& it);
1968 //! template method returning the current matrix element
1969 template<typename _Tp> const _Tp& value() const;
1970 //! returns the current node of the sparse matrix. it.node->idx is the current element index
1971 const SparseMat::Node* node() const;
1973 //! moves iterator to the previous element
1974 SparseMatConstIterator& operator --();
1975 //! moves iterator to the previous element
1976 SparseMatConstIterator operator --(int);
1977 //! moves iterator to the next element
1978 SparseMatConstIterator& operator ++();
1979 //! moves iterator to the next element
1980 SparseMatConstIterator operator ++(int);
1982 //! moves iterator to the element after the last element
1992 ////////////////////////////////// SparseMatIterator /////////////////////////////////
1995 Read-write Sparse Matrix Iterator
1997 The class is similar to cv::SparseMatConstIterator,
1998 but can be used for in-place modification of the matrix elements.
2000 class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator
2003 //! the default constructor
2004 SparseMatIterator();
2005 //! the full constructor setting the iterator to the first sparse matrix element
2006 SparseMatIterator(SparseMat* _m);
2007 //! the full constructor setting the iterator to the specified sparse matrix element
2008 SparseMatIterator(SparseMat* _m, const int* idx);
2009 //! the copy constructor
2010 SparseMatIterator(const SparseMatIterator& it);
2012 //! the assignment operator
2013 SparseMatIterator& operator = (const SparseMatIterator& it);
2014 //! returns read-write reference to the current sparse matrix element
2015 template<typename _Tp> _Tp& value() const;
2016 //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!)
2017 SparseMat::Node* node() const;
2019 //! moves iterator to the next element
2020 SparseMatIterator& operator ++();
2021 //! moves iterator to the next element
2022 SparseMatIterator operator ++(int);
2027 /////////////////////////////// SparseMatConstIterator_ //////////////////////////////
2030 Template Read-Only Sparse Matrix Iterator Class.
2032 This is the derived from SparseMatConstIterator class that
2033 introduces more convenient operator *() for accessing the current element.
2035 template<typename _Tp> class SparseMatConstIterator_ : public SparseMatConstIterator
2039 #ifndef OPENCV_NOSTL
2040 typedef std::forward_iterator_tag iterator_category;
2043 //! the default constructor
2044 SparseMatConstIterator_();
2045 //! the full constructor setting the iterator to the first sparse matrix element
2046 SparseMatConstIterator_(const SparseMat_<_Tp>* _m);
2047 SparseMatConstIterator_(const SparseMat* _m);
2048 //! the copy constructor
2049 SparseMatConstIterator_(const SparseMatConstIterator_& it);
2051 //! the assignment operator
2052 SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it);
2053 //! the element access operator
2054 const _Tp& operator *() const;
2056 //! moves iterator to the next element
2057 SparseMatConstIterator_& operator ++();
2058 //! moves iterator to the next element
2059 SparseMatConstIterator_ operator ++(int);
2064 ///////////////////////////////// SparseMatIterator_ /////////////////////////////////
2067 Template Read-Write Sparse Matrix Iterator Class.
2069 This is the derived from cv::SparseMatConstIterator_ class that
2070 introduces more convenient operator *() for accessing the current element.
2072 template<typename _Tp> class SparseMatIterator_ : public SparseMatConstIterator_<_Tp>
2076 #ifndef OPENCV_NOSTL
2077 typedef std::forward_iterator_tag iterator_category;
2080 //! the default constructor
2081 SparseMatIterator_();
2082 //! the full constructor setting the iterator to the first sparse matrix element
2083 SparseMatIterator_(SparseMat_<_Tp>* _m);
2084 SparseMatIterator_(SparseMat* _m);
2085 //! the copy constructor
2086 SparseMatIterator_(const SparseMatIterator_& it);
2088 //! the assignment operator
2089 SparseMatIterator_& operator = (const SparseMatIterator_& it);
2090 //! returns the reference to the current element
2091 _Tp& operator *() const;
2093 //! moves the iterator to the next element
2094 SparseMatIterator_& operator ++();
2095 //! moves the iterator to the next element
2096 SparseMatIterator_ operator ++(int);
2101 /////////////////////////////////// NAryMatIterator //////////////////////////////////
2104 n-Dimensional Dense Matrix Iterator Class.
2106 The class cv::NAryMatIterator is used for iterating over one or more n-dimensional dense arrays (cv::Mat's).
2108 The iterator is completely different from cv::Mat_ and cv::SparseMat_ iterators.
2109 It iterates through the slices (or planes), not the elements, where "slice" is a continuous part of the arrays.
2111 Here is the example on how the iterator can be used to normalize 3D histogram:
2114 void normalizeColorHist(Mat& hist)
2117 // intialize iterator (the style is different from STL).
2118 // after initialization the iterator will contain
2119 // the number of slices or planes
2120 // the iterator will go through
2121 Mat* arrays[] = { &hist, 0 };
2123 NAryMatIterator it(arrays, planes);
2125 // iterate through the matrix. on each iteration
2126 // it.planes[i] (of type Mat) will be set to the current plane of
2127 // i-th n-dim matrix passed to the iterator constructor.
2128 for(int p = 0; p < it.nplanes; p++, ++it)
2129 s += sum(it.planes[0])[0];
2130 it = NAryMatIterator(hist);
2132 for(int p = 0; p < it.nplanes; p++, ++it)
2135 // this is a shorter implementation of the above
2136 // using built-in operations on Mat
2137 double s = sum(hist)[0];
2138 hist.convertTo(hist, hist.type(), 1./s, 0);
2140 // and this is even shorter one
2141 // (assuming that the histogram elements are non-negative)
2142 normalize(hist, hist, 1, 0, NORM_L1);
2147 You can iterate through several matrices simultaneously as long as they have the same geometry
2148 (dimensionality and all the dimension sizes are the same), which is useful for binary
2149 and n-ary operations on such matrices. Just pass those matrices to cv::MatNDIterator.
2150 Then, during the iteration it.planes[0], it.planes[1], ... will
2151 be the slices of the corresponding matrices
2153 class CV_EXPORTS NAryMatIterator
2156 //! the default constructor
2158 //! the full constructor taking arbitrary number of n-dim matrices
2159 NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1);
2160 //! the full constructor taking arbitrary number of n-dim matrices
2161 NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1);
2162 //! the separate iterator initialization method
2163 void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1);
2165 //! proceeds to the next plane of every iterated matrix
2166 NAryMatIterator& operator ++();
2167 //! proceeds to the next plane of every iterated matrix (postfix increment operator)
2168 NAryMatIterator operator ++(int);
2170 //! the iterated arrays
2172 //! the current planes
2176 //! the number of arrays
2178 //! the number of hyper-planes that the iterator steps through
2180 //! the size of each segment (in elements)
2189 ///////////////////////////////// Matrix Expressions /////////////////////////////////
2191 class CV_EXPORTS MatOp
2197 virtual bool elementWise(const MatExpr& expr) const;
2198 virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0;
2199 virtual void roi(const MatExpr& expr, const Range& rowRange,
2200 const Range& colRange, MatExpr& res) const;
2201 virtual void diag(const MatExpr& expr, int d, MatExpr& res) const;
2202 virtual void augAssignAdd(const MatExpr& expr, Mat& m) const;
2203 virtual void augAssignSubtract(const MatExpr& expr, Mat& m) const;
2204 virtual void augAssignMultiply(const MatExpr& expr, Mat& m) const;
2205 virtual void augAssignDivide(const MatExpr& expr, Mat& m) const;
2206 virtual void augAssignAnd(const MatExpr& expr, Mat& m) const;
2207 virtual void augAssignOr(const MatExpr& expr, Mat& m) const;
2208 virtual void augAssignXor(const MatExpr& expr, Mat& m) const;
2210 virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
2211 virtual void add(const MatExpr& expr1, const Scalar& s, MatExpr& res) const;
2213 virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
2214 virtual void subtract(const Scalar& s, const MatExpr& expr, MatExpr& res) const;
2216 virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
2217 virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const;
2219 virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
2220 virtual void divide(double s, const MatExpr& expr, MatExpr& res) const;
2222 virtual void abs(const MatExpr& expr, MatExpr& res) const;
2224 virtual void transpose(const MatExpr& expr, MatExpr& res) const;
2225 virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
2226 virtual void invert(const MatExpr& expr, int method, MatExpr& res) const;
2228 virtual Size size(const MatExpr& expr) const;
2229 virtual int type(const MatExpr& expr) const;
2233 class CV_EXPORTS MatExpr
2237 explicit MatExpr(const Mat& m);
2239 MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(),
2240 const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar& _s = Scalar());
2242 operator Mat() const;
2243 template<typename _Tp> operator Mat_<_Tp>() const;
2248 MatExpr row(int y) const;
2249 MatExpr col(int x) const;
2250 MatExpr diag(int d = 0) const;
2251 MatExpr operator()( const Range& rowRange, const Range& colRange ) const;
2252 MatExpr operator()( const Rect& roi ) const;
2255 MatExpr inv(int method = DECOMP_LU) const;
2256 MatExpr mul(const MatExpr& e, double scale=1) const;
2257 MatExpr mul(const Mat& m, double scale=1) const;
2259 Mat cross(const Mat& m) const;
2260 double dot(const Mat& m) const;
2271 CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b);
2272 CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s);
2273 CV_EXPORTS MatExpr operator + (const Scalar& s, const Mat& a);
2274 CV_EXPORTS MatExpr operator + (const MatExpr& e, const Mat& m);
2275 CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e);
2276 CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar& s);
2277 CV_EXPORTS MatExpr operator + (const Scalar& s, const MatExpr& e);
2278 CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2);
2280 CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b);
2281 CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar& s);
2282 CV_EXPORTS MatExpr operator - (const Scalar& s, const Mat& a);
2283 CV_EXPORTS MatExpr operator - (const MatExpr& e, const Mat& m);
2284 CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e);
2285 CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar& s);
2286 CV_EXPORTS MatExpr operator - (const Scalar& s, const MatExpr& e);
2287 CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2);
2289 CV_EXPORTS MatExpr operator - (const Mat& m);
2290 CV_EXPORTS MatExpr operator - (const MatExpr& e);
2292 CV_EXPORTS MatExpr operator * (const Mat& a, const Mat& b);
2293 CV_EXPORTS MatExpr operator * (const Mat& a, double s);
2294 CV_EXPORTS MatExpr operator * (double s, const Mat& a);
2295 CV_EXPORTS MatExpr operator * (const MatExpr& e, const Mat& m);
2296 CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e);
2297 CV_EXPORTS MatExpr operator * (const MatExpr& e, double s);
2298 CV_EXPORTS MatExpr operator * (double s, const MatExpr& e);
2299 CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2);
2301 CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b);
2302 CV_EXPORTS MatExpr operator / (const Mat& a, double s);
2303 CV_EXPORTS MatExpr operator / (double s, const Mat& a);
2304 CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m);
2305 CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e);
2306 CV_EXPORTS MatExpr operator / (const MatExpr& e, double s);
2307 CV_EXPORTS MatExpr operator / (double s, const MatExpr& e);
2308 CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2);
2310 CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b);
2311 CV_EXPORTS MatExpr operator < (const Mat& a, double s);
2312 CV_EXPORTS MatExpr operator < (double s, const Mat& a);
2314 CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b);
2315 CV_EXPORTS MatExpr operator <= (const Mat& a, double s);
2316 CV_EXPORTS MatExpr operator <= (double s, const Mat& a);
2318 CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b);
2319 CV_EXPORTS MatExpr operator == (const Mat& a, double s);
2320 CV_EXPORTS MatExpr operator == (double s, const Mat& a);
2322 CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b);
2323 CV_EXPORTS MatExpr operator != (const Mat& a, double s);
2324 CV_EXPORTS MatExpr operator != (double s, const Mat& a);
2326 CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b);
2327 CV_EXPORTS MatExpr operator >= (const Mat& a, double s);
2328 CV_EXPORTS MatExpr operator >= (double s, const Mat& a);
2330 CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b);
2331 CV_EXPORTS MatExpr operator > (const Mat& a, double s);
2332 CV_EXPORTS MatExpr operator > (double s, const Mat& a);
2334 CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b);
2335 CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s);
2336 CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a);
2338 CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b);
2339 CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar& s);
2340 CV_EXPORTS MatExpr operator | (const Scalar& s, const Mat& a);
2342 CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b);
2343 CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s);
2344 CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a);
2346 CV_EXPORTS MatExpr operator ~(const Mat& m);
2348 CV_EXPORTS MatExpr min(const Mat& a, const Mat& b);
2349 CV_EXPORTS MatExpr min(const Mat& a, double s);
2350 CV_EXPORTS MatExpr min(double s, const Mat& a);
2352 CV_EXPORTS MatExpr max(const Mat& a, const Mat& b);
2353 CV_EXPORTS MatExpr max(const Mat& a, double s);
2354 CV_EXPORTS MatExpr max(double s, const Mat& a);
2356 CV_EXPORTS MatExpr abs(const Mat& m);
2357 CV_EXPORTS MatExpr abs(const MatExpr& e);
2361 #include "opencv2/core/mat.inl.hpp"
2363 #endif // __OPENCV_CORE_MAT_HPP__