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 int cols(int i=-1) const;
122 virtual int rows(int i=-1) const;
123 virtual Size size(int i=-1) const;
124 virtual int sizend(int* sz, int i=-1) const;
125 virtual bool sameSize(const _InputArray& arr) const;
126 virtual size_t total(int i=-1) const;
127 virtual int type(int i=-1) const;
128 virtual int depth(int i=-1) const;
129 virtual int channels(int i=-1) const;
130 virtual bool isContinuous(int i=-1) const;
131 virtual bool isSubmatrix(int i=-1) const;
132 virtual bool empty() const;
133 virtual void copyTo(const _OutputArray& arr) const;
134 virtual size_t offset(int i=-1) const;
135 virtual size_t step(int i=-1) const;
138 bool isMatVector() const;
139 bool isUMatVector() const;
142 virtual ~_InputArray();
149 void init(int _flags, const void* _obj);
150 void init(int _flags, const void* _obj, Size _sz);
155 Proxy datatype for passing Mat's and vector<>'s as input parameters
157 class CV_EXPORTS _OutputArray : public _InputArray
162 DEPTH_MASK_8U = 1 << CV_8U,
163 DEPTH_MASK_8S = 1 << CV_8S,
164 DEPTH_MASK_16U = 1 << CV_16U,
165 DEPTH_MASK_16S = 1 << CV_16S,
166 DEPTH_MASK_32S = 1 << CV_32S,
167 DEPTH_MASK_32F = 1 << CV_32F,
168 DEPTH_MASK_64F = 1 << CV_64F,
169 DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1,
170 DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S,
171 DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F
175 _OutputArray(int _flags, void* _obj);
176 _OutputArray(Mat& m);
177 _OutputArray(std::vector<Mat>& vec);
178 _OutputArray(cuda::GpuMat& d_mat);
179 _OutputArray(ogl::Buffer& buf);
180 _OutputArray(cuda::CudaMem& cuda_mem);
181 template<typename _Tp> _OutputArray(cudev::GpuMat_<_Tp>& m);
182 template<typename _Tp> _OutputArray(std::vector<_Tp>& vec);
183 template<typename _Tp> _OutputArray(std::vector<std::vector<_Tp> >& vec);
184 template<typename _Tp> _OutputArray(std::vector<Mat_<_Tp> >& vec);
185 template<typename _Tp> _OutputArray(Mat_<_Tp>& m);
186 template<typename _Tp> _OutputArray(_Tp* vec, int n);
187 template<typename _Tp, int m, int n> _OutputArray(Matx<_Tp, m, n>& matx);
188 _OutputArray(UMat& m);
189 _OutputArray(std::vector<UMat>& vec);
191 _OutputArray(const Mat& m);
192 _OutputArray(const std::vector<Mat>& vec);
193 _OutputArray(const cuda::GpuMat& d_mat);
194 _OutputArray(const ogl::Buffer& buf);
195 _OutputArray(const cuda::CudaMem& cuda_mem);
196 template<typename _Tp> _OutputArray(const cudev::GpuMat_<_Tp>& m);
197 template<typename _Tp> _OutputArray(const std::vector<_Tp>& vec);
198 template<typename _Tp> _OutputArray(const std::vector<std::vector<_Tp> >& vec);
199 template<typename _Tp> _OutputArray(const std::vector<Mat_<_Tp> >& vec);
200 template<typename _Tp> _OutputArray(const Mat_<_Tp>& m);
201 template<typename _Tp> _OutputArray(const _Tp* vec, int n);
202 template<typename _Tp, int m, int n> _OutputArray(const Matx<_Tp, m, n>& matx);
203 _OutputArray(const UMat& m);
204 _OutputArray(const std::vector<UMat>& vec);
206 virtual bool fixedSize() const;
207 virtual bool fixedType() const;
208 virtual bool needed() const;
209 virtual Mat& getMatRef(int i=-1) const;
210 virtual UMat& getUMatRef(int i=-1) const;
211 virtual cuda::GpuMat& getGpuMatRef() const;
212 virtual ogl::Buffer& getOGlBufferRef() const;
213 virtual cuda::CudaMem& getCudaMemRef() const;
214 virtual void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
215 virtual void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
216 virtual void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
217 virtual void createSameSize(const _InputArray& arr, int mtype) const;
218 virtual void release() const;
219 virtual void clear() const;
220 virtual void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const;
224 class CV_EXPORTS _InputOutputArray : public _OutputArray
228 _InputOutputArray(int _flags, void* _obj);
229 _InputOutputArray(Mat& m);
230 _InputOutputArray(std::vector<Mat>& vec);
231 _InputOutputArray(cuda::GpuMat& d_mat);
232 _InputOutputArray(ogl::Buffer& buf);
233 _InputOutputArray(cuda::CudaMem& cuda_mem);
234 template<typename _Tp> _InputOutputArray(cudev::GpuMat_<_Tp>& m);
235 template<typename _Tp> _InputOutputArray(std::vector<_Tp>& vec);
236 template<typename _Tp> _InputOutputArray(std::vector<std::vector<_Tp> >& vec);
237 template<typename _Tp> _InputOutputArray(std::vector<Mat_<_Tp> >& vec);
238 template<typename _Tp> _InputOutputArray(Mat_<_Tp>& m);
239 template<typename _Tp> _InputOutputArray(_Tp* vec, int n);
240 template<typename _Tp, int m, int n> _InputOutputArray(Matx<_Tp, m, n>& matx);
241 _InputOutputArray(UMat& m);
242 _InputOutputArray(std::vector<UMat>& vec);
244 _InputOutputArray(const Mat& m);
245 _InputOutputArray(const std::vector<Mat>& vec);
246 _InputOutputArray(const cuda::GpuMat& d_mat);
247 _InputOutputArray(const ogl::Buffer& buf);
248 _InputOutputArray(const cuda::CudaMem& cuda_mem);
249 template<typename _Tp> _InputOutputArray(const cudev::GpuMat_<_Tp>& m);
250 template<typename _Tp> _InputOutputArray(const std::vector<_Tp>& vec);
251 template<typename _Tp> _InputOutputArray(const std::vector<std::vector<_Tp> >& vec);
252 template<typename _Tp> _InputOutputArray(const std::vector<Mat_<_Tp> >& vec);
253 template<typename _Tp> _InputOutputArray(const Mat_<_Tp>& m);
254 template<typename _Tp> _InputOutputArray(const _Tp* vec, int n);
255 template<typename _Tp, int m, int n> _InputOutputArray(const Matx<_Tp, m, n>& matx);
256 _InputOutputArray(const UMat& m);
257 _InputOutputArray(const std::vector<UMat>& vec);
260 typedef const _InputArray& InputArray;
261 typedef InputArray InputArrayOfArrays;
262 typedef const _OutputArray& OutputArray;
263 typedef OutputArray OutputArrayOfArrays;
264 typedef const _InputOutputArray& InputOutputArray;
265 typedef InputOutputArray InputOutputArrayOfArrays;
267 CV_EXPORTS InputOutputArray noArray();
269 /////////////////////////////////// MatAllocator //////////////////////////////////////
271 //! Usage flags for allocator
276 // default allocation policy is platform and usage specific
277 USAGE_ALLOCATE_HOST_MEMORY = 1 << 0,
278 USAGE_ALLOCATE_DEVICE_MEMORY = 1 << 1,
280 __UMAT_USAGE_FLAGS_32BIT = 0x7fffffff // Binary compatibility hint
283 struct CV_EXPORTS UMatData;
286 Custom array allocator
289 class CV_EXPORTS MatAllocator
293 virtual ~MatAllocator() {}
295 // let's comment it off for now to detect and fix all the uses of allocator
296 //virtual void allocate(int dims, const int* sizes, int type, int*& refcount,
297 // uchar*& datastart, uchar*& data, size_t* step) = 0;
298 //virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0;
299 virtual UMatData* allocate(int dims, const int* sizes, int type,
300 void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const = 0;
301 virtual bool allocate(UMatData* data, int accessflags, UMatUsageFlags usageFlags) const = 0;
302 virtual void deallocate(UMatData* data) const = 0;
303 virtual void map(UMatData* data, int accessflags) const;
304 virtual void unmap(UMatData* data) const;
305 virtual void download(UMatData* data, void* dst, int dims, const size_t sz[],
306 const size_t srcofs[], const size_t srcstep[],
307 const size_t dststep[]) const;
308 virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[],
309 const size_t dstofs[], const size_t dststep[],
310 const size_t srcstep[]) const;
311 virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[],
312 const size_t srcofs[], const size_t srcstep[],
313 const size_t dstofs[], const size_t dststep[], bool sync) const;
315 // default implementation returns DummyBufferPoolController
316 virtual BufferPoolController* getBufferPoolController() const;
320 //////////////////////////////// MatCommaInitializer //////////////////////////////////
323 Comma-separated Matrix Initializer
325 The class instances are usually not created explicitly.
326 Instead, they are created on "matrix << firstValue" operator.
328 The sample below initializes 2x2 rotation matrix:
331 double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180);
332 Mat R = (Mat_<double>(2,2) << a, -b, b, a);
335 template<typename _Tp> class MatCommaInitializer_
338 //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat
339 MatCommaInitializer_(Mat_<_Tp>* _m);
340 //! the operator that takes the next value and put it to the matrix
341 template<typename T2> MatCommaInitializer_<_Tp>& operator , (T2 v);
342 //! another form of conversion operator
343 operator Mat_<_Tp>() const;
345 MatIterator_<_Tp> it;
349 /////////////////////////////////////// Mat ///////////////////////////////////////////
351 // note that umatdata might be allocated together
352 // with the matrix data, not as a separate object.
353 // therefore, it does not have constructor or destructor;
354 // it should be explicitly initialized using init().
355 struct CV_EXPORTS UMatData
357 enum { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2,
358 DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24,
360 UMatData(const MatAllocator* allocator);
363 // provide atomic access to the structure
367 bool hostCopyObsolete() const;
368 bool deviceCopyObsolete() const;
369 bool copyOnMap() const;
370 bool tempUMat() const;
371 bool tempCopiedUMat() const;
372 void markHostCopyObsolete(bool flag);
373 void markDeviceCopyObsolete(bool flag);
375 const MatAllocator* prevAllocator;
376 const MatAllocator* currAllocator;
381 size_t size, capacity;
390 struct CV_EXPORTS UMatDataAutoLock
392 UMatDataAutoLock(UMatData* u);
398 struct CV_EXPORTS MatSize
401 Size operator()() const;
402 const int& operator[](int i) const;
403 int& operator[](int i);
404 operator const int*() const;
405 bool operator == (const MatSize& sz) const;
406 bool operator != (const MatSize& sz) const;
411 struct CV_EXPORTS MatStep
415 const size_t& operator[](int i) const;
416 size_t& operator[](int i);
417 operator size_t() const;
418 MatStep& operator = (size_t s);
423 MatStep& operator = (const MatStep&);
427 The n-dimensional matrix class.
429 The class represents an n-dimensional dense numerical array that can act as
430 a matrix, image, optical flow map, 3-focal tensor etc.
431 It is very similar to CvMat and CvMatND types from earlier versions of OpenCV,
432 and similarly to those types, the matrix can be multi-channel. It also fully supports ROI mechanism.
434 There are many different ways to create cv::Mat object. Here are the some popular ones:
436 <li> using cv::Mat::create(nrows, ncols, type) method or
437 the similar constructor cv::Mat::Mat(nrows, ncols, type[, fill_value]) constructor.
438 A new matrix of the specified size and specifed type will be allocated.
439 "type" has the same meaning as in cvCreateMat function,
440 e.g. CV_8UC1 means 8-bit single-channel matrix, CV_32FC2 means 2-channel (i.e. complex)
441 floating-point matrix etc:
444 // make 7x7 complex matrix filled with 1+3j.
445 cv::Mat M(7,7,CV_32FC2,Scalar(1,3));
446 // and now turn M to 100x60 15-channel 8-bit matrix.
447 // The old content will be deallocated
448 M.create(100,60,CV_8UC(15));
451 As noted in the introduction of this chapter, Mat::create()
452 will only allocate a new matrix when the current matrix dimensionality
453 or type are different from the specified.
455 <li> by using a copy constructor or assignment operator, where on the right side it can
456 be a matrix or expression, see below. Again, as noted in the introduction,
457 matrix assignment is O(1) operation because it only copies the header
458 and increases the reference counter. cv::Mat::clone() method can be used to get a full
459 (a.k.a. deep) copy of the matrix when you need it.
461 <li> by constructing a header for a part of another matrix. It can be a single row, single column,
462 several rows, several columns, rectangular region in the matrix (called a minor in algebra) or
463 a diagonal. Such operations are also O(1), because the new header will reference the same data.
464 You can actually modify a part of the matrix using this feature, e.g.
467 // add 5-th row, multiplied by 3 to the 3rd row
468 M.row(3) = M.row(3) + M.row(5)*3;
470 // now copy 7-th column to the 1-st column
471 // M.col(1) = M.col(7); // this will not work
475 // create new 320x240 image
476 cv::Mat img(Size(320,240),CV_8UC3);
478 cv::Mat roi(img, Rect(10,10,100,100));
479 // fill the ROI with (0,255,0) (which is green in RGB space);
480 // the original 320x240 image will be modified
481 roi = Scalar(0,255,0);
484 Thanks to the additional cv::Mat::datastart and cv::Mat::dataend members, it is possible to
485 compute the relative sub-matrix position in the main "container" matrix using cv::Mat::locateROI():
488 Mat A = Mat::eye(10, 10, CV_32S);
489 // extracts A columns, 1 (inclusive) to 3 (exclusive).
490 Mat B = A(Range::all(), Range(1, 3));
491 // extracts B rows, 5 (inclusive) to 9 (exclusive).
492 // that is, C ~ A(Range(5, 9), Range(1, 3))
493 Mat C = B(Range(5, 9), Range::all());
494 Size size; Point ofs;
495 C.locateROI(size, ofs);
496 // size will be (width=10,height=10) and the ofs will be (x=1, y=5)
499 As in the case of whole matrices, if you need a deep copy, use cv::Mat::clone() method
500 of the extracted sub-matrices.
502 <li> by making a header for user-allocated-data. It can be useful for
504 <li> processing "foreign" data using OpenCV (e.g. when you implement
505 a DirectShow filter or a processing module for gstreamer etc.), e.g.
508 void process_video_frame(const unsigned char* pixels,
509 int width, int height, int step)
511 cv::Mat img(height, width, CV_8UC3, pixels, step);
512 cv::GaussianBlur(img, img, cv::Size(7,7), 1.5, 1.5);
516 <li> for quick initialization of small matrices and/or super-fast element access
519 double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
520 cv::Mat M = cv::Mat(3, 3, CV_64F, m).inv();
524 partial yet very common cases of this "user-allocated data" case are conversions
525 from CvMat and IplImage to cv::Mat. For this purpose there are special constructors
526 taking pointers to CvMat or IplImage and the optional
527 flag indicating whether to copy the data or not.
529 Backward conversion from cv::Mat to CvMat or IplImage is provided via cast operators
530 cv::Mat::operator CvMat() an cv::Mat::operator IplImage().
531 The operators do not copy the data.
535 IplImage* img = cvLoadImage("greatwave.jpg", 1);
536 Mat mtx(img); // convert IplImage* -> cv::Mat
537 CvMat oldmat = mtx; // convert cv::Mat -> CvMat
538 CV_Assert(oldmat.cols == img->width && oldmat.rows == img->height &&
539 oldmat.data.ptr == (uchar*)img->imageData && oldmat.step == img->widthStep);
542 <li> by using MATLAB-style matrix initializers, cv::Mat::zeros(), cv::Mat::ones(), cv::Mat::eye(), e.g.:
545 // create a double-precision identity martix and add it to M.
546 M += Mat::eye(M.rows, M.cols, CV_64F);
549 <li> by using comma-separated initializer:
552 // create 3x3 double-precision identity matrix
553 Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
556 here we first call constructor of cv::Mat_ class (that we describe further) with the proper matrix,
557 and then we just put "<<" operator followed by comma-separated values that can be constants,
558 variables, expressions etc. Also, note the extra parentheses that are needed to avoid compiler errors.
562 Once matrix is created, it will be automatically managed by using reference-counting mechanism
563 (unless the matrix header is built on top of user-allocated data,
564 in which case you should handle the data by yourself).
565 The matrix data will be deallocated when no one points to it;
566 if you want to release the data pointed by a matrix header before the matrix destructor is called,
567 use cv::Mat::release().
569 The next important thing to learn about the matrix class is element access. Here is how the matrix is stored.
570 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,
571 cv::Mat::rows contains the number of matrix rows and cv::Mat::cols - the number of matrix columns. There is yet another member,
572 cv::Mat::step that is used to actually compute address of a matrix element. cv::Mat::step is needed because the matrix can be
573 a part of another matrix or because there can some padding space in the end of each row for a proper alignment.
577 Given these parameters, address of the matrix element M_{ij} is computed as following:
579 addr(M_{ij})=M.data + M.step*i + j*M.elemSize()
581 if you know the matrix element type, e.g. it is float, then you can use cv::Mat::at() method:
583 addr(M_{ij})=&M.at<float>(i,j)
585 (where & is used to convert the reference returned by cv::Mat::at() to a pointer).
586 if you need to process a whole row of matrix, the most efficient way is to get
587 the pointer to the row first, and then just use plain C operator []:
590 // compute sum of positive matrix elements
591 // (assuming that M is double-precision matrix)
593 for(int i = 0; i < M.rows; i++)
595 const double* Mi = M.ptr<double>(i);
596 for(int j = 0; j < M.cols; j++)
597 sum += std::max(Mi[j], 0.);
601 Some operations, like the above one, do not actually depend on the matrix shape,
602 they just process elements of a matrix one by one (or elements from multiple matrices
603 that are sitting in the same place, e.g. matrix addition). Such operations are called
604 element-wise and it makes sense to check whether all the input/output matrices are continuous,
605 i.e. have no gaps in the end of each row, and if yes, process them as a single long row:
608 // compute sum of positive matrix elements, optimized variant
610 int cols = M.cols, rows = M.rows;
616 for(int i = 0; i < rows; i++)
618 const double* Mi = M.ptr<double>(i);
619 for(int j = 0; j < cols; j++)
620 sum += std::max(Mi[j], 0.);
623 in the case of continuous matrix the outer loop body will be executed just once,
624 so the overhead will be smaller, which will be especially noticeable in the case of small matrices.
626 Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:
628 // compute sum of positive matrix elements, iterator-based variant
630 MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
631 for(; it != it_end; ++it)
632 sum += std::max(*it, 0.);
635 The matrix iterators are random-access iterators, so they can be passed
636 to any STL algorithm, including std::sort().
641 //! default constructor
643 //! constructs 2D matrix of the specified size and type
644 // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
645 Mat(int rows, int cols, int type);
646 Mat(Size size, int type);
647 //! constucts 2D matrix and fills it with the specified value _s.
648 Mat(int rows, int cols, int type, const Scalar& s);
649 Mat(Size size, int type, const Scalar& s);
651 //! constructs n-dimensional matrix
652 Mat(int ndims, const int* sizes, int type);
653 Mat(int ndims, const int* sizes, int type, const Scalar& s);
657 //! constructor for matrix headers pointing to user-allocated data
658 Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP);
659 Mat(Size size, int type, void* data, size_t step=AUTO_STEP);
660 Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0);
662 //! creates a matrix header for a part of the bigger matrix
663 Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all());
664 Mat(const Mat& m, const Rect& roi);
665 Mat(const Mat& m, const Range* ranges);
666 //! builds matrix from std::vector with or without copying the data
667 template<typename _Tp> explicit Mat(const std::vector<_Tp>& vec, bool copyData=false);
668 //! builds matrix from cv::Vec; the data is copied by default
669 template<typename _Tp, int n> explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true);
670 //! builds matrix from cv::Matx; the data is copied by default
671 template<typename _Tp, int m, int n> explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
672 //! builds matrix from a 2D point
673 template<typename _Tp> explicit Mat(const Point_<_Tp>& pt, bool copyData=true);
674 //! builds matrix from a 3D point
675 template<typename _Tp> explicit Mat(const Point3_<_Tp>& pt, bool copyData=true);
676 //! builds matrix from comma initializer
677 template<typename _Tp> explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer);
679 //! download data from GpuMat
680 explicit Mat(const cuda::GpuMat& m);
682 //! destructor - calls release()
684 //! assignment operators
685 Mat& operator = (const Mat& m);
686 Mat& operator = (const MatExpr& expr);
688 //! retrieve UMat from Mat
689 UMat getUMat(int accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const;
691 //! returns a new matrix header for the specified row
692 Mat row(int y) const;
693 //! returns a new matrix header for the specified column
694 Mat col(int x) const;
695 //! ... for the specified row span
696 Mat rowRange(int startrow, int endrow) const;
697 Mat rowRange(const Range& r) const;
698 //! ... for the specified column span
699 Mat colRange(int startcol, int endcol) const;
700 Mat colRange(const Range& r) const;
701 //! ... for the specified diagonal
702 // (d=0 - the main diagonal,
703 // >0 - a diagonal from the lower half,
704 // <0 - a diagonal from the upper half)
705 Mat diag(int d=0) const;
706 //! constructs a square diagonal matrix which main diagonal is vector "d"
707 static Mat diag(const Mat& d);
709 //! returns deep copy of the matrix, i.e. the data is copied
711 //! copies the matrix content to "m".
712 // It calls m.create(this->size(), this->type()).
713 void copyTo( OutputArray m ) const;
714 //! copies those matrix elements to "m" that are marked with non-zero mask elements.
715 void copyTo( OutputArray m, InputArray mask ) const;
716 //! converts matrix to another datatype with optional scalng. See cvConvertScale.
717 void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
719 void assignTo( Mat& m, int type=-1 ) const;
721 //! sets every matrix element to s
722 Mat& operator = (const Scalar& s);
723 //! sets some of the matrix elements to s, according to the mask
724 Mat& setTo(InputArray value, InputArray mask=noArray());
725 //! creates alternative matrix header for the same data, with different
726 // number of channels and/or different number of rows. see cvReshape.
727 Mat reshape(int cn, int rows=0) const;
728 Mat reshape(int cn, int newndims, const int* newsz) const;
730 //! matrix transposition by means of matrix expressions
732 //! matrix inversion by means of matrix expressions
733 MatExpr inv(int method=DECOMP_LU) const;
734 //! per-element matrix multiplication by means of matrix expressions
735 MatExpr mul(InputArray m, double scale=1) const;
737 //! computes cross-product of 2 3D vectors
738 Mat cross(InputArray m) const;
739 //! computes dot-product
740 double dot(InputArray m) const;
742 //! Matlab-style matrix initialization
743 static MatExpr zeros(int rows, int cols, int type);
744 static MatExpr zeros(Size size, int type);
745 static MatExpr zeros(int ndims, const int* sz, int type);
746 static MatExpr ones(int rows, int cols, int type);
747 static MatExpr ones(Size size, int type);
748 static MatExpr ones(int ndims, const int* sz, int type);
749 static MatExpr eye(int rows, int cols, int type);
750 static MatExpr eye(Size size, int type);
752 //! allocates new matrix data unless the matrix already has specified size and type.
753 // previous data is unreferenced if needed.
754 void create(int rows, int cols, int type);
755 void create(Size size, int type);
756 void create(int ndims, const int* sizes, int type);
758 //! increases the reference counter; use with care to avoid memleaks
760 //! decreases reference counter;
761 // deallocates the data when reference counter reaches 0.
764 //! deallocates the matrix data
766 //! internal use function; properly re-allocates _size, _step arrays
767 void copySize(const Mat& m);
769 //! reserves enough space to fit sz hyper-planes
770 void reserve(size_t sz);
771 //! resizes matrix to the specified number of hyper-planes
772 void resize(size_t sz);
773 //! resizes matrix to the specified number of hyper-planes; initializes the newly added elements
774 void resize(size_t sz, const Scalar& s);
775 //! internal function
776 void push_back_(const void* elem);
777 //! adds element to the end of 1d matrix (or possibly multiple elements when _Tp=Mat)
778 template<typename _Tp> void push_back(const _Tp& elem);
779 template<typename _Tp> void push_back(const Mat_<_Tp>& elem);
780 void push_back(const Mat& m);
781 //! removes several hyper-planes from bottom of the matrix
782 void pop_back(size_t nelems=1);
784 //! locates matrix header within a parent matrix. See below
785 void locateROI( Size& wholeSize, Point& ofs ) const;
786 //! moves/resizes the current matrix ROI inside the parent matrix.
787 Mat& adjustROI( int dtop, int dbottom, int dleft, int dright );
788 //! extracts a rectangular sub-matrix
789 // (this is a generalized form of row, rowRange etc.)
790 Mat operator()( Range rowRange, Range colRange ) const;
791 Mat operator()( const Rect& roi ) const;
792 Mat operator()( const Range* ranges ) const;
794 // //! converts header to CvMat; no data is copied
795 // operator CvMat() const;
796 // //! converts header to CvMatND; no data is copied
797 // operator CvMatND() const;
798 // //! converts header to IplImage; no data is copied
799 // operator IplImage() const;
801 template<typename _Tp> operator std::vector<_Tp>() const;
802 template<typename _Tp, int n> operator Vec<_Tp, n>() const;
803 template<typename _Tp, int m, int n> operator Matx<_Tp, m, n>() const;
805 //! returns true iff the matrix data is continuous
806 // (i.e. when there are no gaps between successive rows).
807 // similar to CV_IS_MAT_CONT(cvmat->type)
808 bool isContinuous() const;
810 //! returns true if the matrix is a submatrix of another matrix
811 bool isSubmatrix() const;
813 //! returns element size in bytes,
814 // similar to CV_ELEM_SIZE(cvmat->type)
815 size_t elemSize() const;
816 //! returns the size of element channel in bytes.
817 size_t elemSize1() const;
818 //! returns element type, similar to CV_MAT_TYPE(cvmat->type)
820 //! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
822 //! returns element type, similar to CV_MAT_CN(cvmat->type)
823 int channels() const;
824 //! returns step/elemSize1()
825 size_t step1(int i=0) const;
826 //! returns true if matrix data is NULL
828 //! returns the total number of matrix elements
829 size_t total() const;
831 //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
832 int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
834 //! returns pointer to i0-th submatrix along the dimension #0
835 uchar* ptr(int i0=0);
836 const uchar* ptr(int i0=0) const;
838 //! returns pointer to (i0,i1) submatrix along the dimensions #0 and #1
839 uchar* ptr(int i0, int i1);
840 const uchar* ptr(int i0, int i1) const;
842 //! returns pointer to (i0,i1,i3) submatrix along the dimensions #0, #1, #2
843 uchar* ptr(int i0, int i1, int i2);
844 const uchar* ptr(int i0, int i1, int i2) const;
846 //! returns pointer to the matrix element
847 uchar* ptr(const int* idx);
848 //! returns read-only pointer to the matrix element
849 const uchar* ptr(const int* idx) const;
851 template<int n> uchar* ptr(const Vec<int, n>& idx);
852 template<int n> const uchar* ptr(const Vec<int, n>& idx) const;
854 //! template version of the above method
855 template<typename _Tp> _Tp* ptr(int i0=0);
856 template<typename _Tp> const _Tp* ptr(int i0=0) const;
858 template<typename _Tp> _Tp* ptr(int i0, int i1);
859 template<typename _Tp> const _Tp* ptr(int i0, int i1) const;
861 template<typename _Tp> _Tp* ptr(int i0, int i1, int i2);
862 template<typename _Tp> const _Tp* ptr(int i0, int i1, int i2) const;
864 template<typename _Tp> _Tp* ptr(const int* idx);
865 template<typename _Tp> const _Tp* ptr(const int* idx) const;
867 template<typename _Tp, int n> _Tp* ptr(const Vec<int, n>& idx);
868 template<typename _Tp, int n> const _Tp* ptr(const Vec<int, n>& idx) const;
870 //! the same as above, with the pointer dereferencing
871 template<typename _Tp> _Tp& at(int i0=0);
872 template<typename _Tp> const _Tp& at(int i0=0) const;
874 template<typename _Tp> _Tp& at(int i0, int i1);
875 template<typename _Tp> const _Tp& at(int i0, int i1) const;
877 template<typename _Tp> _Tp& at(int i0, int i1, int i2);
878 template<typename _Tp> const _Tp& at(int i0, int i1, int i2) const;
880 template<typename _Tp> _Tp& at(const int* idx);
881 template<typename _Tp> const _Tp& at(const int* idx) const;
883 template<typename _Tp, int n> _Tp& at(const Vec<int, n>& idx);
884 template<typename _Tp, int n> const _Tp& at(const Vec<int, n>& idx) const;
886 //! special versions for 2D arrays (especially convenient for referencing image pixels)
887 template<typename _Tp> _Tp& at(Point pt);
888 template<typename _Tp> const _Tp& at(Point pt) const;
890 //! template methods for iteration over matrix elements.
891 // the iterators take care of skipping gaps in the end of rows (if any)
892 template<typename _Tp> MatIterator_<_Tp> begin();
893 template<typename _Tp> MatIterator_<_Tp> end();
894 template<typename _Tp> MatConstIterator_<_Tp> begin() const;
895 template<typename _Tp> MatConstIterator_<_Tp> end() const;
897 enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
898 enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
900 /*! includes several bit-fields:
901 - the magic signature
907 //! the matrix dimensionality, >= 2
909 //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
911 //! pointer to the data
914 //! helper fields used in locateROI and adjustROI
920 MatAllocator* allocator;
921 //! and the standard allocator
922 static MatAllocator* getStdAllocator();
924 //! interaction with UMat
934 ///////////////////////////////// Mat_<_Tp> ////////////////////////////////////
937 Template matrix class derived from Mat
939 The class Mat_ is a "thin" template wrapper on top of cv::Mat. It does not have any extra data fields,
940 nor it or cv::Mat have any virtual methods and thus references or pointers to these two classes
941 can be safely converted one to another. But do it with care, for example:
944 // create 100x100 8-bit matrix
945 Mat M(100,100,CV_8U);
946 // this will compile fine. no any data conversion will be done.
947 Mat_<float>& M1 = (Mat_<float>&)M;
948 // the program will likely crash at the statement below
952 While cv::Mat is sufficient in most cases, cv::Mat_ can be more convenient if you use a lot of element
953 access operations and if you know matrix type at compile time.
954 Note that cv::Mat::at<_Tp>(int y, int x) and cv::Mat_<_Tp>::operator ()(int y, int x) do absolutely the
955 same thing and run at the same speed, but the latter is certainly shorter:
958 Mat_<double> M(20,20);
959 for(int i = 0; i < M.rows; i++)
960 for(int j = 0; j < M.cols; j++)
964 cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
967 It is easy to use Mat_ for multi-channel images/matrices - just pass cv::Vec as cv::Mat_ template parameter:
970 // allocate 320x240 color image and fill it with green (in RGB space)
971 Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
972 // now draw a diagonal white line
973 for(int i = 0; i < 100; i++)
974 img(i,i)=Vec3b(255,255,255);
975 // and now modify the 2nd (red) channel of each pixel
976 for(int i = 0; i < img.rows; i++)
977 for(int j = 0; j < img.cols; j++)
978 img(i,j)[2] ^= (uchar)(i ^ j); // img(y,x)[c] accesses c-th channel of the pixel (x,y)
981 template<typename _Tp> class Mat_ : public Mat
984 typedef _Tp value_type;
985 typedef typename DataType<_Tp>::channel_type channel_type;
986 typedef MatIterator_<_Tp> iterator;
987 typedef MatConstIterator_<_Tp> const_iterator;
989 //! default constructor
991 //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type)
992 Mat_(int _rows, int _cols);
993 //! constructor that sets each matrix element to specified value
994 Mat_(int _rows, int _cols, const _Tp& value);
995 //! equivalent to Mat(_size, DataType<_Tp>::type)
996 explicit Mat_(Size _size);
997 //! constructor that sets each matrix element to specified value
998 Mat_(Size _size, const _Tp& value);
999 //! n-dim array constructor
1000 Mat_(int _ndims, const int* _sizes);
1001 //! n-dim array constructor that sets each matrix element to specified value
1002 Mat_(int _ndims, const int* _sizes, const _Tp& value);
1003 //! copy/conversion contructor. If m is of different type, it's converted
1005 //! copy constructor
1006 Mat_(const Mat_& m);
1007 //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type
1008 Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP);
1009 //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type
1010 Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0);
1011 //! selects a submatrix
1012 Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all());
1013 //! selects a submatrix
1014 Mat_(const Mat_& m, const Rect& roi);
1015 //! selects a submatrix, n-dim version
1016 Mat_(const Mat_& m, const Range* ranges);
1017 //! from a matrix expression
1018 explicit Mat_(const MatExpr& e);
1019 //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column
1020 explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false);
1021 template<int n> explicit Mat_(const Vec<typename DataType<_Tp>::channel_type, n>& vec, bool copyData=true);
1022 template<int m, int n> explicit Mat_(const Matx<typename DataType<_Tp>::channel_type, m, n>& mtx, bool copyData=true);
1023 explicit Mat_(const Point_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
1024 explicit Mat_(const Point3_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
1025 explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer);
1027 Mat_& operator = (const Mat& m);
1028 Mat_& operator = (const Mat_& m);
1029 //! set all the elements to s.
1030 Mat_& operator = (const _Tp& s);
1031 //! assign a matrix expression
1032 Mat_& operator = (const MatExpr& e);
1034 //! iterators; they are smart enough to skip gaps in the end of rows
1037 const_iterator begin() const;
1038 const_iterator end() const;
1040 //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type)
1041 void create(int _rows, int _cols);
1042 //! equivalent to Mat::create(_size, DataType<_Tp>::type)
1043 void create(Size _size);
1044 //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type)
1045 void create(int _ndims, const int* _sizes);
1047 Mat_ cross(const Mat_& m) const;
1048 //! data type conversion
1049 template<typename T2> operator Mat_<T2>() const;
1050 //! overridden forms of Mat::row() etc.
1051 Mat_ row(int y) const;
1052 Mat_ col(int x) const;
1053 Mat_ diag(int d=0) const;
1056 //! overridden forms of Mat::elemSize() etc.
1057 size_t elemSize() const;
1058 size_t elemSize1() const;
1061 int channels() const;
1062 size_t step1(int i=0) const;
1063 //! returns step()/sizeof(_Tp)
1064 size_t stepT(int i=0) const;
1066 //! overridden forms of Mat::zeros() etc. Data type is omitted, of course
1067 static MatExpr zeros(int rows, int cols);
1068 static MatExpr zeros(Size size);
1069 static MatExpr zeros(int _ndims, const int* _sizes);
1070 static MatExpr ones(int rows, int cols);
1071 static MatExpr ones(Size size);
1072 static MatExpr ones(int _ndims, const int* _sizes);
1073 static MatExpr eye(int rows, int cols);
1074 static MatExpr eye(Size size);
1076 //! some more overriden methods
1077 Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright );
1078 Mat_ operator()( const Range& rowRange, const Range& colRange ) const;
1079 Mat_ operator()( const Rect& roi ) const;
1080 Mat_ operator()( const Range* ranges ) const;
1082 //! more convenient forms of row and element access operators
1083 _Tp* operator [](int y);
1084 const _Tp* operator [](int y) const;
1086 //! returns reference to the specified element
1087 _Tp& operator ()(const int* idx);
1088 //! returns read-only reference to the specified element
1089 const _Tp& operator ()(const int* idx) const;
1091 //! returns reference to the specified element
1092 template<int n> _Tp& operator ()(const Vec<int, n>& idx);
1093 //! returns read-only reference to the specified element
1094 template<int n> const _Tp& operator ()(const Vec<int, n>& idx) const;
1096 //! returns reference to the specified element (1D case)
1097 _Tp& operator ()(int idx0);
1098 //! returns read-only reference to the specified element (1D case)
1099 const _Tp& operator ()(int idx0) const;
1100 //! returns reference to the specified element (2D case)
1101 _Tp& operator ()(int idx0, int idx1);
1102 //! returns read-only reference to the specified element (2D case)
1103 const _Tp& operator ()(int idx0, int idx1) const;
1104 //! returns reference to the specified element (3D case)
1105 _Tp& operator ()(int idx0, int idx1, int idx2);
1106 //! returns read-only reference to the specified element (3D case)
1107 const _Tp& operator ()(int idx0, int idx1, int idx2) const;
1109 _Tp& operator ()(Point pt);
1110 const _Tp& operator ()(Point pt) const;
1112 //! conversion to vector.
1113 operator std::vector<_Tp>() const;
1114 //! conversion to Vec
1115 template<int n> operator Vec<typename DataType<_Tp>::channel_type, n>() const;
1116 //! conversion to Matx
1117 template<int m, int n> operator Matx<typename DataType<_Tp>::channel_type, m, n>() const;
1120 typedef Mat_<uchar> Mat1b;
1121 typedef Mat_<Vec2b> Mat2b;
1122 typedef Mat_<Vec3b> Mat3b;
1123 typedef Mat_<Vec4b> Mat4b;
1125 typedef Mat_<short> Mat1s;
1126 typedef Mat_<Vec2s> Mat2s;
1127 typedef Mat_<Vec3s> Mat3s;
1128 typedef Mat_<Vec4s> Mat4s;
1130 typedef Mat_<ushort> Mat1w;
1131 typedef Mat_<Vec2w> Mat2w;
1132 typedef Mat_<Vec3w> Mat3w;
1133 typedef Mat_<Vec4w> Mat4w;
1135 typedef Mat_<int> Mat1i;
1136 typedef Mat_<Vec2i> Mat2i;
1137 typedef Mat_<Vec3i> Mat3i;
1138 typedef Mat_<Vec4i> Mat4i;
1140 typedef Mat_<float> Mat1f;
1141 typedef Mat_<Vec2f> Mat2f;
1142 typedef Mat_<Vec3f> Mat3f;
1143 typedef Mat_<Vec4f> Mat4f;
1145 typedef Mat_<double> Mat1d;
1146 typedef Mat_<Vec2d> Mat2d;
1147 typedef Mat_<Vec3d> Mat3d;
1148 typedef Mat_<Vec4d> Mat4d;
1150 class CV_EXPORTS UMat
1153 //! default constructor
1154 UMat(UMatUsageFlags usageFlags = USAGE_DEFAULT);
1155 //! constructs 2D matrix of the specified size and type
1156 // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
1157 UMat(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1158 UMat(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1159 //! constucts 2D matrix and fills it with the specified value _s.
1160 UMat(int rows, int cols, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1161 UMat(Size size, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1163 //! constructs n-dimensional matrix
1164 UMat(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1165 UMat(int ndims, const int* sizes, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1167 //! copy constructor
1168 UMat(const UMat& m);
1170 //! creates a matrix header for a part of the bigger matrix
1171 UMat(const UMat& m, const Range& rowRange, const Range& colRange=Range::all());
1172 UMat(const UMat& m, const Rect& roi);
1173 UMat(const UMat& m, const Range* ranges);
1174 //! builds matrix from std::vector with or without copying the data
1175 template<typename _Tp> explicit UMat(const std::vector<_Tp>& vec, bool copyData=false);
1176 //! builds matrix from cv::Vec; the data is copied by default
1177 template<typename _Tp, int n> explicit UMat(const Vec<_Tp, n>& vec, bool copyData=true);
1178 //! builds matrix from cv::Matx; the data is copied by default
1179 template<typename _Tp, int m, int n> explicit UMat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
1180 //! builds matrix from a 2D point
1181 template<typename _Tp> explicit UMat(const Point_<_Tp>& pt, bool copyData=true);
1182 //! builds matrix from a 3D point
1183 template<typename _Tp> explicit UMat(const Point3_<_Tp>& pt, bool copyData=true);
1184 //! builds matrix from comma initializer
1185 template<typename _Tp> explicit UMat(const MatCommaInitializer_<_Tp>& commaInitializer);
1187 //! destructor - calls release()
1189 //! assignment operators
1190 UMat& operator = (const UMat& m);
1192 Mat getMat(int flags) const;
1194 //! returns a new matrix header for the specified row
1195 UMat row(int y) const;
1196 //! returns a new matrix header for the specified column
1197 UMat col(int x) const;
1198 //! ... for the specified row span
1199 UMat rowRange(int startrow, int endrow) const;
1200 UMat rowRange(const Range& r) const;
1201 //! ... for the specified column span
1202 UMat colRange(int startcol, int endcol) const;
1203 UMat colRange(const Range& r) const;
1204 //! ... for the specified diagonal
1205 // (d=0 - the main diagonal,
1206 // >0 - a diagonal from the lower half,
1207 // <0 - a diagonal from the upper half)
1208 UMat diag(int d=0) const;
1209 //! constructs a square diagonal matrix which main diagonal is vector "d"
1210 static UMat diag(const UMat& d);
1212 //! returns deep copy of the matrix, i.e. the data is copied
1214 //! copies the matrix content to "m".
1215 // It calls m.create(this->size(), this->type()).
1216 void copyTo( OutputArray m ) const;
1217 //! copies those matrix elements to "m" that are marked with non-zero mask elements.
1218 void copyTo( OutputArray m, InputArray mask ) const;
1219 //! converts matrix to another datatype with optional scalng. See cvConvertScale.
1220 void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
1222 void assignTo( UMat& m, int type=-1 ) const;
1224 //! sets every matrix element to s
1225 UMat& operator = (const Scalar& s);
1226 //! sets some of the matrix elements to s, according to the mask
1227 UMat& setTo(InputArray value, InputArray mask=noArray());
1228 //! creates alternative matrix header for the same data, with different
1229 // number of channels and/or different number of rows. see cvReshape.
1230 UMat reshape(int cn, int rows=0) const;
1231 UMat reshape(int cn, int newndims, const int* newsz) const;
1233 //! matrix transposition by means of matrix expressions
1235 //! matrix inversion by means of matrix expressions
1236 UMat inv(int method=DECOMP_LU) const;
1237 //! per-element matrix multiplication by means of matrix expressions
1238 UMat mul(InputArray m, double scale=1) const;
1240 //! computes dot-product
1241 double dot(InputArray m) const;
1243 //! Matlab-style matrix initialization
1244 static UMat zeros(int rows, int cols, int type);
1245 static UMat zeros(Size size, int type);
1246 static UMat zeros(int ndims, const int* sz, int type);
1247 static UMat ones(int rows, int cols, int type);
1248 static UMat ones(Size size, int type);
1249 static UMat ones(int ndims, const int* sz, int type);
1250 static UMat eye(int rows, int cols, int type);
1251 static UMat eye(Size size, int type);
1253 //! allocates new matrix data unless the matrix already has specified size and type.
1254 // previous data is unreferenced if needed.
1255 void create(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1256 void create(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1257 void create(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
1259 //! increases the reference counter; use with care to avoid memleaks
1261 //! decreases reference counter;
1262 // deallocates the data when reference counter reaches 0.
1265 //! deallocates the matrix data
1267 //! internal use function; properly re-allocates _size, _step arrays
1268 void copySize(const UMat& m);
1270 //! locates matrix header within a parent matrix. See below
1271 void locateROI( Size& wholeSize, Point& ofs ) const;
1272 //! moves/resizes the current matrix ROI inside the parent matrix.
1273 UMat& adjustROI( int dtop, int dbottom, int dleft, int dright );
1274 //! extracts a rectangular sub-matrix
1275 // (this is a generalized form of row, rowRange etc.)
1276 UMat operator()( Range rowRange, Range colRange ) const;
1277 UMat operator()( const Rect& roi ) const;
1278 UMat operator()( const Range* ranges ) const;
1280 //! returns true iff the matrix data is continuous
1281 // (i.e. when there are no gaps between successive rows).
1282 // similar to CV_IS_MAT_CONT(cvmat->type)
1283 bool isContinuous() const;
1285 //! returns true if the matrix is a submatrix of another matrix
1286 bool isSubmatrix() const;
1288 //! returns element size in bytes,
1289 // similar to CV_ELEM_SIZE(cvmat->type)
1290 size_t elemSize() const;
1291 //! returns the size of element channel in bytes.
1292 size_t elemSize1() const;
1293 //! returns element type, similar to CV_MAT_TYPE(cvmat->type)
1295 //! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
1297 //! returns element type, similar to CV_MAT_CN(cvmat->type)
1298 int channels() const;
1299 //! returns step/elemSize1()
1300 size_t step1(int i=0) const;
1301 //! returns true if matrix data is NULL
1303 //! returns the total number of matrix elements
1304 size_t total() const;
1306 //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
1307 int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
1309 void* handle(int accessFlags) const;
1310 void ndoffset(size_t* ofs) const;
1312 enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
1313 enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
1315 /*! includes several bit-fields:
1316 - the magic signature
1319 - number of channels
1322 //! the matrix dimensionality, >= 2
1324 //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
1327 //! custom allocator
1328 MatAllocator* allocator;
1329 UMatUsageFlags usageFlags; // usage flags for allocator
1330 //! and the standard allocator
1331 static MatAllocator* getStdAllocator();
1333 // black-box container of UMat data
1336 // offset of the submatrix (or 0)
1346 /////////////////////////// multi-dimensional sparse matrix //////////////////////////
1349 Sparse matrix class.
1351 The class represents multi-dimensional sparse numerical arrays. Such a sparse array can store elements
1352 of any type that cv::Mat is able to store. "Sparse" means that only non-zero elements
1353 are stored (though, as a result of some operations on a sparse matrix, some of its stored elements
1354 can actually become 0. It's user responsibility to detect such elements and delete them using cv::SparseMat::erase().
1355 The non-zero elements are stored in a hash table that grows when it's filled enough,
1356 so that the search time remains O(1) in average. Elements can be accessed using the following methods:
1359 <li>Query operations: cv::SparseMat::ptr() and the higher-level cv::SparseMat::ref(),
1360 cv::SparseMat::value() and cv::SparseMat::find, for example:
1363 int size[] = {10, 10, 10, 10, 10};
1364 SparseMat sparse_mat(dims, size, CV_32F);
1365 for(int i = 0; i < 1000; i++)
1368 for(int k = 0; k < dims; k++)
1369 idx[k] = rand()%sparse_mat.size(k);
1370 sparse_mat.ref<float>(idx) += 1.f;
1374 <li>Sparse matrix iterators. Like cv::Mat iterators and unlike cv::Mat iterators, the sparse matrix iterators are STL-style,
1375 that is, the iteration is done as following:
1377 // prints elements of a sparse floating-point matrix and the sum of elements.
1378 SparseMatConstIterator_<float>
1379 it = sparse_mat.begin<float>(),
1380 it_end = sparse_mat.end<float>();
1382 int dims = sparse_mat.dims();
1383 for(; it != it_end; ++it)
1385 // print element indices and the element value
1386 const Node* n = it.node();
1388 for(int i = 0; i < dims; i++)
1389 printf("%3d%c", n->idx[i], i < dims-1 ? ',' : ')');
1390 printf(": %f\n", *it);
1393 printf("Element sum is %g\n", s);
1395 If you run this loop, you will notice that elements are enumerated
1396 in no any logical order (lexicographical etc.),
1397 they come in the same order as they stored in the hash table, i.e. semi-randomly.
1399 You may collect pointers to the nodes and sort them to get the proper ordering.
1400 Note, however, that pointers to the nodes may become invalid when you add more
1401 elements to the matrix; this is because of possible buffer reallocation.
1403 <li>A combination of the above 2 methods when you need to process 2 or more sparse
1404 matrices simultaneously, e.g. this is how you can compute unnormalized
1405 cross-correlation of the 2 floating-point sparse matrices:
1407 double crossCorr(const SparseMat& a, const SparseMat& b)
1409 const SparseMat *_a = &a, *_b = &b;
1410 // if b contains less elements than a,
1411 // it's faster to iterate through b
1412 if(_a->nzcount() > _b->nzcount())
1414 SparseMatConstIterator_<float> it = _a->begin<float>(),
1415 it_end = _a->end<float>();
1417 for(; it != it_end; ++it)
1419 // take the next element from the first matrix
1421 const Node* anode = it.node();
1422 // and try to find element with the same index in the second matrix.
1423 // since the hash value depends only on the element index,
1424 // we reuse hashvalue stored in the node
1425 float bvalue = _b->value<float>(anode->idx,&anode->hashval);
1426 ccorr += avalue*bvalue;
1433 class CV_EXPORTS SparseMat
1436 typedef SparseMatIterator iterator;
1437 typedef SparseMatConstIterator const_iterator;
1439 enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 };
1441 //! the sparse matrix header
1442 struct CV_EXPORTS Hdr
1444 Hdr(int _dims, const int* _sizes, int _type);
1452 std::vector<uchar> pool;
1453 std::vector<size_t> hashtab;
1457 //! sparse matrix node - element of a hash table
1458 struct CV_EXPORTS Node
1462 //! index of the next node in the same hash table entry
1464 //! index of the matrix element
1468 //! default constructor
1470 //! creates matrix of the specified size and type
1471 SparseMat(int dims, const int* _sizes, int _type);
1472 //! copy constructor
1473 SparseMat(const SparseMat& m);
1474 //! converts dense 2d matrix to the sparse form
1476 \param m the input matrix
1478 explicit SparseMat(const Mat& m);
1479 //! converts old-style sparse matrix to the new-style. All the data is copied
1480 //SparseMat(const CvSparseMat* m);
1484 //! assignment operator. This is O(1) operation, i.e. no data is copied
1485 SparseMat& operator = (const SparseMat& m);
1486 //! equivalent to the corresponding constructor
1487 SparseMat& operator = (const Mat& m);
1489 //! creates full copy of the matrix
1490 SparseMat clone() const;
1492 //! copies all the data to the destination matrix. All the previous content of m is erased
1493 void copyTo( SparseMat& m ) const;
1494 //! converts sparse matrix to dense matrix.
1495 void copyTo( Mat& m ) const;
1496 //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type
1497 void convertTo( SparseMat& m, int rtype, double alpha=1 ) const;
1498 //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling.
1500 \param rtype The output matrix data type. When it is =-1, the output array will have the same data type as (*this)
1501 \param alpha The scale factor
1502 \param beta The optional delta added to the scaled values before the conversion
1504 void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
1507 void assignTo( SparseMat& m, int type=-1 ) const;
1509 //! reallocates sparse matrix.
1511 If the matrix already had the proper size and type,
1512 it is simply cleared with clear(), otherwise,
1513 the old matrix is released (using release()) and the new one is allocated.
1515 void create(int dims, const int* _sizes, int _type);
1516 //! sets all the sparse matrix elements to 0, which means clearing the hash table.
1518 //! manually increments the reference counter to the header.
1520 // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated.
1523 //! converts sparse matrix to the old-style representation; all the elements are copied.
1524 //operator CvSparseMat*() const;
1525 //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements)
1526 size_t elemSize() const;
1527 //! returns elemSize()/channels()
1528 size_t elemSize1() const;
1530 //! returns type of sparse matrix elements
1532 //! returns the depth of sparse matrix elements
1534 //! returns the number of channels
1535 int channels() const;
1537 //! returns the array of sizes, or NULL if the matrix is not allocated
1538 const int* size() const;
1539 //! returns the size of i-th matrix dimension (or 0)
1540 int size(int i) const;
1541 //! returns the matrix dimensionality
1543 //! returns the number of non-zero elements (=the number of hash table nodes)
1544 size_t nzcount() const;
1546 //! computes the element hash value (1D case)
1547 size_t hash(int i0) const;
1548 //! computes the element hash value (2D case)
1549 size_t hash(int i0, int i1) const;
1550 //! computes the element hash value (3D case)
1551 size_t hash(int i0, int i1, int i2) const;
1552 //! computes the element hash value (nD case)
1553 size_t hash(const int* idx) const;
1557 specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case.
1559 return pointer to the matrix element.
1561 <li>if the element is there (it's non-zero), the pointer to it is returned
1562 <li>if it's not there and createMissing=false, NULL pointer is returned
1563 <li>if it's not there and createMissing=true, then the new element
1564 is created and initialized with 0. Pointer to it is returned
1565 <li>if the optional hashval pointer is not NULL, the element hash value is
1566 not computed, but *hashval is taken instead.
1569 //! returns pointer to the specified element (1D case)
1570 uchar* ptr(int i0, bool createMissing, size_t* hashval=0);
1571 //! returns pointer to the specified element (2D case)
1572 uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0);
1573 //! returns pointer to the specified element (3D case)
1574 uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0);
1575 //! returns pointer to the specified element (nD case)
1576 uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0);
1581 return read-write reference to the specified sparse matrix element.
1583 ref<_Tp>(i0,...[,hashval]) is equivalent to *(_Tp*)ptr(i0,...,true[,hashval]).
1584 The methods always return a valid reference.
1585 If the element did not exist, it is created and initialiazed with 0.
1587 //! returns reference to the specified element (1D case)
1588 template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0);
1589 //! returns reference to the specified element (2D case)
1590 template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0);
1591 //! returns reference to the specified element (3D case)
1592 template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
1593 //! returns reference to the specified element (nD case)
1594 template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0);
1599 return value of the specified sparse matrix element.
1601 value<_Tp>(i0,...[,hashval]) is equivalent
1604 { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); }
1607 That is, if the element did not exist, the methods return 0.
1609 //! returns value of the specified element (1D case)
1610 template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const;
1611 //! returns value of the specified element (2D case)
1612 template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const;
1613 //! returns value of the specified element (3D case)
1614 template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0) const;
1615 //! returns value of the specified element (nD case)
1616 template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const;
1621 Return pointer to the specified sparse matrix element if it exists
1623 find<_Tp>(i0,...[,hashval]) is equivalent to (_const Tp*)ptr(i0,...false[,hashval]).
1625 If the specified element does not exist, the methods return NULL.
1627 //! returns pointer to the specified element (1D case)
1628 template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const;
1629 //! returns pointer to the specified element (2D case)
1630 template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0) const;
1631 //! returns pointer to the specified element (3D case)
1632 template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const;
1633 //! returns pointer to the specified element (nD case)
1634 template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0) const;
1636 //! erases the specified element (2D case)
1637 void erase(int i0, int i1, size_t* hashval=0);
1638 //! erases the specified element (3D case)
1639 void erase(int i0, int i1, int i2, size_t* hashval=0);
1640 //! erases the specified element (nD case)
1641 void erase(const int* idx, size_t* hashval=0);
1645 return the sparse matrix iterator pointing to the first sparse matrix element
1647 //! returns the sparse matrix iterator at the matrix beginning
1648 SparseMatIterator begin();
1649 //! returns the sparse matrix iterator at the matrix beginning
1650 template<typename _Tp> SparseMatIterator_<_Tp> begin();
1651 //! returns the read-only sparse matrix iterator at the matrix beginning
1652 SparseMatConstIterator begin() const;
1653 //! returns the read-only sparse matrix iterator at the matrix beginning
1654 template<typename _Tp> SparseMatConstIterator_<_Tp> begin() const;
1657 return the sparse matrix iterator pointing to the element following the last sparse matrix element
1659 //! returns the sparse matrix iterator at the matrix end
1660 SparseMatIterator end();
1661 //! returns the read-only sparse matrix iterator at the matrix end
1662 SparseMatConstIterator end() const;
1663 //! returns the typed sparse matrix iterator at the matrix end
1664 template<typename _Tp> SparseMatIterator_<_Tp> end();
1665 //! returns the typed read-only sparse matrix iterator at the matrix end
1666 template<typename _Tp> SparseMatConstIterator_<_Tp> end() const;
1668 //! returns the value stored in the sparse martix node
1669 template<typename _Tp> _Tp& value(Node* n);
1670 //! returns the value stored in the sparse martix node
1671 template<typename _Tp> const _Tp& value(const Node* n) const;
1673 ////////////// some internal-use methods ///////////////
1674 Node* node(size_t nidx);
1675 const Node* node(size_t nidx) const;
1677 uchar* newNode(const int* idx, size_t hashval);
1678 void removeNode(size_t hidx, size_t nidx, size_t previdx);
1679 void resizeHashTab(size_t newsize);
1687 ///////////////////////////////// SparseMat_<_Tp> ////////////////////////////////////
1690 The Template Sparse Matrix class derived from cv::SparseMat
1692 The class provides slightly more convenient operations for accessing elements.
1697 SparseMat_<int> m_ = (SparseMat_<int>&)m;
1698 m_.ref(1)++; // equivalent to m.ref<int>(1)++;
1699 m_.ref(2) += m_(3); // equivalent to m.ref<int>(2) += m.value<int>(3);
1702 template<typename _Tp> class SparseMat_ : public SparseMat
1705 typedef SparseMatIterator_<_Tp> iterator;
1706 typedef SparseMatConstIterator_<_Tp> const_iterator;
1708 //! the default constructor
1710 //! the full constructor equivelent to SparseMat(dims, _sizes, DataType<_Tp>::type)
1711 SparseMat_(int dims, const int* _sizes);
1712 //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted
1713 SparseMat_(const SparseMat& m);
1714 //! the copy constructor. This is O(1) operation - no data is copied
1715 SparseMat_(const SparseMat_& m);
1716 //! converts dense matrix to the sparse form
1717 SparseMat_(const Mat& m);
1718 //! converts the old-style sparse matrix to the C++ class. All the elements are copied
1719 //SparseMat_(const CvSparseMat* m);
1720 //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted
1721 SparseMat_& operator = (const SparseMat& m);
1722 //! the assignment operator. This is O(1) operation - no data is copied
1723 SparseMat_& operator = (const SparseMat_& m);
1724 //! converts dense matrix to the sparse form
1725 SparseMat_& operator = (const Mat& m);
1727 //! makes full copy of the matrix. All the elements are duplicated
1728 SparseMat_ clone() const;
1729 //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type)
1730 void create(int dims, const int* _sizes);
1731 //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied
1732 //operator CvSparseMat*() const;
1734 //! returns type of the matrix elements
1736 //! returns depth of the matrix elements
1738 //! returns the number of channels in each matrix element
1739 int channels() const;
1741 //! equivalent to SparseMat::ref<_Tp>(i0, hashval)
1742 _Tp& ref(int i0, size_t* hashval=0);
1743 //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval)
1744 _Tp& ref(int i0, int i1, size_t* hashval=0);
1745 //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval)
1746 _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
1747 //! equivalent to SparseMat::ref<_Tp>(idx, hashval)
1748 _Tp& ref(const int* idx, size_t* hashval=0);
1750 //! equivalent to SparseMat::value<_Tp>(i0, hashval)
1751 _Tp operator()(int i0, size_t* hashval=0) const;
1752 //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval)
1753 _Tp operator()(int i0, int i1, size_t* hashval=0) const;
1754 //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval)
1755 _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const;
1756 //! equivalent to SparseMat::value<_Tp>(idx, hashval)
1757 _Tp operator()(const int* idx, size_t* hashval=0) const;
1759 //! returns sparse matrix iterator pointing to the first sparse matrix element
1760 SparseMatIterator_<_Tp> begin();
1761 //! returns read-only sparse matrix iterator pointing to the first sparse matrix element
1762 SparseMatConstIterator_<_Tp> begin() const;
1763 //! returns sparse matrix iterator pointing to the element following the last sparse matrix element
1764 SparseMatIterator_<_Tp> end();
1765 //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element
1766 SparseMatConstIterator_<_Tp> end() const;
1771 ////////////////////////////////// MatConstIterator //////////////////////////////////
1773 class CV_EXPORTS MatConstIterator
1776 typedef uchar* value_type;
1777 typedef ptrdiff_t difference_type;
1778 typedef const uchar** pointer;
1779 typedef uchar* reference;
1781 #ifndef OPENCV_NOSTL
1782 typedef std::random_access_iterator_tag iterator_category;
1785 //! default constructor
1787 //! constructor that sets the iterator to the beginning of the matrix
1788 MatConstIterator(const Mat* _m);
1789 //! constructor that sets the iterator to the specified element of the matrix
1790 MatConstIterator(const Mat* _m, int _row, int _col=0);
1791 //! constructor that sets the iterator to the specified element of the matrix
1792 MatConstIterator(const Mat* _m, Point _pt);
1793 //! constructor that sets the iterator to the specified element of the matrix
1794 MatConstIterator(const Mat* _m, const int* _idx);
1795 //! copy constructor
1796 MatConstIterator(const MatConstIterator& it);
1799 MatConstIterator& operator = (const MatConstIterator& it);
1800 //! returns the current matrix element
1801 uchar* operator *() const;
1802 //! returns the i-th matrix element, relative to the current
1803 uchar* operator [](ptrdiff_t i) const;
1805 //! shifts the iterator forward by the specified number of elements
1806 MatConstIterator& operator += (ptrdiff_t ofs);
1807 //! shifts the iterator backward by the specified number of elements
1808 MatConstIterator& operator -= (ptrdiff_t ofs);
1809 //! decrements the iterator
1810 MatConstIterator& operator --();
1811 //! decrements the iterator
1812 MatConstIterator operator --(int);
1813 //! increments the iterator
1814 MatConstIterator& operator ++();
1815 //! increments the iterator
1816 MatConstIterator operator ++(int);
1817 //! returns the current iterator position
1819 //! returns the current iterator position
1820 void pos(int* _idx) const;
1822 ptrdiff_t lpos() const;
1823 void seek(ptrdiff_t ofs, bool relative = false);
1824 void seek(const int* _idx, bool relative = false);
1835 ////////////////////////////////// MatConstIterator_ /////////////////////////////////
1838 Matrix read-only iterator
1840 template<typename _Tp>
1841 class MatConstIterator_ : public MatConstIterator
1844 typedef _Tp value_type;
1845 typedef ptrdiff_t difference_type;
1846 typedef const _Tp* pointer;
1847 typedef const _Tp& reference;
1849 #ifndef OPENCV_NOSTL
1850 typedef std::random_access_iterator_tag iterator_category;
1853 //! default constructor
1854 MatConstIterator_();
1855 //! constructor that sets the iterator to the beginning of the matrix
1856 MatConstIterator_(const Mat_<_Tp>* _m);
1857 //! constructor that sets the iterator to the specified element of the matrix
1858 MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0);
1859 //! constructor that sets the iterator to the specified element of the matrix
1860 MatConstIterator_(const Mat_<_Tp>* _m, Point _pt);
1861 //! constructor that sets the iterator to the specified element of the matrix
1862 MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx);
1863 //! copy constructor
1864 MatConstIterator_(const MatConstIterator_& it);
1867 MatConstIterator_& operator = (const MatConstIterator_& it);
1868 //! returns the current matrix element
1869 _Tp operator *() const;
1870 //! returns the i-th matrix element, relative to the current
1871 _Tp operator [](ptrdiff_t i) const;
1873 //! shifts the iterator forward by the specified number of elements
1874 MatConstIterator_& operator += (ptrdiff_t ofs);
1875 //! shifts the iterator backward by the specified number of elements
1876 MatConstIterator_& operator -= (ptrdiff_t ofs);
1877 //! decrements the iterator
1878 MatConstIterator_& operator --();
1879 //! decrements the iterator
1880 MatConstIterator_ operator --(int);
1881 //! increments the iterator
1882 MatConstIterator_& operator ++();
1883 //! increments the iterator
1884 MatConstIterator_ operator ++(int);
1885 //! returns the current iterator position
1891 //////////////////////////////////// MatIterator_ ////////////////////////////////////
1894 Matrix read-write iterator
1896 template<typename _Tp>
1897 class MatIterator_ : public MatConstIterator_<_Tp>
1900 typedef _Tp* pointer;
1901 typedef _Tp& reference;
1903 #ifndef OPENCV_NOSTL
1904 typedef std::random_access_iterator_tag iterator_category;
1907 //! the default constructor
1909 //! constructor that sets the iterator to the beginning of the matrix
1910 MatIterator_(Mat_<_Tp>* _m);
1911 //! constructor that sets the iterator to the specified element of the matrix
1912 MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0);
1913 //! constructor that sets the iterator to the specified element of the matrix
1914 MatIterator_(const Mat_<_Tp>* _m, Point _pt);
1915 //! constructor that sets the iterator to the specified element of the matrix
1916 MatIterator_(const Mat_<_Tp>* _m, const int* _idx);
1917 //! copy constructor
1918 MatIterator_(const MatIterator_& it);
1920 MatIterator_& operator = (const MatIterator_<_Tp>& it );
1922 //! returns the current matrix element
1923 _Tp& operator *() const;
1924 //! returns the i-th matrix element, relative to the current
1925 _Tp& operator [](ptrdiff_t i) const;
1927 //! shifts the iterator forward by the specified number of elements
1928 MatIterator_& operator += (ptrdiff_t ofs);
1929 //! shifts the iterator backward by the specified number of elements
1930 MatIterator_& operator -= (ptrdiff_t ofs);
1931 //! decrements the iterator
1932 MatIterator_& operator --();
1933 //! decrements the iterator
1934 MatIterator_ operator --(int);
1935 //! increments the iterator
1936 MatIterator_& operator ++();
1937 //! increments the iterator
1938 MatIterator_ operator ++(int);
1943 /////////////////////////////// SparseMatConstIterator ///////////////////////////////
1946 Read-Only Sparse Matrix Iterator.
1947 Here is how to use the iterator to compute the sum of floating-point sparse matrix elements:
1950 SparseMatConstIterator it = m.begin(), it_end = m.end();
1952 CV_Assert( m.type() == CV_32F );
1953 for( ; it != it_end; ++it )
1954 s += it.value<float>();
1957 class CV_EXPORTS SparseMatConstIterator
1960 //! the default constructor
1961 SparseMatConstIterator();
1962 //! the full constructor setting the iterator to the first sparse matrix element
1963 SparseMatConstIterator(const SparseMat* _m);
1964 //! the copy constructor
1965 SparseMatConstIterator(const SparseMatConstIterator& it);
1967 //! the assignment operator
1968 SparseMatConstIterator& operator = (const SparseMatConstIterator& it);
1970 //! template method returning the current matrix element
1971 template<typename _Tp> const _Tp& value() const;
1972 //! returns the current node of the sparse matrix. it.node->idx is the current element index
1973 const SparseMat::Node* node() const;
1975 //! moves iterator to the previous element
1976 SparseMatConstIterator& operator --();
1977 //! moves iterator to the previous element
1978 SparseMatConstIterator operator --(int);
1979 //! moves iterator to the next element
1980 SparseMatConstIterator& operator ++();
1981 //! moves iterator to the next element
1982 SparseMatConstIterator operator ++(int);
1984 //! moves iterator to the element after the last element
1994 ////////////////////////////////// SparseMatIterator /////////////////////////////////
1997 Read-write Sparse Matrix Iterator
1999 The class is similar to cv::SparseMatConstIterator,
2000 but can be used for in-place modification of the matrix elements.
2002 class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator
2005 //! the default constructor
2006 SparseMatIterator();
2007 //! the full constructor setting the iterator to the first sparse matrix element
2008 SparseMatIterator(SparseMat* _m);
2009 //! the full constructor setting the iterator to the specified sparse matrix element
2010 SparseMatIterator(SparseMat* _m, const int* idx);
2011 //! the copy constructor
2012 SparseMatIterator(const SparseMatIterator& it);
2014 //! the assignment operator
2015 SparseMatIterator& operator = (const SparseMatIterator& it);
2016 //! returns read-write reference to the current sparse matrix element
2017 template<typename _Tp> _Tp& value() const;
2018 //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!)
2019 SparseMat::Node* node() const;
2021 //! moves iterator to the next element
2022 SparseMatIterator& operator ++();
2023 //! moves iterator to the next element
2024 SparseMatIterator operator ++(int);
2029 /////////////////////////////// SparseMatConstIterator_ //////////////////////////////
2032 Template Read-Only Sparse Matrix Iterator Class.
2034 This is the derived from SparseMatConstIterator class that
2035 introduces more convenient operator *() for accessing the current element.
2037 template<typename _Tp> class SparseMatConstIterator_ : public SparseMatConstIterator
2041 #ifndef OPENCV_NOSTL
2042 typedef std::forward_iterator_tag iterator_category;
2045 //! the default constructor
2046 SparseMatConstIterator_();
2047 //! the full constructor setting the iterator to the first sparse matrix element
2048 SparseMatConstIterator_(const SparseMat_<_Tp>* _m);
2049 SparseMatConstIterator_(const SparseMat* _m);
2050 //! the copy constructor
2051 SparseMatConstIterator_(const SparseMatConstIterator_& it);
2053 //! the assignment operator
2054 SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it);
2055 //! the element access operator
2056 const _Tp& operator *() const;
2058 //! moves iterator to the next element
2059 SparseMatConstIterator_& operator ++();
2060 //! moves iterator to the next element
2061 SparseMatConstIterator_ operator ++(int);
2066 ///////////////////////////////// SparseMatIterator_ /////////////////////////////////
2069 Template Read-Write Sparse Matrix Iterator Class.
2071 This is the derived from cv::SparseMatConstIterator_ class that
2072 introduces more convenient operator *() for accessing the current element.
2074 template<typename _Tp> class SparseMatIterator_ : public SparseMatConstIterator_<_Tp>
2078 #ifndef OPENCV_NOSTL
2079 typedef std::forward_iterator_tag iterator_category;
2082 //! the default constructor
2083 SparseMatIterator_();
2084 //! the full constructor setting the iterator to the first sparse matrix element
2085 SparseMatIterator_(SparseMat_<_Tp>* _m);
2086 SparseMatIterator_(SparseMat* _m);
2087 //! the copy constructor
2088 SparseMatIterator_(const SparseMatIterator_& it);
2090 //! the assignment operator
2091 SparseMatIterator_& operator = (const SparseMatIterator_& it);
2092 //! returns the reference to the current element
2093 _Tp& operator *() const;
2095 //! moves the iterator to the next element
2096 SparseMatIterator_& operator ++();
2097 //! moves the iterator to the next element
2098 SparseMatIterator_ operator ++(int);
2103 /////////////////////////////////// NAryMatIterator //////////////////////////////////
2106 n-Dimensional Dense Matrix Iterator Class.
2108 The class cv::NAryMatIterator is used for iterating over one or more n-dimensional dense arrays (cv::Mat's).
2110 The iterator is completely different from cv::Mat_ and cv::SparseMat_ iterators.
2111 It iterates through the slices (or planes), not the elements, where "slice" is a continuous part of the arrays.
2113 Here is the example on how the iterator can be used to normalize 3D histogram:
2116 void normalizeColorHist(Mat& hist)
2119 // intialize iterator (the style is different from STL).
2120 // after initialization the iterator will contain
2121 // the number of slices or planes
2122 // the iterator will go through
2123 Mat* arrays[] = { &hist, 0 };
2125 NAryMatIterator it(arrays, planes);
2127 // iterate through the matrix. on each iteration
2128 // it.planes[i] (of type Mat) will be set to the current plane of
2129 // i-th n-dim matrix passed to the iterator constructor.
2130 for(int p = 0; p < it.nplanes; p++, ++it)
2131 s += sum(it.planes[0])[0];
2132 it = NAryMatIterator(hist);
2134 for(int p = 0; p < it.nplanes; p++, ++it)
2137 // this is a shorter implementation of the above
2138 // using built-in operations on Mat
2139 double s = sum(hist)[0];
2140 hist.convertTo(hist, hist.type(), 1./s, 0);
2142 // and this is even shorter one
2143 // (assuming that the histogram elements are non-negative)
2144 normalize(hist, hist, 1, 0, NORM_L1);
2149 You can iterate through several matrices simultaneously as long as they have the same geometry
2150 (dimensionality and all the dimension sizes are the same), which is useful for binary
2151 and n-ary operations on such matrices. Just pass those matrices to cv::MatNDIterator.
2152 Then, during the iteration it.planes[0], it.planes[1], ... will
2153 be the slices of the corresponding matrices
2155 class CV_EXPORTS NAryMatIterator
2158 //! the default constructor
2160 //! the full constructor taking arbitrary number of n-dim matrices
2161 NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1);
2162 //! the full constructor taking arbitrary number of n-dim matrices
2163 NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1);
2164 //! the separate iterator initialization method
2165 void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1);
2167 //! proceeds to the next plane of every iterated matrix
2168 NAryMatIterator& operator ++();
2169 //! proceeds to the next plane of every iterated matrix (postfix increment operator)
2170 NAryMatIterator operator ++(int);
2172 //! the iterated arrays
2174 //! the current planes
2178 //! the number of arrays
2180 //! the number of hyper-planes that the iterator steps through
2182 //! the size of each segment (in elements)
2191 ///////////////////////////////// Matrix Expressions /////////////////////////////////
2193 class CV_EXPORTS MatOp
2199 virtual bool elementWise(const MatExpr& expr) const;
2200 virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0;
2201 virtual void roi(const MatExpr& expr, const Range& rowRange,
2202 const Range& colRange, MatExpr& res) const;
2203 virtual void diag(const MatExpr& expr, int d, MatExpr& res) const;
2204 virtual void augAssignAdd(const MatExpr& expr, Mat& m) const;
2205 virtual void augAssignSubtract(const MatExpr& expr, Mat& m) const;
2206 virtual void augAssignMultiply(const MatExpr& expr, Mat& m) const;
2207 virtual void augAssignDivide(const MatExpr& expr, Mat& m) const;
2208 virtual void augAssignAnd(const MatExpr& expr, Mat& m) const;
2209 virtual void augAssignOr(const MatExpr& expr, Mat& m) const;
2210 virtual void augAssignXor(const MatExpr& expr, Mat& m) const;
2212 virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
2213 virtual void add(const MatExpr& expr1, const Scalar& s, MatExpr& res) const;
2215 virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
2216 virtual void subtract(const Scalar& s, const MatExpr& expr, MatExpr& res) const;
2218 virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
2219 virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const;
2221 virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
2222 virtual void divide(double s, const MatExpr& expr, MatExpr& res) const;
2224 virtual void abs(const MatExpr& expr, MatExpr& res) const;
2226 virtual void transpose(const MatExpr& expr, MatExpr& res) const;
2227 virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
2228 virtual void invert(const MatExpr& expr, int method, MatExpr& res) const;
2230 virtual Size size(const MatExpr& expr) const;
2231 virtual int type(const MatExpr& expr) const;
2235 class CV_EXPORTS MatExpr
2239 explicit MatExpr(const Mat& m);
2241 MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(),
2242 const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar& _s = Scalar());
2244 operator Mat() const;
2245 template<typename _Tp> operator Mat_<_Tp>() const;
2250 MatExpr row(int y) const;
2251 MatExpr col(int x) const;
2252 MatExpr diag(int d = 0) const;
2253 MatExpr operator()( const Range& rowRange, const Range& colRange ) const;
2254 MatExpr operator()( const Rect& roi ) const;
2257 MatExpr inv(int method = DECOMP_LU) const;
2258 MatExpr mul(const MatExpr& e, double scale=1) const;
2259 MatExpr mul(const Mat& m, double scale=1) const;
2261 Mat cross(const Mat& m) const;
2262 double dot(const Mat& m) const;
2273 CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b);
2274 CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s);
2275 CV_EXPORTS MatExpr operator + (const Scalar& s, const Mat& a);
2276 CV_EXPORTS MatExpr operator + (const MatExpr& e, const Mat& m);
2277 CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e);
2278 CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar& s);
2279 CV_EXPORTS MatExpr operator + (const Scalar& s, const MatExpr& e);
2280 CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2);
2282 CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b);
2283 CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar& s);
2284 CV_EXPORTS MatExpr operator - (const Scalar& s, const Mat& a);
2285 CV_EXPORTS MatExpr operator - (const MatExpr& e, const Mat& m);
2286 CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e);
2287 CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar& s);
2288 CV_EXPORTS MatExpr operator - (const Scalar& s, const MatExpr& e);
2289 CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2);
2291 CV_EXPORTS MatExpr operator - (const Mat& m);
2292 CV_EXPORTS MatExpr operator - (const MatExpr& e);
2294 CV_EXPORTS MatExpr operator * (const Mat& a, const Mat& b);
2295 CV_EXPORTS MatExpr operator * (const Mat& a, double s);
2296 CV_EXPORTS MatExpr operator * (double s, const Mat& a);
2297 CV_EXPORTS MatExpr operator * (const MatExpr& e, const Mat& m);
2298 CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e);
2299 CV_EXPORTS MatExpr operator * (const MatExpr& e, double s);
2300 CV_EXPORTS MatExpr operator * (double s, const MatExpr& e);
2301 CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2);
2303 CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b);
2304 CV_EXPORTS MatExpr operator / (const Mat& a, double s);
2305 CV_EXPORTS MatExpr operator / (double s, const Mat& a);
2306 CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m);
2307 CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e);
2308 CV_EXPORTS MatExpr operator / (const MatExpr& e, double s);
2309 CV_EXPORTS MatExpr operator / (double s, const MatExpr& e);
2310 CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2);
2312 CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b);
2313 CV_EXPORTS MatExpr operator < (const Mat& a, double s);
2314 CV_EXPORTS MatExpr operator < (double s, const Mat& a);
2316 CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b);
2317 CV_EXPORTS MatExpr operator <= (const Mat& a, double s);
2318 CV_EXPORTS MatExpr operator <= (double s, const Mat& a);
2320 CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b);
2321 CV_EXPORTS MatExpr operator == (const Mat& a, double s);
2322 CV_EXPORTS MatExpr operator == (double s, const Mat& a);
2324 CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b);
2325 CV_EXPORTS MatExpr operator != (const Mat& a, double s);
2326 CV_EXPORTS MatExpr operator != (double s, const Mat& a);
2328 CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b);
2329 CV_EXPORTS MatExpr operator >= (const Mat& a, double s);
2330 CV_EXPORTS MatExpr operator >= (double s, const Mat& a);
2332 CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b);
2333 CV_EXPORTS MatExpr operator > (const Mat& a, double s);
2334 CV_EXPORTS MatExpr operator > (double s, const Mat& a);
2336 CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b);
2337 CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s);
2338 CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a);
2340 CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b);
2341 CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar& s);
2342 CV_EXPORTS MatExpr operator | (const Scalar& s, const Mat& a);
2344 CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b);
2345 CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s);
2346 CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a);
2348 CV_EXPORTS MatExpr operator ~(const Mat& m);
2350 CV_EXPORTS MatExpr min(const Mat& a, const Mat& b);
2351 CV_EXPORTS MatExpr min(const Mat& a, double s);
2352 CV_EXPORTS MatExpr min(double s, const Mat& a);
2354 CV_EXPORTS MatExpr max(const Mat& a, const Mat& b);
2355 CV_EXPORTS MatExpr max(const Mat& a, double s);
2356 CV_EXPORTS MatExpr max(double s, const Mat& a);
2358 CV_EXPORTS MatExpr abs(const Mat& m);
2359 CV_EXPORTS MatExpr abs(const MatExpr& e);
2363 #include "opencv2/core/mat.inl.hpp"
2365 #endif // __OPENCV_CORE_MAT_HPP__