Renesas / opencv-lib

Dependents:   RZ_A2M_Mbed_samples

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers mat.hpp Source File

mat.hpp

00001 /*M///////////////////////////////////////////////////////////////////////////////////////
00002 //
00003 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
00004 //
00005 //  By downloading, copying, installing or using the software you agree to this license.
00006 //  If you do not agree to this license, do not download, install,
00007 //  copy or use the software.
00008 //
00009 //
00010 //                          License Agreement
00011 //                For Open Source Computer Vision Library
00012 //
00013 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
00014 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
00015 // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
00016 // Third party copyrights are property of their respective owners.
00017 //
00018 // Redistribution and use in source and binary forms, with or without modification,
00019 // are permitted provided that the following conditions are met:
00020 //
00021 //   * Redistribution's of source code must retain the above copyright notice,
00022 //     this list of conditions and the following disclaimer.
00023 //
00024 //   * Redistribution's in binary form must reproduce the above copyright notice,
00025 //     this list of conditions and the following disclaimer in the documentation
00026 //     and/or other materials provided with the distribution.
00027 //
00028 //   * The name of the copyright holders may not be used to endorse or promote products
00029 //     derived from this software without specific prior written permission.
00030 //
00031 // This software is provided by the copyright holders and contributors "as is" and
00032 // any express or implied warranties, including, but not limited to, the implied
00033 // warranties of merchantability and fitness for a particular purpose are disclaimed.
00034 // In no event shall the Intel Corporation or contributors be liable for any direct,
00035 // indirect, incidental, special, exemplary, or consequential damages
00036 // (including, but not limited to, procurement of substitute goods or services;
00037 // loss of use, data, or profits; or business interruption) however caused
00038 // and on any theory of liability, whether in contract, strict liability,
00039 // or tort (including negligence or otherwise) arising in any way out of
00040 // the use of this software, even if advised of the possibility of such damage.
00041 //
00042 //M*/
00043 
00044 #ifndef OPENCV_CORE_MAT_HPP
00045 #define OPENCV_CORE_MAT_HPP
00046 
00047 #ifndef __cplusplus
00048 #  error mat.hpp header must be compiled as C++
00049 #endif
00050 
00051 #include "opencv2/core/matx.hpp"
00052 #include "opencv2/core/types.hpp"
00053 
00054 #include "opencv2/core/bufferpool.hpp"
00055 
00056 namespace cv
00057 {
00058 
00059 //! @addtogroup core_basic
00060 //! @{
00061 
00062 enum { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25,
00063     ACCESS_RW=3<<24, ACCESS_MASK=ACCESS_RW, ACCESS_FAST=1<<26 };
00064 
00065 class CV_EXPORTS _OutputArray;
00066 
00067 //////////////////////// Input/Output Array Arguments /////////////////////////////////
00068 
00069 /** @brief This is the proxy class for passing read-only input arrays into OpenCV functions.
00070 
00071 It is defined as:
00072 @code
00073     typedef const _InputArray& InputArray;
00074 @endcode
00075 where _InputArray is a class that can be constructed from `Mat`, `Mat_<T>`, `Matx<T, m, n>`,
00076 `std::vector<T>`, `std::vector<std::vector<T> >` or `std::vector<Mat>`. It can also be constructed
00077 from a matrix expression.
00078 
00079 Since this is mostly implementation-level class, and its interface may change in future versions, we
00080 do not describe it in details. There are a few key things, though, that should be kept in mind:
00081 
00082 -   When you see in the reference manual or in OpenCV source code a function that takes
00083     InputArray, it means that you can actually pass `Mat`, `Matx`, `vector<T>` etc. (see above the
00084     complete list).
00085 -   Optional input arguments: If some of the input arrays may be empty, pass cv::noArray() (or
00086     simply cv::Mat() as you probably did before).
00087 -   The class is designed solely for passing parameters. That is, normally you *should not*
00088     declare class members, local and global variables of this type.
00089 -   If you want to design your own function or a class method that can operate of arrays of
00090     multiple types, you can use InputArray (or OutputArray) for the respective parameters. Inside
00091     a function you should use _InputArray::getMat() method to construct a matrix header for the
00092     array (without copying data). _InputArray::kind() can be used to distinguish Mat from
00093     `vector<>` etc., but normally it is not needed.
00094 
00095 Here is how you can use a function that takes InputArray :
00096 @code
00097     std::vector<Point2f> vec;
00098     // points or a circle
00099     for( int i = 0; i < 30; i++ )
00100         vec.push_back(Point2f((float)(100 + 30*cos(i*CV_PI*2/5)),
00101                               (float)(100 - 30*sin(i*CV_PI*2/5))));
00102     cv::transform(vec, vec, cv::Matx23f(0.707, -0.707, 10, 0.707, 0.707, 20));
00103 @endcode
00104 That is, we form an STL vector containing points, and apply in-place affine transformation to the
00105 vector using the 2x3 matrix created inline as `Matx<float, 2, 3>` instance.
00106 
00107 Here is how such a function can be implemented (for simplicity, we implement a very specific case of
00108 it, according to the assertion statement inside) :
00109 @code
00110     void myAffineTransform(InputArray _src, OutputArray _dst, InputArray _m)
00111     {
00112         // get Mat headers for input arrays. This is O(1) operation,
00113         // unless _src and/or _m are matrix expressions.
00114         Mat src = _src.getMat(), m = _m.getMat();
00115         CV_Assert( src.type() == CV_32FC2 && m.type() == CV_32F && m.size() == Size(3, 2) );
00116 
00117         // [re]create the output array so that it has the proper size and type.
00118         // In case of Mat it calls Mat::create, in case of STL vector it calls vector::resize.
00119         _dst.create(src.size(), src.type());
00120         Mat dst = _dst.getMat();
00121 
00122         for( int i = 0; i < src.rows; i++ )
00123             for( int j = 0; j < src.cols; j++ )
00124             {
00125                 Point2f pt = src.at<Point2f>(i, j);
00126                 dst.at<Point2f>(i, j) = Point2f(m.at<float>(0, 0)*pt.x +
00127                                                 m.at<float>(0, 1)*pt.y +
00128                                                 m.at<float>(0, 2),
00129                                                 m.at<float>(1, 0)*pt.x +
00130                                                 m.at<float>(1, 1)*pt.y +
00131                                                 m.at<float>(1, 2));
00132             }
00133     }
00134 @endcode
00135 There is another related type, InputArrayOfArrays, which is currently defined as a synonym for
00136 InputArray:
00137 @code
00138     typedef InputArray InputArrayOfArrays;
00139 @endcode
00140 It denotes function arguments that are either vectors of vectors or vectors of matrices. A separate
00141 synonym is needed to generate Python/Java etc. wrappers properly. At the function implementation
00142 level their use is similar, but _InputArray::getMat(idx) should be used to get header for the
00143 idx-th component of the outer vector and _InputArray::size().area() should be used to find the
00144 number of components (vectors/matrices) of the outer vector.
00145  */
00146 class CV_EXPORTS _InputArray
00147 {
00148 public:
00149     enum {
00150         KIND_SHIFT = 16,
00151         FIXED_TYPE = 0x8000 << KIND_SHIFT,
00152         FIXED_SIZE = 0x4000 << KIND_SHIFT,
00153         KIND_MASK = 31 << KIND_SHIFT,
00154 
00155         NONE              = 0 << KIND_SHIFT,
00156         MAT               = 1 << KIND_SHIFT,
00157         MATX              = 2 << KIND_SHIFT,
00158         STD_VECTOR        = 3 << KIND_SHIFT,
00159         STD_VECTOR_VECTOR = 4 << KIND_SHIFT,
00160         STD_VECTOR_MAT    = 5 << KIND_SHIFT,
00161         EXPR              = 6 << KIND_SHIFT,
00162         OPENGL_BUFFER     = 7 << KIND_SHIFT,
00163         CUDA_HOST_MEM     = 8 << KIND_SHIFT,
00164         CUDA_GPU_MAT      = 9 << KIND_SHIFT,
00165         UMAT              =10 << KIND_SHIFT,
00166         STD_VECTOR_UMAT   =11 << KIND_SHIFT,
00167         STD_BOOL_VECTOR   =12 << KIND_SHIFT,
00168         STD_VECTOR_CUDA_GPU_MAT = 13 << KIND_SHIFT
00169     };
00170 
00171     _InputArray();
00172     _InputArray(int _flags, void* _obj);
00173     _InputArray(const Mat& m);
00174     _InputArray(const MatExpr& expr);
00175     _InputArray(const std::vector<Mat>& vec);
00176     template<typename _Tp> _InputArray(const Mat_<_Tp>& m);
00177     template<typename _Tp> _InputArray(const std::vector<_Tp>& vec);
00178     _InputArray(const std::vector<bool>& vec);
00179     template<typename _Tp> _InputArray(const std::vector<std::vector<_Tp> >& vec);
00180     template<typename _Tp> _InputArray(const std::vector<Mat_<_Tp> >& vec);
00181     template<typename _Tp> _InputArray(const _Tp* vec, int n);
00182     template<typename _Tp, int m, int n> _InputArray(const Matx<_Tp, m, n>& matx);
00183     _InputArray(const double& val);
00184     _InputArray(const cuda::GpuMat& d_mat);
00185     _InputArray(const std::vector<cuda::GpuMat>& d_mat_array);
00186     _InputArray(const ogl::Buffer& buf);
00187     _InputArray(const cuda::HostMem& cuda_mem);
00188     template<typename _Tp> _InputArray(const cudev::GpuMat_<_Tp>& m);
00189     _InputArray(const UMat & um);
00190     _InputArray(const std::vector<UMat>& umv);
00191 
00192     Mat getMat(int idx=-1) const;
00193     Mat getMat_(int idx=-1) const;
00194     UMat  getUMat(int idx=-1) const;
00195     void getMatVector(std::vector<Mat>& mv) const;
00196     void getUMatVector(std::vector<UMat>& umv) const;
00197     void getGpuMatVector(std::vector<cuda::GpuMat>& gpumv) const;
00198     cuda::GpuMat getGpuMat() const;
00199     ogl::Buffer getOGlBuffer() const;
00200 
00201     int getFlags() const;
00202     void* getObj() const;
00203     Size getSz() const;
00204 
00205     int kind() const;
00206     int dims(int i=-1) const;
00207     int cols(int i=-1) const;
00208     int rows(int i=-1) const;
00209     Size size(int i=-1) const;
00210     int sizend(int* sz, int i=-1) const;
00211     bool sameSize(const _InputArray& arr) const;
00212     size_t total(int i=-1) const;
00213     int type(int i=-1) const;
00214     int depth(int i=-1) const;
00215     int channels(int i=-1) const;
00216     bool isContinuous(int i=-1) const;
00217     bool isSubmatrix(int i=-1) const;
00218     bool empty() const;
00219     void copyTo(const _OutputArray& arr) const;
00220     void copyTo(const _OutputArray& arr, const _InputArray & mask) const;
00221     size_t offset(int i=-1) const;
00222     size_t step(int i=-1) const;
00223     bool isMat() const;
00224     bool isUMat() const;
00225     bool isMatVector() const;
00226     bool isUMatVector() const;
00227     bool isMatx() const;
00228     bool isVector() const;
00229     bool isGpuMatVector() const;
00230     ~_InputArray();
00231 
00232 protected:
00233     int flags;
00234     void* obj;
00235     Size sz;
00236 
00237     void init(int _flags, const void* _obj);
00238     void init(int _flags, const void* _obj, Size _sz);
00239 };
00240 
00241 
00242 /** @brief This type is very similar to InputArray except that it is used for input/output and output function
00243 parameters.
00244 
00245 Just like with InputArray, OpenCV users should not care about OutputArray, they just pass `Mat`,
00246 `vector<T>` etc. to the functions. The same limitation as for `InputArray`: *Do not explicitly
00247 create OutputArray instances* applies here too.
00248 
00249 If you want to make your function polymorphic (i.e. accept different arrays as output parameters),
00250 it is also not very difficult. Take the sample above as the reference. Note that
00251 _OutputArray::create() needs to be called before _OutputArray::getMat(). This way you guarantee
00252 that the output array is properly allocated.
00253 
00254 Optional output parameters. If you do not need certain output array to be computed and returned to
00255 you, pass cv::noArray(), just like you would in the case of optional input array. At the
00256 implementation level, use _OutputArray::needed() to check if certain output array needs to be
00257 computed or not.
00258 
00259 There are several synonyms for OutputArray that are used to assist automatic Python/Java/... wrapper
00260 generators:
00261 @code
00262     typedef OutputArray OutputArrayOfArrays;
00263     typedef OutputArray InputOutputArray;
00264     typedef OutputArray InputOutputArrayOfArrays;
00265 @endcode
00266  */
00267 class CV_EXPORTS _OutputArray : public _InputArray
00268 {
00269 public:
00270     enum
00271     {
00272         DEPTH_MASK_8U = 1 << CV_8U,
00273         DEPTH_MASK_8S = 1 << CV_8S,
00274         DEPTH_MASK_16U = 1 << CV_16U,
00275         DEPTH_MASK_16S = 1 << CV_16S,
00276         DEPTH_MASK_32S = 1 << CV_32S,
00277         DEPTH_MASK_32F = 1 << CV_32F,
00278         DEPTH_MASK_64F = 1 << CV_64F,
00279         DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1,
00280         DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S,
00281         DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F
00282     };
00283 
00284     _OutputArray();
00285     _OutputArray(int _flags, void* _obj);
00286     _OutputArray(Mat& m);
00287     _OutputArray(std::vector<Mat>& vec);
00288     _OutputArray(cuda::GpuMat& d_mat);
00289     _OutputArray(std::vector<cuda::GpuMat>& d_mat);
00290     _OutputArray(ogl::Buffer& buf);
00291     _OutputArray(cuda::HostMem& cuda_mem);
00292     template<typename _Tp> _OutputArray(cudev::GpuMat_<_Tp>& m);
00293     template<typename _Tp> _OutputArray(std::vector<_Tp>& vec);
00294     _OutputArray(std::vector<bool>& vec);
00295     template<typename _Tp> _OutputArray(std::vector<std::vector<_Tp> >& vec);
00296     template<typename _Tp> _OutputArray(std::vector<Mat_<_Tp> >& vec);
00297     template<typename _Tp> _OutputArray(Mat_<_Tp>& m);
00298     template<typename _Tp> _OutputArray(_Tp* vec, int n);
00299     template<typename _Tp, int m, int n> _OutputArray(Matx<_Tp, m, n>& matx);
00300     _OutputArray(UMat & m);
00301     _OutputArray(std::vector<UMat>& vec);
00302 
00303     _OutputArray(const Mat& m);
00304     _OutputArray(const std::vector<Mat>& vec);
00305     _OutputArray(const cuda::GpuMat& d_mat);
00306     _OutputArray(const std::vector<cuda::GpuMat>& d_mat);
00307     _OutputArray(const ogl::Buffer& buf);
00308     _OutputArray(const cuda::HostMem& cuda_mem);
00309     template<typename _Tp> _OutputArray(const cudev::GpuMat_<_Tp>& m);
00310     template<typename _Tp> _OutputArray(const std::vector<_Tp>& vec);
00311     template<typename _Tp> _OutputArray(const std::vector<std::vector<_Tp> >& vec);
00312     template<typename _Tp> _OutputArray(const std::vector<Mat_<_Tp> >& vec);
00313     template<typename _Tp> _OutputArray(const Mat_<_Tp>& m);
00314     template<typename _Tp> _OutputArray(const _Tp* vec, int n);
00315     template<typename _Tp, int m, int n> _OutputArray(const Matx<_Tp, m, n>& matx);
00316     _OutputArray(const UMat & m);
00317     _OutputArray(const std::vector<UMat>& vec);
00318 
00319     bool fixedSize() const;
00320     bool fixedType() const;
00321     bool needed() const;
00322     Mat& getMatRef(int i=-1) const;
00323     UMat & getUMatRef(int i=-1) const;
00324     cuda::GpuMat& getGpuMatRef() const;
00325     std::vector<cuda::GpuMat>& getGpuMatVecRef() const;
00326     ogl::Buffer& getOGlBufferRef() const;
00327     cuda::HostMem& getHostMemRef() const;
00328     void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
00329     void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
00330     void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
00331     void createSameSize(const _InputArray& arr, int mtype) const;
00332     void release() const;
00333     void clear() const;
00334     void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const;
00335 
00336     void assign(const UMat & u) const;
00337     void assign(const Mat& m) const;
00338 };
00339 
00340 
00341 class CV_EXPORTS _InputOutputArray : public _OutputArray
00342 {
00343 public:
00344     _InputOutputArray();
00345     _InputOutputArray(int _flags, void* _obj);
00346     _InputOutputArray(Mat& m);
00347     _InputOutputArray(std::vector<Mat>& vec);
00348     _InputOutputArray(cuda::GpuMat& d_mat);
00349     _InputOutputArray(ogl::Buffer& buf);
00350     _InputOutputArray(cuda::HostMem& cuda_mem);
00351     template<typename _Tp> _InputOutputArray(cudev::GpuMat_<_Tp>& m);
00352     template<typename _Tp> _InputOutputArray(std::vector<_Tp>& vec);
00353     _InputOutputArray(std::vector<bool>& vec);
00354     template<typename _Tp> _InputOutputArray(std::vector<std::vector<_Tp> >& vec);
00355     template<typename _Tp> _InputOutputArray(std::vector<Mat_<_Tp> >& vec);
00356     template<typename _Tp> _InputOutputArray(Mat_<_Tp>& m);
00357     template<typename _Tp> _InputOutputArray(_Tp* vec, int n);
00358     template<typename _Tp, int m, int n> _InputOutputArray(Matx<_Tp, m, n>& matx);
00359     _InputOutputArray(UMat & m);
00360     _InputOutputArray(std::vector<UMat>& vec);
00361 
00362     _InputOutputArray(const Mat& m);
00363     _InputOutputArray(const std::vector<Mat>& vec);
00364     _InputOutputArray(const cuda::GpuMat& d_mat);
00365     _InputOutputArray(const std::vector<cuda::GpuMat>& d_mat);
00366     _InputOutputArray(const ogl::Buffer& buf);
00367     _InputOutputArray(const cuda::HostMem& cuda_mem);
00368     template<typename _Tp> _InputOutputArray(const cudev::GpuMat_<_Tp>& m);
00369     template<typename _Tp> _InputOutputArray(const std::vector<_Tp>& vec);
00370     template<typename _Tp> _InputOutputArray(const std::vector<std::vector<_Tp> >& vec);
00371     template<typename _Tp> _InputOutputArray(const std::vector<Mat_<_Tp> >& vec);
00372     template<typename _Tp> _InputOutputArray(const Mat_<_Tp>& m);
00373     template<typename _Tp> _InputOutputArray(const _Tp* vec, int n);
00374     template<typename _Tp, int m, int n> _InputOutputArray(const Matx<_Tp, m, n>& matx);
00375     _InputOutputArray(const UMat & m);
00376     _InputOutputArray(const std::vector<UMat>& vec);
00377 };
00378 
00379 typedef const _InputArray& InputArray;
00380 typedef InputArray InputArrayOfArrays;
00381 typedef const _OutputArray& OutputArray;
00382 typedef OutputArray OutputArrayOfArrays;
00383 typedef const _InputOutputArray& InputOutputArray;
00384 typedef InputOutputArray InputOutputArrayOfArrays;
00385 
00386 CV_EXPORTS InputOutputArray noArray();
00387 
00388 /////////////////////////////////// MatAllocator //////////////////////////////////////
00389 
00390 //! Usage flags for allocator
00391 enum UMatUsageFlags
00392 {
00393     USAGE_DEFAULT = 0,
00394 
00395     // buffer allocation policy is platform and usage specific
00396     USAGE_ALLOCATE_HOST_MEMORY = 1 << 0,
00397     USAGE_ALLOCATE_DEVICE_MEMORY = 1 << 1,
00398     USAGE_ALLOCATE_SHARED_MEMORY = 1 << 2, // It is not equal to: USAGE_ALLOCATE_HOST_MEMORY | USAGE_ALLOCATE_DEVICE_MEMORY
00399 
00400     __UMAT_USAGE_FLAGS_32BIT = 0x7fffffff // Binary compatibility hint
00401 };
00402 
00403 struct CV_EXPORTS UMatData;
00404 
00405 /** @brief  Custom array allocator
00406 */
00407 class CV_EXPORTS MatAllocator
00408 {
00409 public:
00410     MatAllocator() {}
00411     virtual ~MatAllocator() {}
00412 
00413     // let's comment it off for now to detect and fix all the uses of allocator
00414     //virtual void allocate(int dims, const int* sizes, int type, int*& refcount,
00415     //                      uchar*& datastart, uchar*& data, size_t* step) = 0;
00416     //virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0;
00417     virtual UMatData* allocate(int dims, const int* sizes, int type,
00418                                void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const = 0;
00419     virtual bool allocate(UMatData* data, int accessflags, UMatUsageFlags usageFlags) const = 0;
00420     virtual void deallocate(UMatData* data) const = 0;
00421     virtual void map(UMatData* data, int accessflags) const;
00422     virtual void unmap(UMatData* data) const;
00423     virtual void download(UMatData* data, void* dst, int dims, const size_t sz[],
00424                           const size_t srcofs[], const size_t srcstep[],
00425                           const size_t dststep[]) const;
00426     virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[],
00427                         const size_t dstofs[], const size_t dststep[],
00428                         const size_t srcstep[]) const;
00429     virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[],
00430                       const size_t srcofs[], const size_t srcstep[],
00431                       const size_t dstofs[], const size_t dststep[], bool sync) const;
00432 
00433     // default implementation returns DummyBufferPoolController
00434     virtual BufferPoolController* getBufferPoolController(const char* id = NULL) const;
00435 };
00436 
00437 
00438 //////////////////////////////// MatCommaInitializer //////////////////////////////////
00439 
00440 /** @brief  Comma-separated Matrix Initializer
00441 
00442  The class instances are usually not created explicitly.
00443  Instead, they are created on "matrix << firstValue" operator.
00444 
00445  The sample below initializes 2x2 rotation matrix:
00446 
00447  \code
00448  double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180);
00449  Mat R = (Mat_<double>(2,2) << a, -b, b, a);
00450  \endcode
00451 */
00452 template<typename _Tp> class MatCommaInitializer_
00453 {
00454 public:
00455     //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat
00456     MatCommaInitializer_(Mat_<_Tp>* _m);
00457     //! the operator that takes the next value and put it to the matrix
00458     template<typename T2> MatCommaInitializer_<_Tp>& operator , (T2 v);
00459     //! another form of conversion operator
00460     operator Mat_<_Tp>() const;
00461 protected:
00462     MatIterator_<_Tp> it;
00463 };
00464 
00465 
00466 /////////////////////////////////////// Mat ///////////////////////////////////////////
00467 
00468 // note that umatdata might be allocated together
00469 // with the matrix data, not as a separate object.
00470 // therefore, it does not have constructor or destructor;
00471 // it should be explicitly initialized using init().
00472 struct CV_EXPORTS UMatData
00473 {
00474     enum { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2,
00475         DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24,
00476         USER_ALLOCATED=32, DEVICE_MEM_MAPPED=64};
00477     UMatData(const MatAllocator* allocator);
00478     ~UMatData();
00479 
00480     // provide atomic access to the structure
00481     void lock();
00482     void unlock();
00483 
00484     bool hostCopyObsolete() const;
00485     bool deviceCopyObsolete() const;
00486     bool deviceMemMapped() const;
00487     bool copyOnMap() const;
00488     bool tempUMat() const;
00489     bool tempCopiedUMat() const;
00490     void markHostCopyObsolete(bool flag);
00491     void markDeviceCopyObsolete(bool flag);
00492     void markDeviceMemMapped(bool flag);
00493 
00494     const MatAllocator* prevAllocator;
00495     const MatAllocator* currAllocator;
00496     int urefcount;
00497     int refcount;
00498     uchar* data;
00499     uchar* origdata;
00500     size_t size;
00501 
00502     int flags;
00503     void* handle;
00504     void* userdata;
00505     int allocatorFlags_;
00506     int mapcount;
00507     UMatData* originalUMatData;
00508 };
00509 
00510 
00511 struct CV_EXPORTS UMatDataAutoLock
00512 {
00513     explicit UMatDataAutoLock(UMatData* u);
00514     ~UMatDataAutoLock();
00515     UMatData* u;
00516 };
00517 
00518 
00519 struct CV_EXPORTS MatSize
00520 {
00521     explicit MatSize(int* _p);
00522     Size operator()() const;
00523     const int& operator[](int i) const;
00524     int& operator[](int i);
00525     operator const int*() const;
00526     bool operator == (const MatSize& sz) const;
00527     bool operator != (const MatSize& sz) const;
00528 
00529     int* p;
00530 };
00531 
00532 struct CV_EXPORTS MatStep
00533 {
00534     MatStep();
00535     explicit MatStep(size_t s);
00536     const size_t& operator[](int i) const;
00537     size_t& operator[](int i);
00538     operator size_t() const;
00539     MatStep& operator = (size_t s);
00540 
00541     size_t* p;
00542     size_t buf[2];
00543 protected:
00544     MatStep& operator = (const MatStep&);
00545 };
00546 
00547 /** @example cout_mat.cpp
00548 An example demonstrating the serial out capabilities of cv::Mat
00549 */
00550 
00551  /** @brief n-dimensional dense array class
00552 
00553 The class Mat represents an n-dimensional dense numerical single-channel or multi-channel array. It
00554 can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel
00555 volumes, vector fields, point clouds, tensors, histograms (though, very high-dimensional histograms
00556 may be better stored in a SparseMat ). The data layout of the array `M` is defined by the array
00557 `M.step[]`, so that the address of element \f$(i_0,...,i_{M.dims-1})\f$, where \f$0\leq i_k<M.size[k]\f$, is
00558 computed as:
00559 \f[addr(M_{i_0,...,i_{M.dims-1}}) = M.data + M.step[0]*i_0 + M.step[1]*i_1 + ... + M.step[M.dims-1]*i_{M.dims-1}\f]
00560 In case of a 2-dimensional array, the above formula is reduced to:
00561 \f[addr(M_{i,j}) = M.data + M.step[0]*i + M.step[1]*j\f]
00562 Note that `M.step[i] >= M.step[i+1]` (in fact, `M.step[i] >= M.step[i+1]*M.size[i+1]` ). This means
00563 that 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane,
00564 and so on. M.step[M.dims-1] is minimal and always equal to the element size M.elemSize() .
00565 
00566 So, the data layout in Mat is fully compatible with CvMat, IplImage, and CvMatND types from OpenCV
00567 1.x. It is also compatible with the majority of dense array types from the standard toolkits and
00568 SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others, that is, with any
00569 array that uses *steps* (or *strides*) to compute the position of a pixel. Due to this
00570 compatibility, it is possible to make a Mat header for user-allocated data and process it in-place
00571 using OpenCV functions.
00572 
00573 There are many different ways to create a Mat object. The most popular options are listed below:
00574 
00575 - Use the create(nrows, ncols, type) method or the similar Mat(nrows, ncols, type[, fillValue])
00576 constructor. A new array of the specified size and type is allocated. type has the same meaning as
00577 in the cvCreateMat method. For example, CV_8UC1 means a 8-bit single-channel array, CV_32FC2
00578 means a 2-channel (complex) floating-point array, and so on.
00579 @code
00580     // make a 7x7 complex matrix filled with 1+3j.
00581     Mat M(7,7,CV_32FC2,Scalar(1,3));
00582     // and now turn M to a 100x60 15-channel 8-bit matrix.
00583     // The old content will be deallocated
00584     M.create(100,60,CV_8UC(15));
00585 @endcode
00586 As noted in the introduction to this chapter, create() allocates only a new array when the shape
00587 or type of the current array are different from the specified ones.
00588 
00589 - Create a multi-dimensional array:
00590 @code
00591     // create a 100x100x100 8-bit array
00592     int sz[] = {100, 100, 100};
00593     Mat bigCube(3, sz, CV_8U, Scalar::all(0));
00594 @endcode
00595 It passes the number of dimensions =1 to the Mat constructor but the created array will be
00596 2-dimensional with the number of columns set to 1. So, Mat::dims is always >= 2 (can also be 0
00597 when the array is empty).
00598 
00599 - Use a copy constructor or assignment operator where there can be an array or expression on the
00600 right side (see below). As noted in the introduction, the array assignment is an O(1) operation
00601 because it only copies the header and increases the reference counter. The Mat::clone() method can
00602 be used to get a full (deep) copy of the array when you need it.
00603 
00604 - Construct a header for a part of another array. It can be a single row, single column, several
00605 rows, several columns, rectangular region in the array (called a *minor* in algebra) or a
00606 diagonal. Such operations are also O(1) because the new header references the same data. You can
00607 actually modify a part of the array using this feature, for example:
00608 @code
00609     // add the 5-th row, multiplied by 3 to the 3rd row
00610     M.row(3) = M.row(3) + M.row(5)*3;
00611     // now copy the 7-th column to the 1-st column
00612     // M.col(1) = M.col(7); // this will not work
00613     Mat M1 = M.col(1);
00614     M.col(7).copyTo(M1);
00615     // create a new 320x240 image
00616     Mat img(Size(320,240),CV_8UC3);
00617     // select a ROI
00618     Mat roi(img, Rect(10,10,100,100));
00619     // fill the ROI with (0,255,0) (which is green in RGB space);
00620     // the original 320x240 image will be modified
00621     roi = Scalar(0,255,0);
00622 @endcode
00623 Due to the additional datastart and dataend members, it is possible to compute a relative
00624 sub-array position in the main *container* array using locateROI():
00625 @code
00626     Mat A = Mat::eye(10, 10, CV_32S);
00627     // extracts A columns, 1 (inclusive) to 3 (exclusive).
00628     Mat B = A(Range::all(), Range(1, 3));
00629     // extracts B rows, 5 (inclusive) to 9 (exclusive).
00630     // that is, C \~ A(Range(5, 9), Range(1, 3))
00631     Mat C = B(Range(5, 9), Range::all());
00632     Size size; Point ofs;
00633     C.locateROI(size, ofs);
00634     // size will be (width=10,height=10) and the ofs will be (x=1, y=5)
00635 @endcode
00636 As in case of whole matrices, if you need a deep copy, use the `clone()` method of the extracted
00637 sub-matrices.
00638 
00639 - Make a header for user-allocated data. It can be useful to do the following:
00640     -# Process "foreign" data using OpenCV (for example, when you implement a DirectShow\* filter or
00641     a processing module for gstreamer, and so on). For example:
00642     @code
00643         void process_video_frame(const unsigned char* pixels,
00644                                  int width, int height, int step)
00645         {
00646             Mat img(height, width, CV_8UC3, pixels, step);
00647             GaussianBlur(img, img, Size(7,7), 1.5, 1.5);
00648         }
00649     @endcode
00650     -# Quickly initialize small matrices and/or get a super-fast element access.
00651     @code
00652         double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
00653         Mat M = Mat(3, 3, CV_64F, m).inv();
00654     @endcode
00655     .
00656     Partial yet very common cases of this *user-allocated data* case are conversions from CvMat and
00657     IplImage to Mat. For this purpose, there is function cv::cvarrToMat taking pointers to CvMat or
00658     IplImage and the optional flag indicating whether to copy the data or not.
00659     @snippet samples/cpp/image.cpp iplimage
00660 
00661 - Use MATLAB-style array initializers, zeros(), ones(), eye(), for example:
00662 @code
00663     // create a double-precision identity martix and add it to M.
00664     M += Mat::eye(M.rows, M.cols, CV_64F);
00665 @endcode
00666 
00667 - Use a comma-separated initializer:
00668 @code
00669     // create a 3x3 double-precision identity matrix
00670     Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
00671 @endcode
00672 With this approach, you first call a constructor of the Mat class with the proper parameters, and
00673 then you just put `<< operator` followed by comma-separated values that can be constants,
00674 variables, expressions, and so on. Also, note the extra parentheses required to avoid compilation
00675 errors.
00676 
00677 Once the array is created, it is automatically managed via a reference-counting mechanism. If the
00678 array header is built on top of user-allocated data, you should handle the data by yourself. The
00679 array data is deallocated when no one points to it. If you want to release the data pointed by a
00680 array header before the array destructor is called, use Mat::release().
00681 
00682 The next important thing to learn about the array class is element access. This manual already
00683 described how to compute an address of each array element. Normally, you are not required to use the
00684 formula directly in the code. If you know the array element type (which can be retrieved using the
00685 method Mat::type() ), you can access the element \f$M_{ij}\f$ of a 2-dimensional array as:
00686 @code
00687     M.at<double>(i,j) += 1.f;
00688 @endcode
00689 assuming that `M` is a double-precision floating-point array. There are several variants of the method
00690 at for a different number of dimensions.
00691 
00692 If you need to process a whole row of a 2D array, the most efficient way is to get the pointer to
00693 the row first, and then just use the plain C operator [] :
00694 @code
00695     // compute sum of positive matrix elements
00696     // (assuming that M isa double-precision matrix)
00697     double sum=0;
00698     for(int i = 0; i < M.rows; i++)
00699     {
00700         const double* Mi = M.ptr<double>(i);
00701         for(int j = 0; j < M.cols; j++)
00702             sum += std::max(Mi[j], 0.);
00703     }
00704 @endcode
00705 Some operations, like the one above, do not actually depend on the array shape. They just process
00706 elements of an array one by one (or elements from multiple arrays that have the same coordinates,
00707 for example, array addition). Such operations are called *element-wise*. It makes sense to check
00708 whether all the input/output arrays are continuous, namely, have no gaps at the end of each row. If
00709 yes, process them as a long single row:
00710 @code
00711     // compute the sum of positive matrix elements, optimized variant
00712     double sum=0;
00713     int cols = M.cols, rows = M.rows;
00714     if(M.isContinuous())
00715     {
00716         cols *= rows;
00717         rows = 1;
00718     }
00719     for(int i = 0; i < rows; i++)
00720     {
00721         const double* Mi = M.ptr<double>(i);
00722         for(int j = 0; j < cols; j++)
00723             sum += std::max(Mi[j], 0.);
00724     }
00725 @endcode
00726 In case of the continuous matrix, the outer loop body is executed just once. So, the overhead is
00727 smaller, which is especially noticeable in case of small matrices.
00728 
00729 Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:
00730 @code
00731     // compute sum of positive matrix elements, iterator-based variant
00732     double sum=0;
00733     MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
00734     for(; it != it_end; ++it)
00735         sum += std::max(*it, 0.);
00736 @endcode
00737 The matrix iterators are random-access iterators, so they can be passed to any STL algorithm,
00738 including std::sort().
00739 */
00740 class CV_EXPORTS Mat
00741 {
00742 public:
00743     /**
00744     These are various constructors that form a matrix. As noted in the AutomaticAllocation, often
00745     the default constructor is enough, and the proper matrix will be allocated by an OpenCV function.
00746     The constructed matrix can further be assigned to another matrix or matrix expression or can be
00747     allocated with Mat::create . In the former case, the old content is de-referenced.
00748      */
00749     Mat();
00750 
00751     /** @overload
00752     @param rows Number of rows in a 2D array.
00753     @param cols Number of columns in a 2D array.
00754     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
00755     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
00756     */
00757     Mat(int rows, int cols, int type);
00758 
00759     /** @overload
00760     @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the
00761     number of columns go in the reverse order.
00762     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
00763     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
00764       */
00765     Mat(Size size, int type);
00766 
00767     /** @overload
00768     @param rows Number of rows in a 2D array.
00769     @param cols Number of columns in a 2D array.
00770     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
00771     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
00772     @param s An optional value to initialize each matrix element with. To set all the matrix elements to
00773     the particular value after the construction, use the assignment operator
00774     Mat::operator=(const Scalar& value) .
00775     */
00776     Mat(int rows, int cols, int type, const Scalar & s);
00777 
00778     /** @overload
00779     @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the
00780     number of columns go in the reverse order.
00781     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
00782     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
00783     @param s An optional value to initialize each matrix element with. To set all the matrix elements to
00784     the particular value after the construction, use the assignment operator
00785     Mat::operator=(const Scalar& value) .
00786       */
00787     Mat(Size size, int type, const Scalar & s);
00788 
00789     /** @overload
00790     @param ndims Array dimensionality.
00791     @param sizes Array of integers specifying an n-dimensional array shape.
00792     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
00793     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
00794     */
00795     Mat(int ndims, const int* sizes, int type);
00796 
00797     /** @overload
00798     @param sizes Array of integers specifying an n-dimensional array shape.
00799     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
00800     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
00801     */
00802     Mat(const std::vector<int>& sizes, int type);
00803 
00804     /** @overload
00805     @param ndims Array dimensionality.
00806     @param sizes Array of integers specifying an n-dimensional array shape.
00807     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
00808     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
00809     @param s An optional value to initialize each matrix element with. To set all the matrix elements to
00810     the particular value after the construction, use the assignment operator
00811     Mat::operator=(const Scalar& value) .
00812     */
00813     Mat(int ndims, const int* sizes, int type, const Scalar & s);
00814 
00815     /** @overload
00816     @param sizes Array of integers specifying an n-dimensional array shape.
00817     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
00818     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
00819     @param s An optional value to initialize each matrix element with. To set all the matrix elements to
00820     the particular value after the construction, use the assignment operator
00821     Mat::operator=(const Scalar& value) .
00822     */
00823     Mat(const std::vector<int>& sizes, int type, const Scalar & s);
00824 
00825 
00826     /** @overload
00827     @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
00828     by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
00829     associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
00830     formed using such a constructor, you also modify the corresponding elements of m . If you want to
00831     have an independent copy of the sub-array, use Mat::clone() .
00832     */
00833     Mat(const Mat& m);
00834 
00835     /** @overload
00836     @param rows Number of rows in a 2D array.
00837     @param cols Number of columns in a 2D array.
00838     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
00839     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
00840     @param data Pointer to the user data. Matrix constructors that take data and step parameters do not
00841     allocate matrix data. Instead, they just initialize the matrix header that points to the specified
00842     data, which means that no data is copied. This operation is very efficient and can be used to
00843     process external data using OpenCV functions. The external data is not automatically deallocated, so
00844     you should take care of it.
00845     @param step Number of bytes each matrix row occupies. The value should include the padding bytes at
00846     the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed
00847     and the actual step is calculated as cols*elemSize(). See Mat::elemSize.
00848     */
00849     Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP);
00850 
00851     /** @overload
00852     @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the
00853     number of columns go in the reverse order.
00854     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
00855     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
00856     @param data Pointer to the user data. Matrix constructors that take data and step parameters do not
00857     allocate matrix data. Instead, they just initialize the matrix header that points to the specified
00858     data, which means that no data is copied. This operation is very efficient and can be used to
00859     process external data using OpenCV functions. The external data is not automatically deallocated, so
00860     you should take care of it.
00861     @param step Number of bytes each matrix row occupies. The value should include the padding bytes at
00862     the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed
00863     and the actual step is calculated as cols*elemSize(). See Mat::elemSize.
00864     */
00865     Mat(Size size, int type, void* data, size_t step=AUTO_STEP);
00866 
00867     /** @overload
00868     @param ndims Array dimensionality.
00869     @param sizes Array of integers specifying an n-dimensional array shape.
00870     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
00871     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
00872     @param data Pointer to the user data. Matrix constructors that take data and step parameters do not
00873     allocate matrix data. Instead, they just initialize the matrix header that points to the specified
00874     data, which means that no data is copied. This operation is very efficient and can be used to
00875     process external data using OpenCV functions. The external data is not automatically deallocated, so
00876     you should take care of it.
00877     @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always
00878     set to the element size). If not specified, the matrix is assumed to be continuous.
00879     */
00880     Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0);
00881 
00882     /** @overload
00883     @param sizes Array of integers specifying an n-dimensional array shape.
00884     @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
00885     CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
00886     @param data Pointer to the user data. Matrix constructors that take data and step parameters do not
00887     allocate matrix data. Instead, they just initialize the matrix header that points to the specified
00888     data, which means that no data is copied. This operation is very efficient and can be used to
00889     process external data using OpenCV functions. The external data is not automatically deallocated, so
00890     you should take care of it.
00891     @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always
00892     set to the element size). If not specified, the matrix is assumed to be continuous.
00893     */
00894     Mat(const std::vector<int>& sizes, int type, void* data, const size_t* steps=0);
00895 
00896     /** @overload
00897     @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
00898     by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
00899     associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
00900     formed using such a constructor, you also modify the corresponding elements of m . If you want to
00901     have an independent copy of the sub-array, use Mat::clone() .
00902     @param rowRange Range of the m rows to take. As usual, the range start is inclusive and the range
00903     end is exclusive. Use Range::all() to take all the rows.
00904     @param colRange Range of the m columns to take. Use Range::all() to take all the columns.
00905     */
00906     Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all());
00907 
00908     /** @overload
00909     @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
00910     by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
00911     associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
00912     formed using such a constructor, you also modify the corresponding elements of m . If you want to
00913     have an independent copy of the sub-array, use Mat::clone() .
00914     @param roi Region of interest.
00915     */
00916     Mat(const Mat& m, const Rect& roi);
00917 
00918     /** @overload
00919     @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
00920     by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
00921     associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
00922     formed using such a constructor, you also modify the corresponding elements of m . If you want to
00923     have an independent copy of the sub-array, use Mat::clone() .
00924     @param ranges Array of selected ranges of m along each dimensionality.
00925     */
00926     Mat(const Mat& m, const Range* ranges);
00927 
00928     /** @overload
00929     @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
00930     by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
00931     associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
00932     formed using such a constructor, you also modify the corresponding elements of m . If you want to
00933     have an independent copy of the sub-array, use Mat::clone() .
00934     @param ranges Array of selected ranges of m along each dimensionality.
00935     */
00936     Mat(const Mat& m, const std::vector<Range>& ranges);
00937 
00938     /** @overload
00939     @param vec STL vector whose elements form the matrix. The matrix has a single column and the number
00940     of rows equal to the number of vector elements. Type of the matrix matches the type of vector
00941     elements. The constructor can handle arbitrary types, for which there is a properly declared
00942     DataType . This means that the vector elements must be primitive numbers or uni-type numerical
00943     tuples of numbers. Mixed-type structures are not supported. The corresponding constructor is
00944     explicit. Since STL vectors are not automatically converted to Mat instances, you should write
00945     Mat(vec) explicitly. Unless you copy the data into the matrix ( copyData=true ), no new elements
00946     will be added to the vector because it can potentially yield vector data reallocation, and, thus,
00947     the matrix data pointer will be invalid.
00948     @param copyData Flag to specify whether the underlying data of the STL vector should be copied
00949     to (true) or shared with (false) the newly constructed matrix. When the data is copied, the
00950     allocated buffer is managed using Mat reference counting mechanism. While the data is shared,
00951     the reference counter is NULL, and you should not deallocate the data until the matrix is not
00952     destructed.
00953     */
00954     template<typename _Tp> explicit Mat(const std::vector<_Tp>& vec, bool copyData=false);
00955 
00956     /** @overload
00957     */
00958     template<typename _Tp, int n> explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true);
00959 
00960     /** @overload
00961     */
00962     template<typename _Tp, int m, int n> explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
00963 
00964     /** @overload
00965     */
00966     template<typename _Tp> explicit Mat(const Point_<_Tp>& pt, bool copyData=true);
00967 
00968     /** @overload
00969     */
00970     template<typename _Tp> explicit Mat(const Point3_<_Tp>& pt, bool copyData=true);
00971 
00972     /** @overload
00973     */
00974     template<typename _Tp> explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer);
00975 
00976     //! download data from GpuMat
00977     explicit Mat(const cuda::GpuMat& m);
00978 
00979     //! destructor - calls release()
00980     ~Mat();
00981 
00982     /** @brief assignment operators
00983 
00984     These are available assignment operators. Since they all are very different, make sure to read the
00985     operator parameters description.
00986     @param m Assigned, right-hand-side matrix. Matrix assignment is an O(1) operation. This means that
00987     no data is copied but the data is shared and the reference counter, if any, is incremented. Before
00988     assigning new data, the old data is de-referenced via Mat::release .
00989      */
00990     Mat& operator = (const Mat& m);
00991 
00992     /** @overload
00993     @param expr Assigned matrix expression object. As opposite to the first form of the assignment
00994     operation, the second form can reuse already allocated matrix if it has the right size and type to
00995     fit the matrix expression result. It is automatically handled by the real function that the matrix
00996     expressions is expanded to. For example, C=A+B is expanded to add(A, B, C), and add takes care of
00997     automatic C reallocation.
00998     */
00999     Mat& operator = (const MatExpr& expr);
01000 
01001     //! retrieve UMat from Mat
01002     UMat  getUMat(int accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const;
01003 
01004     /** @brief Creates a matrix header for the specified matrix row.
01005 
01006     The method makes a new header for the specified matrix row and returns it. This is an O(1)
01007     operation, regardless of the matrix size. The underlying data of the new matrix is shared with the
01008     original matrix. Here is the example of one of the classical basic matrix processing operations,
01009     axpy, used by LU and many other algorithms:
01010     @code
01011         inline void matrix_axpy(Mat& A, int i, int j, double alpha)
01012         {
01013             A.row(i) += A.row(j)*alpha;
01014         }
01015     @endcode
01016     @note In the current implementation, the following code does not work as expected:
01017     @code
01018         Mat A;
01019         ...
01020         A.row(i) = A.row(j); // will not work
01021     @endcode
01022     This happens because A.row(i) forms a temporary header that is further assigned to another header.
01023     Remember that each of these operations is O(1), that is, no data is copied. Thus, the above
01024     assignment is not true if you may have expected the j-th row to be copied to the i-th row. To
01025     achieve that, you should either turn this simple assignment into an expression or use the
01026     Mat::copyTo method:
01027     @code
01028         Mat A;
01029         ...
01030         // works, but looks a bit obscure.
01031         A.row(i) = A.row(j) + 0;
01032         // this is a bit longer, but the recommended method.
01033         A.row(j).copyTo(A.row(i));
01034     @endcode
01035     @param y A 0-based row index.
01036      */
01037     Mat row(int y) const;
01038 
01039     /** @brief Creates a matrix header for the specified matrix column.
01040 
01041     The method makes a new header for the specified matrix column and returns it. This is an O(1)
01042     operation, regardless of the matrix size. The underlying data of the new matrix is shared with the
01043     original matrix. See also the Mat::row description.
01044     @param x A 0-based column index.
01045      */
01046     Mat col(int x) const;
01047 
01048     /** @brief Creates a matrix header for the specified row span.
01049 
01050     The method makes a new header for the specified row span of the matrix. Similarly to Mat::row and
01051     Mat::col , this is an O(1) operation.
01052     @param startrow An inclusive 0-based start index of the row span.
01053     @param endrow An exclusive 0-based ending index of the row span.
01054      */
01055     Mat rowRange(int startrow, int endrow) const;
01056 
01057     /** @overload
01058     @param r Range structure containing both the start and the end indices.
01059     */
01060     Mat rowRange(const Range& r) const;
01061 
01062     /** @brief Creates a matrix header for the specified column span.
01063 
01064     The method makes a new header for the specified column span of the matrix. Similarly to Mat::row and
01065     Mat::col , this is an O(1) operation.
01066     @param startcol An inclusive 0-based start index of the column span.
01067     @param endcol An exclusive 0-based ending index of the column span.
01068      */
01069     Mat colRange(int startcol, int endcol) const;
01070 
01071     /** @overload
01072     @param r Range structure containing both the start and the end indices.
01073     */
01074     Mat colRange(const Range& r) const;
01075 
01076     /** @brief Extracts a diagonal from a matrix
01077 
01078     The method makes a new header for the specified matrix diagonal. The new matrix is represented as a
01079     single-column matrix. Similarly to Mat::row and Mat::col, this is an O(1) operation.
01080     @param d index of the diagonal, with the following values:
01081     - `d=0` is the main diagonal.
01082     - `d>0` is a diagonal from the lower half. For example, d=1 means the diagonal is set
01083       immediately below the main one.
01084     - `d<0` is a diagonal from the upper half. For example, d=-1 means the diagonal is set
01085       immediately above the main one.
01086      */
01087     Mat diag(int d=0) const;
01088 
01089     /** @brief creates a diagonal matrix
01090 
01091     The method creates a square diagonal matrix from specified main diagonal.
01092     @param d One-dimensional matrix that represents the main diagonal.
01093      */
01094     static Mat diag(const Mat& d);
01095 
01096     /** @brief Creates a full copy of the array and the underlying data.
01097 
01098     The method creates a full copy of the array. The original step[] is not taken into account. So, the
01099     array copy is a continuous array occupying total()*elemSize() bytes.
01100      */
01101     Mat clone() const;
01102 
01103     /** @brief Copies the matrix to another one.
01104 
01105     The method copies the matrix data to another matrix. Before copying the data, the method invokes :
01106     @code
01107         m.create(this->size(), this->type());
01108     @endcode
01109     so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the
01110     function does not handle the case of a partial overlap between the source and the destination
01111     matrices.
01112 
01113     When the operation mask is specified, if the Mat::create call shown above reallocates the matrix,
01114     the newly allocated matrix is initialized with all zeros before copying the data.
01115     @param m Destination matrix. If it does not have a proper size or type before the operation, it is
01116     reallocated.
01117      */
01118     void copyTo( OutputArray m ) const;
01119 
01120     /** @overload
01121     @param m Destination matrix. If it does not have a proper size or type before the operation, it is
01122     reallocated.
01123     @param mask Operation mask. Its non-zero elements indicate which matrix elements need to be copied.
01124     The mask has to be of type CV_8U and can have 1 or multiple channels.
01125     */
01126     void copyTo( OutputArray m, InputArray mask ) const;
01127 
01128     /** @brief Converts an array to another data type with optional scaling.
01129 
01130     The method converts source pixel values to the target data type. saturate_cast<> is applied at
01131     the end to avoid possible overflows:
01132 
01133     \f[m(x,y) = saturate \_ cast<rType>( \alpha (*this)(x,y) +  \beta )\f]
01134     @param m output matrix; if it does not have a proper size or type before the operation, it is
01135     reallocated.
01136     @param rtype desired output matrix type or, rather, the depth since the number of channels are the
01137     same as the input has; if rtype is negative, the output matrix will have the same type as the input.
01138     @param alpha optional scale factor.
01139     @param beta optional delta added to the scaled values.
01140      */
01141     void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
01142 
01143     /** @brief Provides a functional form of convertTo.
01144 
01145     This is an internally used method called by the @ref MatrixExpressions engine.
01146     @param m Destination array.
01147     @param type Desired destination array depth (or -1 if it should be the same as the source type).
01148      */
01149     void assignTo( Mat& m, int type=-1 ) const;
01150 
01151     /** @brief Sets all or some of the array elements to the specified value.
01152     @param s Assigned scalar converted to the actual array type.
01153     */
01154     Mat& operator = (const Scalar & s);
01155 
01156     /** @brief Sets all or some of the array elements to the specified value.
01157 
01158     This is an advanced variant of the Mat::operator=(const Scalar& s) operator.
01159     @param value Assigned scalar converted to the actual array type.
01160     @param mask Operation mask of the same size as \*this.
01161      */
01162     Mat& setTo(InputArray value, InputArray mask=noArray());
01163 
01164     /** @brief Changes the shape and/or the number of channels of a 2D matrix without copying the data.
01165 
01166     The method makes a new matrix header for \*this elements. The new matrix may have a different size
01167     and/or different number of channels. Any combination is possible if:
01168     -   No extra elements are included into the new matrix and no elements are excluded. Consequently,
01169         the product rows\*cols\*channels() must stay the same after the transformation.
01170     -   No data is copied. That is, this is an O(1) operation. Consequently, if you change the number of
01171         rows, or the operation changes the indices of elements row in some other way, the matrix must be
01172         continuous. See Mat::isContinuous .
01173 
01174     For example, if there is a set of 3D points stored as an STL vector, and you want to represent the
01175     points as a 3xN matrix, do the following:
01176     @code
01177         std::vector<Point3f> vec;
01178         ...
01179         Mat pointMat = Mat(vec). // convert vector to Mat, O(1) operation
01180                           reshape(1). // make Nx3 1-channel matrix out of Nx1 3-channel.
01181                                       // Also, an O(1) operation
01182                              t(); // finally, transpose the Nx3 matrix.
01183                                   // This involves copying all the elements
01184     @endcode
01185     @param cn New number of channels. If the parameter is 0, the number of channels remains the same.
01186     @param rows New number of rows. If the parameter is 0, the number of rows remains the same.
01187      */
01188     Mat reshape(int cn, int rows=0) const;
01189 
01190     /** @overload */
01191     Mat reshape(int cn, int newndims, const int* newsz) const;
01192 
01193     /** @brief Transposes a matrix.
01194 
01195     The method performs matrix transposition by means of matrix expressions. It does not perform the
01196     actual transposition but returns a temporary matrix transposition object that can be further used as
01197     a part of more complex matrix expressions or can be assigned to a matrix:
01198     @code
01199         Mat A1 = A + Mat::eye(A.size(), A.type())*lambda;
01200         Mat C = A1.t()*A1; // compute (A + lambda*I)^t * (A + lamda*I)
01201     @endcode
01202      */
01203     MatExpr t() const;
01204 
01205     /** @brief Inverses a matrix.
01206 
01207     The method performs a matrix inversion by means of matrix expressions. This means that a temporary
01208     matrix inversion object is returned by the method and can be used further as a part of more complex
01209     matrix expressions or can be assigned to a matrix.
01210     @param method Matrix inversion method. One of cv::DecompTypes
01211      */
01212     MatExpr inv(int method=DECOMP_LU) const;
01213 
01214     /** @brief Performs an element-wise multiplication or division of the two matrices.
01215 
01216     The method returns a temporary object encoding per-element array multiplication, with optional
01217     scale. Note that this is not a matrix multiplication that corresponds to a simpler "\*" operator.
01218 
01219     Example:
01220     @code
01221         Mat C = A.mul(5/B); // equivalent to divide(A, B, C, 5)
01222     @endcode
01223     @param m Another array of the same type and the same size as \*this, or a matrix expression.
01224     @param scale Optional scale factor.
01225      */
01226     MatExpr mul(InputArray m, double scale=1) const;
01227 
01228     /** @brief Computes a cross-product of two 3-element vectors.
01229 
01230     The method computes a cross-product of two 3-element vectors. The vectors must be 3-element
01231     floating-point vectors of the same shape and size. The result is another 3-element vector of the
01232     same shape and type as operands.
01233     @param m Another cross-product operand.
01234      */
01235     Mat cross(InputArray m) const;
01236 
01237     /** @brief Computes a dot-product of two vectors.
01238 
01239     The method computes a dot-product of two matrices. If the matrices are not single-column or
01240     single-row vectors, the top-to-bottom left-to-right scan ordering is used to treat them as 1D
01241     vectors. The vectors must have the same size and type. If the matrices have more than one channel,
01242     the dot products from all the channels are summed together.
01243     @param m another dot-product operand.
01244      */
01245     double dot(InputArray m) const;
01246 
01247     /** @brief Returns a zero array of the specified size and type.
01248 
01249     The method returns a Matlab-style zero array initializer. It can be used to quickly form a constant
01250     array as a function parameter, part of a matrix expression, or as a matrix initializer. :
01251     @code
01252         Mat A;
01253         A = Mat::zeros(3, 3, CV_32F);
01254     @endcode
01255     In the example above, a new matrix is allocated only if A is not a 3x3 floating-point matrix.
01256     Otherwise, the existing matrix A is filled with zeros.
01257     @param rows Number of rows.
01258     @param cols Number of columns.
01259     @param type Created matrix type.
01260      */
01261     static MatExpr zeros(int rows, int cols, int type);
01262 
01263     /** @overload
01264     @param size Alternative to the matrix size specification Size(cols, rows) .
01265     @param type Created matrix type.
01266     */
01267     static MatExpr zeros(Size size, int type);
01268 
01269     /** @overload
01270     @param ndims Array dimensionality.
01271     @param sz Array of integers specifying the array shape.
01272     @param type Created matrix type.
01273     */
01274     static MatExpr zeros(int ndims, const int* sz, int type);
01275 
01276     /** @brief Returns an array of all 1's of the specified size and type.
01277 
01278     The method returns a Matlab-style 1's array initializer, similarly to Mat::zeros. Note that using
01279     this method you can initialize an array with an arbitrary value, using the following Matlab idiom:
01280     @code
01281         Mat A = Mat::ones(100, 100, CV_8U)*3; // make 100x100 matrix filled with 3.
01282     @endcode
01283     The above operation does not form a 100x100 matrix of 1's and then multiply it by 3. Instead, it
01284     just remembers the scale factor (3 in this case) and use it when actually invoking the matrix
01285     initializer.
01286     @param rows Number of rows.
01287     @param cols Number of columns.
01288     @param type Created matrix type.
01289      */
01290     static MatExpr ones(int rows, int cols, int type);
01291 
01292     /** @overload
01293     @param size Alternative to the matrix size specification Size(cols, rows) .
01294     @param type Created matrix type.
01295     */
01296     static MatExpr ones(Size size, int type);
01297 
01298     /** @overload
01299     @param ndims Array dimensionality.
01300     @param sz Array of integers specifying the array shape.
01301     @param type Created matrix type.
01302     */
01303     static MatExpr ones(int ndims, const int* sz, int type);
01304 
01305     /** @brief Returns an identity matrix of the specified size and type.
01306 
01307     The method returns a Matlab-style identity matrix initializer, similarly to Mat::zeros. Similarly to
01308     Mat::ones, you can use a scale operation to create a scaled identity matrix efficiently:
01309     @code
01310         // make a 4x4 diagonal matrix with 0.1's on the diagonal.
01311         Mat A = Mat::eye(4, 4, CV_32F)*0.1;
01312     @endcode
01313     @param rows Number of rows.
01314     @param cols Number of columns.
01315     @param type Created matrix type.
01316      */
01317     static MatExpr eye(int rows, int cols, int type);
01318 
01319     /** @overload
01320     @param size Alternative matrix size specification as Size(cols, rows) .
01321     @param type Created matrix type.
01322     */
01323     static MatExpr eye(Size size, int type);
01324 
01325     /** @brief Allocates new array data if needed.
01326 
01327     This is one of the key Mat methods. Most new-style OpenCV functions and methods that produce arrays
01328     call this method for each output array. The method uses the following algorithm:
01329 
01330     -# If the current array shape and the type match the new ones, return immediately. Otherwise,
01331        de-reference the previous data by calling Mat::release.
01332     -# Initialize the new header.
01333     -# Allocate the new data of total()\*elemSize() bytes.
01334     -# Allocate the new, associated with the data, reference counter and set it to 1.
01335 
01336     Such a scheme makes the memory management robust and efficient at the same time and helps avoid
01337     extra typing for you. This means that usually there is no need to explicitly allocate output arrays.
01338     That is, instead of writing:
01339     @code
01340         Mat color;
01341         ...
01342         Mat gray(color.rows, color.cols, color.depth());
01343         cvtColor(color, gray, COLOR_BGR2GRAY);
01344     @endcode
01345     you can simply write:
01346     @code
01347         Mat color;
01348         ...
01349         Mat gray;
01350         cvtColor(color, gray, COLOR_BGR2GRAY);
01351     @endcode
01352     because cvtColor, as well as the most of OpenCV functions, calls Mat::create() for the output array
01353     internally.
01354     @param rows New number of rows.
01355     @param cols New number of columns.
01356     @param type New matrix type.
01357      */
01358     void create(int rows, int cols, int type);
01359 
01360     /** @overload
01361     @param size Alternative new matrix size specification: Size(cols, rows)
01362     @param type New matrix type.
01363     */
01364     void create(Size size, int type);
01365 
01366     /** @overload
01367     @param ndims New array dimensionality.
01368     @param sizes Array of integers specifying a new array shape.
01369     @param type New matrix type.
01370     */
01371     void create(int ndims, const int* sizes, int type);
01372 
01373     /** @overload
01374     @param sizes Array of integers specifying a new array shape.
01375     @param type New matrix type.
01376     */
01377     void create(const std::vector<int>& sizes, int type);
01378 
01379     /** @brief Increments the reference counter.
01380 
01381     The method increments the reference counter associated with the matrix data. If the matrix header
01382     points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no
01383     effect in this case. Normally, to avoid memory leaks, the method should not be called explicitly. It
01384     is called implicitly by the matrix assignment operator. The reference counter increment is an atomic
01385     operation on the platforms that support it. Thus, it is safe to operate on the same matrices
01386     asynchronously in different threads.
01387      */
01388     void addref();
01389 
01390     /** @brief Decrements the reference counter and deallocates the matrix if needed.
01391 
01392     The method decrements the reference counter associated with the matrix data. When the reference
01393     counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers
01394     are set to NULL's. If the matrix header points to an external data set (see Mat::Mat ), the
01395     reference counter is NULL, and the method has no effect in this case.
01396 
01397     This method can be called manually to force the matrix data deallocation. But since this method is
01398     automatically called in the destructor, or by any other method that changes the data pointer, it is
01399     usually not needed. The reference counter decrement and check for 0 is an atomic operation on the
01400     platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in
01401     different threads.
01402      */
01403     void release();
01404 
01405     //! deallocates the matrix data
01406     void deallocate();
01407     //! internal use function; properly re-allocates _size, _step arrays
01408     void copySize(const Mat& m);
01409 
01410     /** @brief Reserves space for the certain number of rows.
01411 
01412     The method reserves space for sz rows. If the matrix already has enough space to store sz rows,
01413     nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method
01414     emulates the corresponding method of the STL vector class.
01415     @param sz Number of rows.
01416      */
01417     void reserve(size_t sz);
01418 
01419     /** @brief Changes the number of matrix rows.
01420 
01421     The methods change the number of matrix rows. If the matrix is reallocated, the first
01422     min(Mat::rows, sz) rows are preserved. The methods emulate the corresponding methods of the STL
01423     vector class.
01424     @param sz New number of rows.
01425      */
01426     void resize(size_t sz);
01427 
01428     /** @overload
01429     @param sz New number of rows.
01430     @param s Value assigned to the newly added elements.
01431      */
01432     void resize(size_t sz, const Scalar & s);
01433 
01434     //! internal function
01435     void push_back_(const void* elem);
01436 
01437     /** @brief Adds elements to the bottom of the matrix.
01438 
01439     The methods add one or more elements to the bottom of the matrix. They emulate the corresponding
01440     method of the STL vector class. When elem is Mat , its type and the number of columns must be the
01441     same as in the container matrix.
01442     @param elem Added element(s).
01443      */
01444     template<typename _Tp> void push_back(const _Tp& elem);
01445 
01446     /** @overload
01447     @param elem Added element(s).
01448     */
01449     template<typename _Tp> void push_back(const Mat_<_Tp>& elem);
01450 
01451     /** @overload
01452     @param m Added line(s).
01453     */
01454     void push_back(const Mat& m);
01455 
01456     /** @brief Removes elements from the bottom of the matrix.
01457 
01458     The method removes one or more rows from the bottom of the matrix.
01459     @param nelems Number of removed rows. If it is greater than the total number of rows, an exception
01460     is thrown.
01461      */
01462     void pop_back(size_t nelems=1);
01463 
01464     /** @brief Locates the matrix header within a parent matrix.
01465 
01466     After you extracted a submatrix from a matrix using Mat::row, Mat::col, Mat::rowRange,
01467     Mat::colRange, and others, the resultant submatrix points just to the part of the original big
01468     matrix. However, each submatrix contains information (represented by datastart and dataend
01469     fields) that helps reconstruct the original matrix size and the position of the extracted
01470     submatrix within the original matrix. The method locateROI does exactly that.
01471     @param wholeSize Output parameter that contains the size of the whole matrix containing *this*
01472     as a part.
01473     @param ofs Output parameter that contains an offset of *this* inside the whole matrix.
01474      */
01475     void locateROI( Size& wholeSize, Point& ofs ) const;
01476 
01477     /** @brief Adjusts a submatrix size and position within the parent matrix.
01478 
01479     The method is complimentary to Mat::locateROI . The typical use of these functions is to determine
01480     the submatrix position within the parent matrix and then shift the position somehow. Typically, it
01481     can be required for filtering operations when pixels outside of the ROI should be taken into
01482     account. When all the method parameters are positive, the ROI needs to grow in all directions by the
01483     specified amount, for example:
01484     @code
01485         A.adjustROI(2, 2, 2, 2);
01486     @endcode
01487     In this example, the matrix size is increased by 4 elements in each direction. The matrix is shifted
01488     by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the
01489     filtering with the 5x5 kernel.
01490 
01491     adjustROI forces the adjusted ROI to be inside of the parent matrix that is boundaries of the
01492     adjusted ROI are constrained by boundaries of the parent matrix. For example, if the submatrix A is
01493     located in the first row of a parent matrix and you called A.adjustROI(2, 2, 2, 2) then A will not
01494     be increased in the upward direction.
01495 
01496     The function is used internally by the OpenCV filtering functions, like filter2D , morphological
01497     operations, and so on.
01498     @param dtop Shift of the top submatrix boundary upwards.
01499     @param dbottom Shift of the bottom submatrix boundary downwards.
01500     @param dleft Shift of the left submatrix boundary to the left.
01501     @param dright Shift of the right submatrix boundary to the right.
01502     @sa copyMakeBorder
01503      */
01504     Mat& adjustROI( int dtop, int dbottom, int dleft, int dright );
01505 
01506     /** @brief Extracts a rectangular submatrix.
01507 
01508     The operators make a new header for the specified sub-array of \*this . They are the most
01509     generalized forms of Mat::row, Mat::col, Mat::rowRange, and Mat::colRange . For example,
01510     `A(Range(0, 10), Range::all())` is equivalent to `A.rowRange(0, 10)`. Similarly to all of the above,
01511     the operators are O(1) operations, that is, no matrix data is copied.
01512     @param rowRange Start and end row of the extracted submatrix. The upper boundary is not included. To
01513     select all the rows, use Range::all().
01514     @param colRange Start and end column of the extracted submatrix. The upper boundary is not included.
01515     To select all the columns, use Range::all().
01516      */
01517     Mat operator()( Range rowRange, Range colRange ) const;
01518 
01519     /** @overload
01520     @param roi Extracted submatrix specified as a rectangle.
01521     */
01522     Mat operator()( const Rect& roi ) const;
01523 
01524     /** @overload
01525     @param ranges Array of selected ranges along each array dimension.
01526     */
01527     Mat operator()( const Range* ranges ) const;
01528 
01529     /** @overload
01530     @param ranges Array of selected ranges along each array dimension.
01531     */
01532     Mat operator()(const std::vector<Range>& ranges) const;
01533 
01534     // //! converts header to CvMat; no data is copied
01535     // operator CvMat() const;
01536     // //! converts header to CvMatND; no data is copied
01537     // operator CvMatND() const;
01538     // //! converts header to IplImage; no data is copied
01539     // operator IplImage() const;
01540 
01541     template<typename _Tp> operator std::vector<_Tp>() const;
01542     template<typename _Tp, int n> operator Vec<_Tp, n>() const;
01543     template<typename _Tp, int m, int n> operator Matx<_Tp, m, n>() const;
01544 
01545     /** @brief Reports whether the matrix is continuous or not.
01546 
01547     The method returns true if the matrix elements are stored continuously without gaps at the end of
01548     each row. Otherwise, it returns false. Obviously, 1x1 or 1xN matrices are always continuous.
01549     Matrices created with Mat::create are always continuous. But if you extract a part of the matrix
01550     using Mat::col, Mat::diag, and so on, or constructed a matrix header for externally allocated data,
01551     such matrices may no longer have this property.
01552 
01553     The continuity flag is stored as a bit in the Mat::flags field and is computed automatically when
01554     you construct a matrix header. Thus, the continuity check is a very fast operation, though
01555     theoretically it could be done as follows:
01556     @code
01557         // alternative implementation of Mat::isContinuous()
01558         bool myCheckMatContinuity(const Mat& m)
01559         {
01560             //return (m.flags & Mat::CONTINUOUS_FLAG) != 0;
01561             return m.rows == 1 || m.step == m.cols*m.elemSize();
01562         }
01563     @endcode
01564     The method is used in quite a few of OpenCV functions. The point is that element-wise operations
01565     (such as arithmetic and logical operations, math functions, alpha blending, color space
01566     transformations, and others) do not depend on the image geometry. Thus, if all the input and output
01567     arrays are continuous, the functions can process them as very long single-row vectors. The example
01568     below illustrates how an alpha-blending function can be implemented:
01569     @code
01570         template<typename T>
01571         void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst)
01572         {
01573             const float alpha_scale = (float)std::numeric_limits<T>::max(),
01574                         inv_scale = 1.f/alpha_scale;
01575 
01576             CV_Assert( src1.type() == src2.type() &&
01577                        src1.type() == CV_MAKETYPE(DataType<T>::depth, 4) &&
01578                        src1.size() == src2.size());
01579             Size size = src1.size();
01580             dst.create(size, src1.type());
01581 
01582             // here is the idiom: check the arrays for continuity and,
01583             // if this is the case,
01584             // treat the arrays as 1D vectors
01585             if( src1.isContinuous() && src2.isContinuous() && dst.isContinuous() )
01586             {
01587                 size.width *= size.height;
01588                 size.height = 1;
01589             }
01590             size.width *= 4;
01591 
01592             for( int i = 0; i < size.height; i++ )
01593             {
01594                 // when the arrays are continuous,
01595                 // the outer loop is executed only once
01596                 const T* ptr1 = src1.ptr<T>(i);
01597                 const T* ptr2 = src2.ptr<T>(i);
01598                 T* dptr = dst.ptr<T>(i);
01599 
01600                 for( int j = 0; j < size.width; j += 4 )
01601                 {
01602                     float alpha = ptr1[j+3]*inv_scale, beta = ptr2[j+3]*inv_scale;
01603                     dptr[j] = saturate_cast<T>(ptr1[j]*alpha + ptr2[j]*beta);
01604                     dptr[j+1] = saturate_cast<T>(ptr1[j+1]*alpha + ptr2[j+1]*beta);
01605                     dptr[j+2] = saturate_cast<T>(ptr1[j+2]*alpha + ptr2[j+2]*beta);
01606                     dptr[j+3] = saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale);
01607                 }
01608             }
01609         }
01610     @endcode
01611     This approach, while being very simple, can boost the performance of a simple element-operation by
01612     10-20 percents, especially if the image is rather small and the operation is quite simple.
01613 
01614     Another OpenCV idiom in this function, a call of Mat::create for the destination array, that
01615     allocates the destination array unless it already has the proper size and type. And while the newly
01616     allocated arrays are always continuous, you still need to check the destination array because
01617     Mat::create does not always allocate a new matrix.
01618      */
01619     bool isContinuous() const;
01620 
01621     //! returns true if the matrix is a submatrix of another matrix
01622     bool isSubmatrix() const;
01623 
01624     /** @brief Returns the matrix element size in bytes.
01625 
01626     The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 ,
01627     the method returns 3\*sizeof(short) or 6.
01628      */
01629     size_t elemSize() const;
01630 
01631     /** @brief Returns the size of each matrix element channel in bytes.
01632 
01633     The method returns the matrix element channel size in bytes, that is, it ignores the number of
01634     channels. For example, if the matrix type is CV_16SC3 , the method returns sizeof(short) or 2.
01635      */
01636     size_t elemSize1() const;
01637 
01638     /** @brief Returns the type of a matrix element.
01639 
01640     The method returns a matrix element type. This is an identifier compatible with the CvMat type
01641     system, like CV_16SC3 or 16-bit signed 3-channel array, and so on.
01642      */
01643     int type() const;
01644 
01645     /** @brief Returns the depth of a matrix element.
01646 
01647     The method returns the identifier of the matrix element depth (the type of each individual channel).
01648     For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of
01649     matrix types contains the following values:
01650     -   CV_8U - 8-bit unsigned integers ( 0..255 )
01651     -   CV_8S - 8-bit signed integers ( -128..127 )
01652     -   CV_16U - 16-bit unsigned integers ( 0..65535 )
01653     -   CV_16S - 16-bit signed integers ( -32768..32767 )
01654     -   CV_32S - 32-bit signed integers ( -2147483648..2147483647 )
01655     -   CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN )
01656     -   CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN )
01657      */
01658     int depth() const;
01659 
01660     /** @brief Returns the number of matrix channels.
01661 
01662     The method returns the number of matrix channels.
01663      */
01664     int channels() const;
01665 
01666     /** @brief Returns a normalized step.
01667 
01668     The method returns a matrix step divided by Mat::elemSize1() . It can be useful to quickly access an
01669     arbitrary matrix element.
01670      */
01671     size_t step1(int i=0) const;
01672 
01673     /** @brief Returns true if the array has no elements.
01674 
01675     The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and
01676     resize() methods `M.total() == 0` does not imply that `M.data == NULL`.
01677      */
01678     bool empty() const;
01679 
01680     /** @brief Returns the total number of array elements.
01681 
01682     The method returns the number of array elements (a number of pixels if the array represents an
01683     image).
01684      */
01685     size_t total() const;
01686 
01687     //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
01688     int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
01689 
01690     /** @brief Returns a pointer to the specified matrix row.
01691 
01692     The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in
01693     Mat::isContinuous to know how to use these methods.
01694     @param i0 A 0-based row index.
01695      */
01696     uchar* ptr(int i0=0);
01697     /** @overload */
01698     const uchar* ptr(int i0=0) const;
01699 
01700     /** @overload
01701     @param row Index along the dimension 0
01702     @param col Index along the dimension 1
01703     */
01704     uchar* ptr(int row, int col);
01705     /** @overload
01706     @param row Index along the dimension 0
01707     @param col Index along the dimension 1
01708     */
01709     const uchar* ptr(int row, int col) const;
01710 
01711     /** @overload */
01712     uchar* ptr(int i0, int i1, int i2);
01713     /** @overload */
01714     const uchar* ptr(int i0, int i1, int i2) const;
01715 
01716     /** @overload */
01717     uchar* ptr(const int* idx);
01718     /** @overload */
01719     const uchar* ptr(const int* idx) const;
01720     /** @overload */
01721     template<int n> uchar* ptr(const Vec<int, n>& idx);
01722     /** @overload */
01723     template<int n> const uchar* ptr(const Vec<int, n>& idx) const;
01724 
01725     /** @overload */
01726     template<typename _Tp> _Tp* ptr(int i0=0);
01727     /** @overload */
01728     template<typename _Tp> const _Tp* ptr(int i0=0) const;
01729     /** @overload
01730     @param row Index along the dimension 0
01731     @param col Index along the dimension 1
01732     */
01733     template<typename _Tp> _Tp* ptr(int row, int col);
01734     /** @overload
01735     @param row Index along the dimension 0
01736     @param col Index along the dimension 1
01737     */
01738     template<typename _Tp> const _Tp* ptr(int row, int col) const;
01739     /** @overload */
01740     template<typename _Tp> _Tp* ptr(int i0, int i1, int i2);
01741     /** @overload */
01742     template<typename _Tp> const _Tp* ptr(int i0, int i1, int i2) const;
01743     /** @overload */
01744     template<typename _Tp> _Tp* ptr(const int* idx);
01745     /** @overload */
01746     template<typename _Tp> const _Tp* ptr(const int* idx) const;
01747     /** @overload */
01748     template<typename _Tp, int n> _Tp* ptr(const Vec<int, n>& idx);
01749     /** @overload */
01750     template<typename _Tp, int n> const _Tp* ptr(const Vec<int, n>& idx) const;
01751 
01752     /** @brief Returns a reference to the specified array element.
01753 
01754     The template methods return a reference to the specified array element. For the sake of higher
01755     performance, the index range checks are only performed in the Debug configuration.
01756 
01757     Note that the variants with a single index (i) can be used to access elements of single-row or
01758     single-column 2-dimensional arrays. That is, if, for example, A is a 1 x N floating-point matrix and
01759     B is an M x 1 integer matrix, you can simply write `A.at<float>(k+4)` and `B.at<int>(2*i+1)`
01760     instead of `A.at<float>(0,k+4)` and `B.at<int>(2*i+1,0)`, respectively.
01761 
01762     The example below initializes a Hilbert matrix:
01763     @code
01764         Mat H(100, 100, CV_64F);
01765         for(int i = 0; i < H.rows; i++)
01766             for(int j = 0; j < H.cols; j++)
01767                 H.at<double>(i,j)=1./(i+j+1);
01768     @endcode
01769 
01770     Keep in mind that the size identifier used in the at operator cannot be chosen at random. It depends
01771     on the image from which you are trying to retrieve the data. The table below gives a better insight in this:
01772      - If matrix is of type `CV_8U` then use `Mat.at<uchar>(y,x)`.
01773      - If matrix is of type `CV_8S` then use `Mat.at<schar>(y,x)`.
01774      - If matrix is of type `CV_16U` then use `Mat.at<ushort>(y,x)`.
01775      - If matrix is of type `CV_16S` then use `Mat.at<short>(y,x)`.
01776      - If matrix is of type `CV_32S`  then use `Mat.at<int>(y,x)`.
01777      - If matrix is of type `CV_32F`  then use `Mat.at<float>(y,x)`.
01778      - If matrix is of type `CV_64F` then use `Mat.at<double>(y,x)`.
01779 
01780     @param i0 Index along the dimension 0
01781      */
01782     template<typename _Tp> _Tp& at(int i0=0);
01783     /** @overload
01784     @param i0 Index along the dimension 0
01785     */
01786     template<typename _Tp> const _Tp& at(int i0=0) const;
01787     /** @overload
01788     @param row Index along the dimension 0
01789     @param col Index along the dimension 1
01790     */
01791     template<typename _Tp> _Tp& at(int row, int col);
01792     /** @overload
01793     @param row Index along the dimension 0
01794     @param col Index along the dimension 1
01795     */
01796     template<typename _Tp> const _Tp& at(int row, int col) const;
01797 
01798     /** @overload
01799     @param i0 Index along the dimension 0
01800     @param i1 Index along the dimension 1
01801     @param i2 Index along the dimension 2
01802     */
01803     template<typename _Tp> _Tp& at(int i0, int i1, int i2);
01804     /** @overload
01805     @param i0 Index along the dimension 0
01806     @param i1 Index along the dimension 1
01807     @param i2 Index along the dimension 2
01808     */
01809     template<typename _Tp> const _Tp& at(int i0, int i1, int i2) const;
01810 
01811     /** @overload
01812     @param idx Array of Mat::dims indices.
01813     */
01814     template<typename _Tp> _Tp& at(const int* idx);
01815     /** @overload
01816     @param idx Array of Mat::dims indices.
01817     */
01818     template<typename _Tp> const _Tp& at(const int* idx) const;
01819 
01820     /** @overload */
01821     template<typename _Tp, int n> _Tp& at(const Vec<int, n>& idx);
01822     /** @overload */
01823     template<typename _Tp, int n> const _Tp& at(const Vec<int, n>& idx) const;
01824 
01825     /** @overload
01826     special versions for 2D arrays (especially convenient for referencing image pixels)
01827     @param pt Element position specified as Point(j,i) .
01828     */
01829     template<typename _Tp> _Tp& at(Point pt);
01830     /** @overload
01831     special versions for 2D arrays (especially convenient for referencing image pixels)
01832     @param pt Element position specified as Point(j,i) .
01833     */
01834     template<typename _Tp> const _Tp& at(Point pt) const;
01835 
01836     /** @brief Returns the matrix iterator and sets it to the first matrix element.
01837 
01838     The methods return the matrix read-only or read-write iterators. The use of matrix iterators is very
01839     similar to the use of bi-directional STL iterators. In the example below, the alpha blending
01840     function is rewritten using the matrix iterators:
01841     @code
01842         template<typename T>
01843         void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst)
01844         {
01845             typedef Vec<T, 4> VT;
01846 
01847             const float alpha_scale = (float)std::numeric_limits<T>::max(),
01848                         inv_scale = 1.f/alpha_scale;
01849 
01850             CV_Assert( src1.type() == src2.type() &&
01851                        src1.type() == DataType<VT>::type &&
01852                        src1.size() == src2.size());
01853             Size size = src1.size();
01854             dst.create(size, src1.type());
01855 
01856             MatConstIterator_<VT> it1 = src1.begin<VT>(), it1_end = src1.end<VT>();
01857             MatConstIterator_<VT> it2 = src2.begin<VT>();
01858             MatIterator_<VT> dst_it = dst.begin<VT>();
01859 
01860             for( ; it1 != it1_end; ++it1, ++it2, ++dst_it )
01861             {
01862                 VT pix1 = *it1, pix2 = *it2;
01863                 float alpha = pix1[3]*inv_scale, beta = pix2[3]*inv_scale;
01864                 *dst_it = VT(saturate_cast<T>(pix1[0]*alpha + pix2[0]*beta),
01865                              saturate_cast<T>(pix1[1]*alpha + pix2[1]*beta),
01866                              saturate_cast<T>(pix1[2]*alpha + pix2[2]*beta),
01867                              saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale));
01868             }
01869         }
01870     @endcode
01871      */
01872     template<typename _Tp> MatIterator_<_Tp> begin();
01873     template<typename _Tp> MatConstIterator_<_Tp> begin() const;
01874 
01875     /** @brief Returns the matrix iterator and sets it to the after-last matrix element.
01876 
01877     The methods return the matrix read-only or read-write iterators, set to the point following the last
01878     matrix element.
01879      */
01880     template<typename _Tp> MatIterator_<_Tp> end();
01881     template<typename _Tp> MatConstIterator_<_Tp> end() const;
01882 
01883     /** @brief Runs the given functor over all matrix elements in parallel.
01884 
01885     The operation passed as argument has to be a function pointer, a function object or a lambda(C++11).
01886 
01887     Example 1. All of the operations below put 0xFF the first channel of all matrix elements:
01888     @code
01889         Mat image(1920, 1080, CV_8UC3);
01890         typedef cv::Point3_<uint8_t> Pixel;
01891 
01892         // first. raw pointer access.
01893         for (int r = 0; r < image.rows; ++r) {
01894             Pixel* ptr = image.ptr<Pixel>(0, r);
01895             const Pixel* ptr_end = ptr + image.cols;
01896             for (; ptr != ptr_end; ++ptr) {
01897                 ptr->x = 255;
01898             }
01899         }
01900 
01901         // Using MatIterator. (Simple but there are a Iterator's overhead)
01902         for (Pixel &p : cv::Mat_<Pixel>(image)) {
01903             p.x = 255;
01904         }
01905 
01906         // Parallel execution with function object.
01907         struct Operator {
01908             void operator ()(Pixel &pixel, const int * position) {
01909                 pixel.x = 255;
01910             }
01911         };
01912         image.forEach<Pixel>(Operator());
01913 
01914         // Parallel execution using C++11 lambda.
01915         image.forEach<Pixel>([](Pixel &p, const int * position) -> void {
01916             p.x = 255;
01917         });
01918     @endcode
01919     Example 2. Using the pixel's position:
01920     @code
01921         // Creating 3D matrix (255 x 255 x 255) typed uint8_t
01922         // and initialize all elements by the value which equals elements position.
01923         // i.e. pixels (x,y,z) = (1,2,3) is (b,g,r) = (1,2,3).
01924 
01925         int sizes[] = { 255, 255, 255 };
01926         typedef cv::Point3_<uint8_t> Pixel;
01927 
01928         Mat_<Pixel> image = Mat::zeros(3, sizes, CV_8UC3);
01929 
01930         image.forEach<Pixel>([&](Pixel& pixel, const int position[]) -> void {
01931             pixel.x = position[0];
01932             pixel.y = position[1];
01933             pixel.z = position[2];
01934         });
01935     @endcode
01936      */
01937     template<typename _Tp, typename Functor> void forEach(const Functor& operation);
01938     /** @overload */
01939     template<typename _Tp, typename Functor> void forEach(const Functor& operation) const;
01940 
01941 #ifdef CV_CXX_MOVE_SEMANTICS
01942     Mat(Mat&& m);
01943     Mat& operator = (Mat&& m);
01944 #endif
01945 
01946     enum { MAGIC_VAL  = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
01947     enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
01948 
01949     /*! includes several bit-fields:
01950          - the magic signature
01951          - continuity flag
01952          - depth
01953          - number of channels
01954      */
01955     int flags ;
01956     //! the matrix dimensionality, >= 2
01957     int dims;
01958     //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
01959     int rows, cols;
01960     //! pointer to the data
01961     uchar* data;
01962 
01963     //! helper fields used in locateROI and adjustROI
01964     const uchar* datastart;
01965     const uchar* dataend;
01966     const uchar* datalimit;
01967 
01968     //! custom allocator
01969     MatAllocator* allocator;
01970     //! and the standard allocator
01971     static MatAllocator* getStdAllocator();
01972     static MatAllocator* getDefaultAllocator();
01973     static void setDefaultAllocator(MatAllocator* allocator);
01974 
01975     //! interaction with UMat
01976     UMatData* u;
01977 
01978     MatSize size;
01979     MatStep step;
01980 
01981 protected:
01982     template<typename _Tp, typename Functor> void forEach_impl(const Functor& operation);
01983 };
01984 
01985 
01986 ///////////////////////////////// Mat_<_Tp> ////////////////////////////////////
01987 
01988 /** @brief Template matrix class derived from Mat
01989 
01990 @code
01991     template<typename _Tp> class Mat_ : public Mat
01992     {
01993     public:
01994         // ... some specific methods
01995         //         and
01996         // no new extra fields
01997     };
01998 @endcode
01999 The class `Mat_<_Tp>` is a *thin* template wrapper on top of the Mat class. It does not have any
02000 extra data fields. Nor this class nor Mat has any virtual methods. Thus, references or pointers to
02001 these two classes can be freely but carefully converted one to another. For example:
02002 @code
02003     // create a 100x100 8-bit matrix
02004     Mat M(100,100,CV_8U);
02005     // this will be compiled fine. no any data conversion will be done.
02006     Mat_<float>& M1 = (Mat_<float>&)M;
02007     // the program is likely to crash at the statement below
02008     M1(99,99) = 1.f;
02009 @endcode
02010 While Mat is sufficient in most cases, Mat_ can be more convenient if you use a lot of element
02011 access operations and if you know matrix type at the compilation time. Note that
02012 `Mat::at(int y,int x)` and `Mat_::operator()(int y,int x)` do absolutely the same
02013 and run at the same speed, but the latter is certainly shorter:
02014 @code
02015     Mat_<double> M(20,20);
02016     for(int i = 0; i < M.rows; i++)
02017         for(int j = 0; j < M.cols; j++)
02018             M(i,j) = 1./(i+j+1);
02019     Mat E, V;
02020     eigen(M,E,V);
02021     cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
02022 @endcode
02023 To use Mat_ for multi-channel images/matrices, pass Vec as a Mat_ parameter:
02024 @code
02025     // allocate a 320x240 color image and fill it with green (in RGB space)
02026     Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
02027     // now draw a diagonal white line
02028     for(int i = 0; i < 100; i++)
02029         img(i,i)=Vec3b(255,255,255);
02030     // and now scramble the 2nd (red) channel of each pixel
02031     for(int i = 0; i < img.rows; i++)
02032         for(int j = 0; j < img.cols; j++)
02033             img(i,j)[2] ^= (uchar)(i ^ j);
02034 @endcode
02035  */
02036 template<typename _Tp> class Mat_ : public Mat
02037 {
02038 public:
02039     typedef _Tp value_type;
02040     typedef typename DataType<_Tp>::channel_type channel_type;
02041     typedef MatIterator_<_Tp> iterator;
02042     typedef MatConstIterator_<_Tp> const_iterator;
02043 
02044     //! default constructor
02045     Mat_();
02046     //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type)
02047     Mat_(int _rows, int _cols);
02048     //! constructor that sets each matrix element to specified value
02049     Mat_(int _rows, int _cols, const _Tp& value);
02050     //! equivalent to Mat(_size, DataType<_Tp>::type)
02051     explicit Mat_(Size _size);
02052     //! constructor that sets each matrix element to specified value
02053     Mat_(Size _size, const _Tp& value);
02054     //! n-dim array constructor
02055     Mat_(int _ndims, const int* _sizes);
02056     //! n-dim array constructor that sets each matrix element to specified value
02057     Mat_(int _ndims, const int* _sizes, const _Tp& value);
02058     //! copy/conversion contructor. If m is of different type, it's converted
02059     Mat_(const Mat& m);
02060     //! copy constructor
02061     Mat_(const Mat_& m);
02062     //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type
02063     Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP);
02064     //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type
02065     Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0);
02066     //! selects a submatrix
02067     Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all());
02068     //! selects a submatrix
02069     Mat_(const Mat_& m, const Rect& roi);
02070     //! selects a submatrix, n-dim version
02071     Mat_(const Mat_& m, const Range* ranges);
02072     //! selects a submatrix, n-dim version
02073     Mat_(const Mat_& m, const std::vector<Range>& ranges);
02074     //! from a matrix expression
02075     explicit Mat_(const MatExpr& e);
02076     //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column
02077     explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false);
02078     template<int n> explicit Mat_(const Vec<typename DataType<_Tp>::channel_type, n>& vec, bool copyData=true);
02079     template<int m, int n> explicit Mat_(const Matx<typename DataType<_Tp>::channel_type, m, n>& mtx, bool copyData=true);
02080     explicit Mat_(const Point_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
02081     explicit Mat_(const Point3_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
02082     explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer);
02083 
02084     Mat_& operator = (const Mat& m);
02085     Mat_& operator = (const Mat_& m);
02086     //! set all the elements to s.
02087     Mat_& operator = (const _Tp& s);
02088     //! assign a matrix expression
02089     Mat_& operator = (const MatExpr& e);
02090 
02091     //! iterators; they are smart enough to skip gaps in the end of rows
02092     iterator begin();
02093     iterator end();
02094     const_iterator begin() const;
02095     const_iterator end() const;
02096 
02097     //! template methods for for operation over all matrix elements.
02098     // the operations take care of skipping gaps in the end of rows (if any)
02099     template<typename Functor> void forEach(const Functor& operation);
02100     template<typename Functor> void forEach(const Functor& operation) const;
02101 
02102     //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type)
02103     void create(int _rows, int _cols);
02104     //! equivalent to Mat::create(_size, DataType<_Tp>::type)
02105     void create(Size _size);
02106     //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type)
02107     void create(int _ndims, const int* _sizes);
02108     //! cross-product
02109     Mat_ cross(const Mat_& m) const;
02110     //! data type conversion
02111     template<typename T2> operator Mat_<T2>() const;
02112     //! overridden forms of Mat::row() etc.
02113     Mat_ row(int y) const;
02114     Mat_ col(int x) const;
02115     Mat_ diag(int d=0) const;
02116     Mat_ clone() const;
02117 
02118     //! overridden forms of Mat::elemSize() etc.
02119     size_t elemSize() const;
02120     size_t elemSize1() const;
02121     int type() const;
02122     int depth() const;
02123     int channels() const;
02124     size_t step1(int i=0) const;
02125     //! returns step()/sizeof(_Tp)
02126     size_t stepT(int i=0) const;
02127 
02128     //! overridden forms of Mat::zeros() etc. Data type is omitted, of course
02129     static MatExpr zeros(int rows, int cols);
02130     static MatExpr zeros(Size size);
02131     static MatExpr zeros(int _ndims, const int* _sizes);
02132     static MatExpr ones(int rows, int cols);
02133     static MatExpr ones(Size size);
02134     static MatExpr ones(int _ndims, const int* _sizes);
02135     static MatExpr eye(int rows, int cols);
02136     static MatExpr eye(Size size);
02137 
02138     //! some more overriden methods
02139     Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright );
02140     Mat_ operator()( const Range& rowRange, const Range& colRange ) const;
02141     Mat_ operator()( const Rect& roi ) const;
02142     Mat_ operator()( const Range* ranges ) const;
02143     Mat_ operator()(const std::vector<Range>& ranges) const;
02144 
02145     //! more convenient forms of row and element access operators
02146     _Tp* operator [](int y);
02147     const _Tp* operator [](int y) const;
02148 
02149     //! returns reference to the specified element
02150     _Tp& operator ()(const int* idx);
02151     //! returns read-only reference to the specified element
02152     const _Tp& operator ()(const int* idx) const;
02153 
02154     //! returns reference to the specified element
02155     template<int n> _Tp& operator ()(const Vec<int, n>& idx);
02156     //! returns read-only reference to the specified element
02157     template<int n> const _Tp& operator ()(const Vec<int, n>& idx) const;
02158 
02159     //! returns reference to the specified element (1D case)
02160     _Tp& operator ()(int idx0);
02161     //! returns read-only reference to the specified element (1D case)
02162     const _Tp& operator ()(int idx0) const;
02163     //! returns reference to the specified element (2D case)
02164     _Tp& operator ()(int row, int col);
02165     //! returns read-only reference to the specified element (2D case)
02166     const _Tp& operator ()(int row, int col) const;
02167     //! returns reference to the specified element (3D case)
02168     _Tp& operator ()(int idx0, int idx1, int idx2);
02169     //! returns read-only reference to the specified element (3D case)
02170     const _Tp& operator ()(int idx0, int idx1, int idx2) const;
02171 
02172     _Tp& operator ()(Point pt);
02173     const _Tp& operator ()(Point pt) const;
02174 
02175     //! conversion to vector.
02176     operator std::vector<_Tp>() const;
02177     //! conversion to Vec
02178     template<int n> operator Vec<typename DataType<_Tp>::channel_type, n>() const;
02179     //! conversion to Matx
02180     template<int m, int n> operator Matx<typename DataType<_Tp>::channel_type, m, n>() const;
02181 
02182 #ifdef CV_CXX_MOVE_SEMANTICS
02183     Mat_(Mat_&& m);
02184     Mat_& operator = (Mat_&& m);
02185 
02186     Mat_(Mat&& m);
02187     Mat_& operator = (Mat&& m);
02188 
02189     Mat_(MatExpr&& e);
02190 #endif
02191 };
02192 
02193 typedef Mat_<uchar>  Mat1b ;
02194 typedef Mat_<Vec2b> Mat2b;
02195 typedef Mat_<Vec3b> Mat3b;
02196 typedef Mat_<Vec4b> Mat4b;
02197 
02198 typedef Mat_<short> Mat1s;
02199 typedef Mat_<Vec2s> Mat2s;
02200 typedef Mat_<Vec3s> Mat3s;
02201 typedef Mat_<Vec4s> Mat4s;
02202 
02203 typedef Mat_<ushort> Mat1w;
02204 typedef Mat_<Vec2w> Mat2w;
02205 typedef Mat_<Vec3w> Mat3w;
02206 typedef Mat_<Vec4w> Mat4w;
02207 
02208 typedef Mat_<int>    Mat1i ;
02209 typedef Mat_<Vec2i> Mat2i;
02210 typedef Mat_<Vec3i> Mat3i;
02211 typedef Mat_<Vec4i> Mat4i;
02212 
02213 typedef Mat_<float>  Mat1f ;
02214 typedef Mat_<Vec2f> Mat2f;
02215 typedef Mat_<Vec3f> Mat3f;
02216 typedef Mat_<Vec4f> Mat4f;
02217 
02218 typedef Mat_<double>  Mat1d ;
02219 typedef Mat_<Vec2d> Mat2d;
02220 typedef Mat_<Vec3d> Mat3d;
02221 typedef Mat_<Vec4d> Mat4d;
02222 
02223 /** @todo document */
02224 class CV_EXPORTS UMat 
02225 {
02226 public:
02227     //! default constructor
02228     UMat (UMatUsageFlags usageFlags = USAGE_DEFAULT);
02229     //! constructs 2D matrix of the specified size and type
02230     // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
02231     UMat (int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
02232     UMat (Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
02233     //! constucts 2D matrix and fills it with the specified value _s.
02234     UMat (int rows, int cols, int type, const Scalar & s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
02235     UMat (Size size, int type, const Scalar & s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
02236 
02237     //! constructs n-dimensional matrix
02238     UMat (int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
02239     UMat (int ndims, const int* sizes, int type, const Scalar & s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
02240 
02241     //! copy constructor
02242     UMat (const UMat & m);
02243 
02244     //! creates a matrix header for a part of the bigger matrix
02245     UMat (const UMat & m, const Range& rowRange, const Range& colRange=Range::all());
02246     UMat (const UMat & m, const Rect& roi);
02247     UMat (const UMat & m, const Range* ranges);
02248     UMat (const UMat & m, const std::vector<Range>& ranges);
02249     //! builds matrix from std::vector with or without copying the data
02250     template<typename _Tp> explicit UMat (const std::vector<_Tp>& vec, bool copyData=false);
02251     //! builds matrix from cv::Vec; the data is copied by default
02252     template<typename _Tp, int n> explicit UMat (const Vec<_Tp, n>& vec, bool copyData=true);
02253     //! builds matrix from cv::Matx; the data is copied by default
02254     template<typename _Tp, int m, int n> explicit UMat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
02255     //! builds matrix from a 2D point
02256     template<typename _Tp> explicit UMat(const Point_<_Tp>& pt, bool copyData=true);
02257     //! builds matrix from a 3D point
02258     template<typename _Tp> explicit UMat(const Point3_<_Tp>& pt, bool copyData=true);
02259     //! builds matrix from comma initializer
02260     template<typename _Tp> explicit UMat(const MatCommaInitializer_<_Tp>& commaInitializer);
02261 
02262     //! destructor - calls release()
02263     ~UMat();
02264     //! assignment operators
02265     UMat& operator = (const UMat& m);
02266 
02267     Mat getMat(int flags) const;
02268 
02269     //! returns a new matrix header for the specified row
02270     UMat row(int y) const;
02271     //! returns a new matrix header for the specified column
02272     UMat col(int x) const;
02273     //! ... for the specified row span
02274     UMat rowRange(int startrow, int endrow) const;
02275     UMat rowRange(const Range& r) const;
02276     //! ... for the specified column span
02277     UMat colRange(int startcol, int endcol) const;
02278     UMat colRange(const Range& r) const;
02279     //! ... for the specified diagonal
02280     // (d=0 - the main diagonal,
02281     //  >0 - a diagonal from the lower half,
02282     //  <0 - a diagonal from the upper half)
02283     UMat diag(int d=0) const;
02284     //! constructs a square diagonal matrix which main diagonal is vector "d"
02285     static UMat diag(const UMat& d);
02286 
02287     //! returns deep copy of the matrix, i.e. the data is copied
02288     UMat clone() const;
02289     //! copies the matrix content to "m".
02290     // It calls m.create(this->size(), this->type()).
02291     void copyTo( OutputArray m ) const;
02292     //! copies those matrix elements to "m" that are marked with non-zero mask elements.
02293     void copyTo( OutputArray m, InputArray mask ) const;
02294     //! converts matrix to another datatype with optional scalng. See cvConvertScale.
02295     void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
02296 
02297     void assignTo( UMat& m, int type=-1 ) const;
02298 
02299     //! sets every matrix element to s
02300     UMat& operator = (const Scalar & s);
02301     //! sets some of the matrix elements to s, according to the mask
02302     UMat& setTo(InputArray value, InputArray mask=noArray());
02303     //! creates alternative matrix header for the same data, with different
02304     // number of channels and/or different number of rows. see cvReshape.
02305     UMat reshape(int cn, int rows=0) const;
02306     UMat reshape(int cn, int newndims, const int* newsz) const;
02307 
02308     //! matrix transposition by means of matrix expressions
02309     UMat t() const;
02310     //! matrix inversion by means of matrix expressions
02311     UMat inv(int method=DECOMP_LU) const;
02312     //! per-element matrix multiplication by means of matrix expressions
02313     UMat mul(InputArray m, double scale=1) const;
02314 
02315     //! computes dot-product
02316     double dot(InputArray m) const;
02317 
02318     //! Matlab-style matrix initialization
02319     static UMat zeros(int rows, int cols, int type);
02320     static UMat zeros(Size size, int type);
02321     static UMat zeros(int ndims, const int* sz, int type);
02322     static UMat ones(int rows, int cols, int type);
02323     static UMat ones(Size size, int type);
02324     static UMat ones(int ndims, const int* sz, int type);
02325     static UMat eye(int rows, int cols, int type);
02326     static UMat eye(Size size, int type);
02327 
02328     //! allocates new matrix data unless the matrix already has specified size and type.
02329     // previous data is unreferenced if needed.
02330     void create(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
02331     void create(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
02332     void create(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
02333     void create(const std::vector<int>& sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
02334 
02335     //! increases the reference counter; use with care to avoid memleaks
02336     void addref();
02337     //! decreases reference counter;
02338     // deallocates the data when reference counter reaches 0.
02339     void release();
02340 
02341     //! deallocates the matrix data
02342     void deallocate();
02343     //! internal use function; properly re-allocates _size, _step arrays
02344     void copySize(const UMat& m);
02345 
02346     //! locates matrix header within a parent matrix. See below
02347     void locateROI( Size& wholeSize, Point& ofs ) const;
02348     //! moves/resizes the current matrix ROI inside the parent matrix.
02349     UMat& adjustROI( int dtop, int dbottom, int dleft, int dright );
02350     //! extracts a rectangular sub-matrix
02351     // (this is a generalized form of row, rowRange etc.)
02352     UMat operator()( Range rowRange, Range colRange ) const;
02353     UMat operator()( const Rect& roi ) const;
02354     UMat operator()( const Range* ranges ) const;
02355     UMat operator()(const std::vector<Range>& ranges) const;
02356 
02357     //! returns true iff the matrix data is continuous
02358     // (i.e. when there are no gaps between successive rows).
02359     // similar to CV_IS_MAT_CONT(cvmat->type)
02360     bool isContinuous() const;
02361 
02362     //! returns true if the matrix is a submatrix of another matrix
02363     bool isSubmatrix() const;
02364 
02365     //! returns element size in bytes,
02366     // similar to CV_ELEM_SIZE(cvmat->type)
02367     size_t elemSize() const;
02368     //! returns the size of element channel in bytes.
02369     size_t elemSize1() const;
02370     //! returns element type, similar to CV_MAT_TYPE(cvmat->type)
02371     int type() const;
02372     //! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
02373     int depth() const;
02374     //! returns element type, similar to CV_MAT_CN(cvmat->type)
02375     int channels() const;
02376     //! returns step/elemSize1()
02377     size_t step1(int i=0) const;
02378     //! returns true if matrix data is NULL
02379     bool empty() const;
02380     //! returns the total number of matrix elements
02381     size_t total() const;
02382 
02383     //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
02384     int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
02385 
02386 #ifdef CV_CXX_MOVE_SEMANTICS
02387     UMat(UMat&& m);
02388     UMat& operator = (UMat&& m);
02389 #endif
02390 
02391     void* handle(int accessFlags) const;
02392     void ndoffset(size_t* ofs) const;
02393 
02394     enum { MAGIC_VAL  = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
02395     enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
02396 
02397     /*! includes several bit-fields:
02398          - the magic signature
02399          - continuity flag
02400          - depth
02401          - number of channels
02402      */
02403     int flags ;
02404     //! the matrix dimensionality, >= 2
02405     int dims;
02406     //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
02407     int rows, cols;
02408 
02409     //! custom allocator
02410     MatAllocator* allocator;
02411     UMatUsageFlags usageFlags; // usage flags for allocator
02412     //! and the standard allocator
02413     static MatAllocator* getStdAllocator();
02414 
02415     // black-box container of UMat data
02416     UMatData* u;
02417 
02418     // offset of the submatrix (or 0)
02419     size_t offset;
02420 
02421     MatSize size;
02422     MatStep step;
02423 
02424 protected:
02425 };
02426 
02427 
02428 /////////////////////////// multi-dimensional sparse matrix //////////////////////////
02429 
02430 /** @brief The class SparseMat represents multi-dimensional sparse numerical arrays.
02431 
02432 Such a sparse array can store elements of any type that Mat can store. *Sparse* means that only
02433 non-zero elements are stored (though, as a result of operations on a sparse matrix, some of its
02434 stored elements can actually become 0. It is up to you to detect such elements and delete them
02435 using SparseMat::erase ). The non-zero elements are stored in a hash table that grows when it is
02436 filled so that the search time is O(1) in average (regardless of whether element is there or not).
02437 Elements can be accessed using the following methods:
02438 -   Query operations (SparseMat::ptr and the higher-level SparseMat::ref, SparseMat::value and
02439     SparseMat::find), for example:
02440     @code
02441         const int dims = 5;
02442         int size[5] = {10, 10, 10, 10, 10};
02443         SparseMat sparse_mat(dims, size, CV_32F);
02444         for(int i = 0; i < 1000; i++)
02445         {
02446             int idx[dims];
02447             for(int k = 0; k < dims; k++)
02448                 idx[k] = rand() % size[k];
02449             sparse_mat.ref<float>(idx) += 1.f;
02450         }
02451         cout << "nnz = " << sparse_mat.nzcount() << endl;
02452     @endcode
02453 -   Sparse matrix iterators. They are similar to MatIterator but different from NAryMatIterator.
02454     That is, the iteration loop is familiar to STL users:
02455     @code
02456         // prints elements of a sparse floating-point matrix
02457         // and the sum of elements.
02458         SparseMatConstIterator_<float>
02459             it = sparse_mat.begin<float>(),
02460             it_end = sparse_mat.end<float>();
02461         double s = 0;
02462         int dims = sparse_mat.dims();
02463         for(; it != it_end; ++it)
02464         {
02465             // print element indices and the element value
02466             const SparseMat::Node* n = it.node();
02467             printf("(");
02468             for(int i = 0; i < dims; i++)
02469                 printf("%d%s", n->idx[i], i < dims-1 ? ", " : ")");
02470             printf(": %g\n", it.value<float>());
02471             s += *it;
02472         }
02473         printf("Element sum is %g\n", s);
02474     @endcode
02475     If you run this loop, you will notice that elements are not enumerated in a logical order
02476     (lexicographical, and so on). They come in the same order as they are stored in the hash table
02477     (semi-randomly). You may collect pointers to the nodes and sort them to get the proper ordering.
02478     Note, however, that pointers to the nodes may become invalid when you add more elements to the
02479     matrix. This may happen due to possible buffer reallocation.
02480 -   Combination of the above 2 methods when you need to process 2 or more sparse matrices
02481     simultaneously. For example, this is how you can compute unnormalized cross-correlation of the 2
02482     floating-point sparse matrices:
02483     @code
02484         double cross_corr(const SparseMat& a, const SparseMat& b)
02485         {
02486             const SparseMat *_a = &a, *_b = &b;
02487             // if b contains less elements than a,
02488             // it is faster to iterate through b
02489             if(_a->nzcount() > _b->nzcount())
02490                 std::swap(_a, _b);
02491             SparseMatConstIterator_<float> it = _a->begin<float>(),
02492                                            it_end = _a->end<float>();
02493             double ccorr = 0;
02494             for(; it != it_end; ++it)
02495             {
02496                 // take the next element from the first matrix
02497                 float avalue = *it;
02498                 const Node* anode = it.node();
02499                 // and try to find an element with the same index in the second matrix.
02500                 // since the hash value depends only on the element index,
02501                 // reuse the hash value stored in the node
02502                 float bvalue = _b->value<float>(anode->idx,&anode->hashval);
02503                 ccorr += avalue*bvalue;
02504             }
02505             return ccorr;
02506         }
02507     @endcode
02508  */
02509 class CV_EXPORTS SparseMat
02510 {
02511 public:
02512     typedef SparseMatIterator iterator;
02513     typedef SparseMatConstIterator const_iterator;
02514 
02515     enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 };
02516 
02517     //! the sparse matrix header
02518     struct CV_EXPORTS Hdr
02519     {
02520         Hdr(int _dims, const int* _sizes, int _type);
02521         void clear();
02522         int refcount;
02523         int dims;
02524         int valueOffset;
02525         size_t nodeSize;
02526         size_t nodeCount;
02527         size_t freeList;
02528         std::vector<uchar> pool;
02529         std::vector<size_t> hashtab;
02530         int size[MAX_DIM];
02531     };
02532 
02533     //! sparse matrix node - element of a hash table
02534     struct CV_EXPORTS Node
02535     {
02536         //! hash value
02537         size_t hashval;
02538         //! index of the next node in the same hash table entry
02539         size_t next;
02540         //! index of the matrix element
02541         int idx[MAX_DIM];
02542     };
02543 
02544     /** @brief Various SparseMat constructors.
02545      */
02546     SparseMat();
02547 
02548     /** @overload
02549     @param dims Array dimensionality.
02550     @param _sizes Sparce matrix size on all dementions.
02551     @param _type Sparse matrix data type.
02552     */
02553     SparseMat(int dims, const int* _sizes, int _type);
02554 
02555     /** @overload
02556     @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted
02557     to sparse representation.
02558     */
02559     SparseMat(const SparseMat& m);
02560 
02561     /** @overload
02562     @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted
02563     to sparse representation.
02564     */
02565     explicit SparseMat(const Mat& m);
02566 
02567     //! the destructor
02568     ~SparseMat();
02569 
02570     //! assignment operator. This is O(1) operation, i.e. no data is copied
02571     SparseMat& operator = (const SparseMat& m);
02572     //! equivalent to the corresponding constructor
02573     SparseMat& operator = (const Mat& m);
02574 
02575     //! creates full copy of the matrix
02576     SparseMat clone() const;
02577 
02578     //! copies all the data to the destination matrix. All the previous content of m is erased
02579     void copyTo( SparseMat& m ) const;
02580     //! converts sparse matrix to dense matrix.
02581     void copyTo( Mat& m ) const;
02582     //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type
02583     void convertTo( SparseMat& m, int rtype, double alpha=1 ) const;
02584     //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling.
02585     /*!
02586         @param [out] m - output matrix; if it does not have a proper size or type before the operation,
02587             it is reallocated
02588         @param [in] rtype – desired output matrix type or, rather, the depth since the number of channels
02589             are the same as the input has; if rtype is negative, the output matrix will have the
02590             same type as the input.
02591         @param [in] alpha – optional scale factor
02592         @param [in] beta – optional delta added to the scaled values
02593     */
02594     void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
02595 
02596     // not used now
02597     void assignTo( SparseMat& m, int type=-1 ) const;
02598 
02599     //! reallocates sparse matrix.
02600     /*!
02601         If the matrix already had the proper size and type,
02602         it is simply cleared with clear(), otherwise,
02603         the old matrix is released (using release()) and the new one is allocated.
02604     */
02605     void create(int dims, const int* _sizes, int _type);
02606     //! sets all the sparse matrix elements to 0, which means clearing the hash table.
02607     void clear();
02608     //! manually increments the reference counter to the header.
02609     void addref();
02610     // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated.
02611     void release();
02612 
02613     //! converts sparse matrix to the old-style representation; all the elements are copied.
02614     //operator CvSparseMat*() const;
02615     //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements)
02616     size_t elemSize() const;
02617     //! returns elemSize()/channels()
02618     size_t elemSize1() const;
02619 
02620     //! returns type of sparse matrix elements
02621     int type() const;
02622     //! returns the depth of sparse matrix elements
02623     int depth() const;
02624     //! returns the number of channels
02625     int channels() const;
02626 
02627     //! returns the array of sizes, or NULL if the matrix is not allocated
02628     const int* size() const;
02629     //! returns the size of i-th matrix dimension (or 0)
02630     int size(int i) const;
02631     //! returns the matrix dimensionality
02632     int dims() const;
02633     //! returns the number of non-zero elements (=the number of hash table nodes)
02634     size_t nzcount() const;
02635 
02636     //! computes the element hash value (1D case)
02637     size_t hash(int i0) const;
02638     //! computes the element hash value (2D case)
02639     size_t hash(int i0, int i1) const;
02640     //! computes the element hash value (3D case)
02641     size_t hash(int i0, int i1, int i2) const;
02642     //! computes the element hash value (nD case)
02643     size_t hash(const int* idx) const;
02644 
02645     //!@{
02646     /*!
02647      specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case.
02648      return pointer to the matrix element.
02649       - if the element is there (it's non-zero), the pointer to it is returned
02650       - if it's not there and createMissing=false, NULL pointer is returned
02651       - if it's not there and createMissing=true, then the new element
02652         is created and initialized with 0. Pointer to it is returned
02653       - if the optional hashval pointer is not NULL, the element hash value is
02654         not computed, but *hashval is taken instead.
02655     */
02656     //! returns pointer to the specified element (1D case)
02657     uchar* ptr(int i0, bool createMissing, size_t* hashval=0);
02658     //! returns pointer to the specified element (2D case)
02659     uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0);
02660     //! returns pointer to the specified element (3D case)
02661     uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0);
02662     //! returns pointer to the specified element (nD case)
02663     uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0);
02664     //!@}
02665 
02666     //!@{
02667     /*!
02668      return read-write reference to the specified sparse matrix element.
02669 
02670      `ref<_Tp>(i0,...[,hashval])` is equivalent to `*(_Tp*)ptr(i0,...,true[,hashval])`.
02671      The methods always return a valid reference.
02672      If the element did not exist, it is created and initialiazed with 0.
02673     */
02674     //! returns reference to the specified element (1D case)
02675     template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0);
02676     //! returns reference to the specified element (2D case)
02677     template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0);
02678     //! returns reference to the specified element (3D case)
02679     template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
02680     //! returns reference to the specified element (nD case)
02681     template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0);
02682     //!@}
02683 
02684     //!@{
02685     /*!
02686      return value of the specified sparse matrix element.
02687 
02688      `value<_Tp>(i0,...[,hashval])` is equivalent to
02689      @code
02690      { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); }
02691      @endcode
02692 
02693      That is, if the element did not exist, the methods return 0.
02694      */
02695     //! returns value of the specified element (1D case)
02696     template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const;
02697     //! returns value of the specified element (2D case)
02698     template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const;
02699     //! returns value of the specified element (3D case)
02700     template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0) const;
02701     //! returns value of the specified element (nD case)
02702     template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const;
02703     //!@}
02704 
02705     //!@{
02706     /*!
02707      Return pointer to the specified sparse matrix element if it exists
02708 
02709      `find<_Tp>(i0,...[,hashval])` is equivalent to `(_const Tp*)ptr(i0,...false[,hashval])`.
02710 
02711      If the specified element does not exist, the methods return NULL.
02712     */
02713     //! returns pointer to the specified element (1D case)
02714     template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const;
02715     //! returns pointer to the specified element (2D case)
02716     template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0) const;
02717     //! returns pointer to the specified element (3D case)
02718     template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const;
02719     //! returns pointer to the specified element (nD case)
02720     template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0) const;
02721     //!@}
02722 
02723     //! erases the specified element (2D case)
02724     void erase(int i0, int i1, size_t* hashval=0);
02725     //! erases the specified element (3D case)
02726     void erase(int i0, int i1, int i2, size_t* hashval=0);
02727     //! erases the specified element (nD case)
02728     void erase(const int* idx, size_t* hashval=0);
02729 
02730     //!@{
02731     /*!
02732        return the sparse matrix iterator pointing to the first sparse matrix element
02733     */
02734     //! returns the sparse matrix iterator at the matrix beginning
02735     SparseMatIterator begin();
02736     //! returns the sparse matrix iterator at the matrix beginning
02737     template<typename _Tp> SparseMatIterator_<_Tp> begin();
02738     //! returns the read-only sparse matrix iterator at the matrix beginning
02739     SparseMatConstIterator begin() const;
02740     //! returns the read-only sparse matrix iterator at the matrix beginning
02741     template<typename _Tp> SparseMatConstIterator_<_Tp> begin() const;
02742     //!@}
02743     /*!
02744        return the sparse matrix iterator pointing to the element following the last sparse matrix element
02745     */
02746     //! returns the sparse matrix iterator at the matrix end
02747     SparseMatIterator end();
02748     //! returns the read-only sparse matrix iterator at the matrix end
02749     SparseMatConstIterator end() const;
02750     //! returns the typed sparse matrix iterator at the matrix end
02751     template<typename _Tp> SparseMatIterator_<_Tp> end();
02752     //! returns the typed read-only sparse matrix iterator at the matrix end
02753     template<typename _Tp> SparseMatConstIterator_<_Tp> end() const;
02754 
02755     //! returns the value stored in the sparse martix node
02756     template<typename _Tp> _Tp& value(Node* n);
02757     //! returns the value stored in the sparse martix node
02758     template<typename _Tp> const _Tp& value(const Node* n) const;
02759 
02760     ////////////// some internal-use methods ///////////////
02761     Node* node(size_t nidx);
02762     const Node* node(size_t nidx) const;
02763 
02764     uchar* newNode(const int* idx, size_t hashval);
02765     void removeNode(size_t hidx, size_t nidx, size_t previdx);
02766     void resizeHashTab(size_t newsize);
02767 
02768     int flags;
02769     Hdr* hdr;
02770 };
02771 
02772 
02773 
02774 ///////////////////////////////// SparseMat_<_Tp> ////////////////////////////////////
02775 
02776 /** @brief Template sparse n-dimensional array class derived from SparseMat
02777 
02778 SparseMat_ is a thin wrapper on top of SparseMat created in the same way as Mat_ . It simplifies
02779 notation of some operations:
02780 @code
02781     int sz[] = {10, 20, 30};
02782     SparseMat_<double> M(3, sz);
02783     ...
02784     M.ref(1, 2, 3) = M(4, 5, 6) + M(7, 8, 9);
02785 @endcode
02786  */
02787 template<typename _Tp> class SparseMat_ : public SparseMat
02788 {
02789 public:
02790     typedef SparseMatIterator_<_Tp> iterator;
02791     typedef SparseMatConstIterator_<_Tp> const_iterator;
02792 
02793     //! the default constructor
02794     SparseMat_();
02795     //! the full constructor equivelent to SparseMat(dims, _sizes, DataType<_Tp>::type)
02796     SparseMat_(int dims, const int* _sizes);
02797     //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted
02798     SparseMat_(const SparseMat& m);
02799     //! the copy constructor. This is O(1) operation - no data is copied
02800     SparseMat_(const SparseMat_& m);
02801     //! converts dense matrix to the sparse form
02802     SparseMat_(const Mat& m);
02803     //! converts the old-style sparse matrix to the C++ class. All the elements are copied
02804     //SparseMat_(const CvSparseMat* m);
02805     //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted
02806     SparseMat_& operator = (const SparseMat& m);
02807     //! the assignment operator. This is O(1) operation - no data is copied
02808     SparseMat_& operator = (const SparseMat_& m);
02809     //! converts dense matrix to the sparse form
02810     SparseMat_& operator = (const Mat& m);
02811 
02812     //! makes full copy of the matrix. All the elements are duplicated
02813     SparseMat_ clone() const;
02814     //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type)
02815     void create(int dims, const int* _sizes);
02816     //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied
02817     //operator CvSparseMat*() const;
02818 
02819     //! returns type of the matrix elements
02820     int type() const;
02821     //! returns depth of the matrix elements
02822     int depth() const;
02823     //! returns the number of channels in each matrix element
02824     int channels() const;
02825 
02826     //! equivalent to SparseMat::ref<_Tp>(i0, hashval)
02827     _Tp& ref(int i0, size_t* hashval=0);
02828     //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval)
02829     _Tp& ref(int i0, int i1, size_t* hashval=0);
02830     //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval)
02831     _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
02832     //! equivalent to SparseMat::ref<_Tp>(idx, hashval)
02833     _Tp& ref(const int* idx, size_t* hashval=0);
02834 
02835     //! equivalent to SparseMat::value<_Tp>(i0, hashval)
02836     _Tp operator()(int i0, size_t* hashval=0) const;
02837     //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval)
02838     _Tp operator()(int i0, int i1, size_t* hashval=0) const;
02839     //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval)
02840     _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const;
02841     //! equivalent to SparseMat::value<_Tp>(idx, hashval)
02842     _Tp operator()(const int* idx, size_t* hashval=0) const;
02843 
02844     //! returns sparse matrix iterator pointing to the first sparse matrix element
02845     SparseMatIterator_<_Tp> begin();
02846     //! returns read-only sparse matrix iterator pointing to the first sparse matrix element
02847     SparseMatConstIterator_<_Tp> begin() const;
02848     //! returns sparse matrix iterator pointing to the element following the last sparse matrix element
02849     SparseMatIterator_<_Tp> end();
02850     //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element
02851     SparseMatConstIterator_<_Tp> end() const;
02852 };
02853 
02854 
02855 
02856 ////////////////////////////////// MatConstIterator //////////////////////////////////
02857 
02858 class CV_EXPORTS MatConstIterator
02859 {
02860 public:
02861     typedef uchar* value_type;
02862     typedef ptrdiff_t difference_type;
02863     typedef const uchar** pointer;
02864     typedef uchar* reference;
02865 
02866 #ifndef OPENCV_NOSTL
02867     typedef std::random_access_iterator_tag iterator_category;
02868 #endif
02869 
02870     //! default constructor
02871     MatConstIterator();
02872     //! constructor that sets the iterator to the beginning of the matrix
02873     MatConstIterator(const Mat* _m);
02874     //! constructor that sets the iterator to the specified element of the matrix
02875     MatConstIterator(const Mat* _m, int _row, int _col=0);
02876     //! constructor that sets the iterator to the specified element of the matrix
02877     MatConstIterator(const Mat* _m, Point _pt);
02878     //! constructor that sets the iterator to the specified element of the matrix
02879     MatConstIterator(const Mat* _m, const int* _idx);
02880     //! copy constructor
02881     MatConstIterator(const MatConstIterator& it);
02882 
02883     //! copy operator
02884     MatConstIterator& operator = (const MatConstIterator& it);
02885     //! returns the current matrix element
02886     const uchar* operator *() const;
02887     //! returns the i-th matrix element, relative to the current
02888     const uchar* operator [](ptrdiff_t i) const;
02889 
02890     //! shifts the iterator forward by the specified number of elements
02891     MatConstIterator& operator += (ptrdiff_t ofs);
02892     //! shifts the iterator backward by the specified number of elements
02893     MatConstIterator& operator -= (ptrdiff_t ofs);
02894     //! decrements the iterator
02895     MatConstIterator& operator --();
02896     //! decrements the iterator
02897     MatConstIterator operator --(int);
02898     //! increments the iterator
02899     MatConstIterator& operator ++();
02900     //! increments the iterator
02901     MatConstIterator operator ++(int);
02902     //! returns the current iterator position
02903     Point pos() const;
02904     //! returns the current iterator position
02905     void pos(int* _idx) const;
02906 
02907     ptrdiff_t lpos() const;
02908     void seek(ptrdiff_t ofs, bool relative = false);
02909     void seek(const int* _idx, bool relative = false);
02910 
02911     const Mat* m;
02912     size_t elemSize;
02913     const uchar* ptr;
02914     const uchar* sliceStart;
02915     const uchar* sliceEnd;
02916 };
02917 
02918 
02919 
02920 ////////////////////////////////// MatConstIterator_ /////////////////////////////////
02921 
02922 /** @brief Matrix read-only iterator
02923  */
02924 template<typename _Tp>
02925 class MatConstIterator_ : public MatConstIterator
02926 {
02927 public:
02928     typedef _Tp value_type;
02929     typedef ptrdiff_t difference_type;
02930     typedef const _Tp* pointer;
02931     typedef const _Tp& reference;
02932 
02933 #ifndef OPENCV_NOSTL
02934     typedef std::random_access_iterator_tag iterator_category;
02935 #endif
02936 
02937     //! default constructor
02938     MatConstIterator_();
02939     //! constructor that sets the iterator to the beginning of the matrix
02940     MatConstIterator_(const Mat_<_Tp>* _m);
02941     //! constructor that sets the iterator to the specified element of the matrix
02942     MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0);
02943     //! constructor that sets the iterator to the specified element of the matrix
02944     MatConstIterator_(const Mat_<_Tp>* _m, Point _pt);
02945     //! constructor that sets the iterator to the specified element of the matrix
02946     MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx);
02947     //! copy constructor
02948     MatConstIterator_(const MatConstIterator_& it);
02949 
02950     //! copy operator
02951     MatConstIterator_& operator = (const MatConstIterator_& it);
02952     //! returns the current matrix element
02953     const _Tp& operator *() const;
02954     //! returns the i-th matrix element, relative to the current
02955     const _Tp& operator [](ptrdiff_t i) const;
02956 
02957     //! shifts the iterator forward by the specified number of elements
02958     MatConstIterator_& operator += (ptrdiff_t ofs);
02959     //! shifts the iterator backward by the specified number of elements
02960     MatConstIterator_& operator -= (ptrdiff_t ofs);
02961     //! decrements the iterator
02962     MatConstIterator_& operator --();
02963     //! decrements the iterator
02964     MatConstIterator_ operator --(int);
02965     //! increments the iterator
02966     MatConstIterator_& operator ++();
02967     //! increments the iterator
02968     MatConstIterator_ operator ++(int);
02969     //! returns the current iterator position
02970     Point pos() const;
02971 };
02972 
02973 
02974 
02975 //////////////////////////////////// MatIterator_ ////////////////////////////////////
02976 
02977 /** @brief Matrix read-write iterator
02978 */
02979 template<typename _Tp>
02980 class MatIterator_ : public MatConstIterator_<_Tp>
02981 {
02982 public:
02983     typedef _Tp* pointer;
02984     typedef _Tp& reference;
02985 
02986 #ifndef OPENCV_NOSTL
02987     typedef std::random_access_iterator_tag iterator_category;
02988 #endif
02989 
02990     //! the default constructor
02991     MatIterator_();
02992     //! constructor that sets the iterator to the beginning of the matrix
02993     MatIterator_(Mat_<_Tp>* _m);
02994     //! constructor that sets the iterator to the specified element of the matrix
02995     MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0);
02996     //! constructor that sets the iterator to the specified element of the matrix
02997     MatIterator_(Mat_<_Tp>* _m, Point _pt);
02998     //! constructor that sets the iterator to the specified element of the matrix
02999     MatIterator_(Mat_<_Tp>* _m, const int* _idx);
03000     //! copy constructor
03001     MatIterator_(const MatIterator_& it);
03002     //! copy operator
03003     MatIterator_& operator = (const MatIterator_<_Tp>& it );
03004 
03005     //! returns the current matrix element
03006     _Tp& operator *() const;
03007     //! returns the i-th matrix element, relative to the current
03008     _Tp& operator [](ptrdiff_t i) const;
03009 
03010     //! shifts the iterator forward by the specified number of elements
03011     MatIterator_& operator += (ptrdiff_t ofs);
03012     //! shifts the iterator backward by the specified number of elements
03013     MatIterator_& operator -= (ptrdiff_t ofs);
03014     //! decrements the iterator
03015     MatIterator_& operator --();
03016     //! decrements the iterator
03017     MatIterator_ operator --(int);
03018     //! increments the iterator
03019     MatIterator_& operator ++();
03020     //! increments the iterator
03021     MatIterator_ operator ++(int);
03022 };
03023 
03024 
03025 
03026 /////////////////////////////// SparseMatConstIterator ///////////////////////////////
03027 
03028 /**  @brief Read-Only Sparse Matrix Iterator.
03029 
03030  Here is how to use the iterator to compute the sum of floating-point sparse matrix elements:
03031 
03032  \code
03033  SparseMatConstIterator it = m.begin(), it_end = m.end();
03034  double s = 0;
03035  CV_Assert( m.type() == CV_32F );
03036  for( ; it != it_end; ++it )
03037     s += it.value<float>();
03038  \endcode
03039 */
03040 class CV_EXPORTS SparseMatConstIterator
03041 {
03042 public:
03043     //! the default constructor
03044     SparseMatConstIterator();
03045     //! the full constructor setting the iterator to the first sparse matrix element
03046     SparseMatConstIterator(const SparseMat* _m);
03047     //! the copy constructor
03048     SparseMatConstIterator(const SparseMatConstIterator& it);
03049 
03050     //! the assignment operator
03051     SparseMatConstIterator& operator = (const SparseMatConstIterator& it);
03052 
03053     //! template method returning the current matrix element
03054     template<typename _Tp> const _Tp& value() const;
03055     //! returns the current node of the sparse matrix. it.node->idx is the current element index
03056     const SparseMat::Node* node() const;
03057 
03058     //! moves iterator to the previous element
03059     SparseMatConstIterator& operator --();
03060     //! moves iterator to the previous element
03061     SparseMatConstIterator operator --(int);
03062     //! moves iterator to the next element
03063     SparseMatConstIterator& operator ++();
03064     //! moves iterator to the next element
03065     SparseMatConstIterator operator ++(int);
03066 
03067     //! moves iterator to the element after the last element
03068     void seekEnd();
03069 
03070     const SparseMat* m;
03071     size_t hashidx;
03072     uchar* ptr;
03073 };
03074 
03075 
03076 
03077 ////////////////////////////////// SparseMatIterator /////////////////////////////////
03078 
03079 /** @brief  Read-write Sparse Matrix Iterator
03080 
03081  The class is similar to cv::SparseMatConstIterator,
03082  but can be used for in-place modification of the matrix elements.
03083 */
03084 class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator
03085 {
03086 public:
03087     //! the default constructor
03088     SparseMatIterator();
03089     //! the full constructor setting the iterator to the first sparse matrix element
03090     SparseMatIterator(SparseMat* _m);
03091     //! the full constructor setting the iterator to the specified sparse matrix element
03092     SparseMatIterator(SparseMat* _m, const int* idx);
03093     //! the copy constructor
03094     SparseMatIterator(const SparseMatIterator& it);
03095 
03096     //! the assignment operator
03097     SparseMatIterator& operator = (const SparseMatIterator& it);
03098     //! returns read-write reference to the current sparse matrix element
03099     template<typename _Tp> _Tp& value() const;
03100     //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!)
03101     SparseMat::Node* node() const;
03102 
03103     //! moves iterator to the next element
03104     SparseMatIterator& operator ++();
03105     //! moves iterator to the next element
03106     SparseMatIterator operator ++(int);
03107 };
03108 
03109 
03110 
03111 /////////////////////////////// SparseMatConstIterator_ //////////////////////////////
03112 
03113 /** @brief  Template Read-Only Sparse Matrix Iterator Class.
03114 
03115  This is the derived from SparseMatConstIterator class that
03116  introduces more convenient operator *() for accessing the current element.
03117 */
03118 template<typename _Tp> class SparseMatConstIterator_ : public SparseMatConstIterator
03119 {
03120 public:
03121 
03122 #ifndef OPENCV_NOSTL
03123     typedef std::forward_iterator_tag iterator_category;
03124 #endif
03125 
03126     //! the default constructor
03127     SparseMatConstIterator_();
03128     //! the full constructor setting the iterator to the first sparse matrix element
03129     SparseMatConstIterator_(const SparseMat_<_Tp>* _m);
03130     SparseMatConstIterator_(const SparseMat* _m);
03131     //! the copy constructor
03132     SparseMatConstIterator_(const SparseMatConstIterator_& it);
03133 
03134     //! the assignment operator
03135     SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it);
03136     //! the element access operator
03137     const _Tp& operator *() const;
03138 
03139     //! moves iterator to the next element
03140     SparseMatConstIterator_& operator ++();
03141     //! moves iterator to the next element
03142     SparseMatConstIterator_ operator ++(int);
03143 };
03144 
03145 
03146 
03147 ///////////////////////////////// SparseMatIterator_ /////////////////////////////////
03148 
03149 /** @brief  Template Read-Write Sparse Matrix Iterator Class.
03150 
03151  This is the derived from cv::SparseMatConstIterator_ class that
03152  introduces more convenient operator *() for accessing the current element.
03153 */
03154 template<typename _Tp> class SparseMatIterator_ : public SparseMatConstIterator_<_Tp>
03155 {
03156 public:
03157 
03158 #ifndef OPENCV_NOSTL
03159     typedef std::forward_iterator_tag iterator_category;
03160 #endif
03161 
03162     //! the default constructor
03163     SparseMatIterator_();
03164     //! the full constructor setting the iterator to the first sparse matrix element
03165     SparseMatIterator_(SparseMat_<_Tp>* _m);
03166     SparseMatIterator_(SparseMat* _m);
03167     //! the copy constructor
03168     SparseMatIterator_(const SparseMatIterator_& it);
03169 
03170     //! the assignment operator
03171     SparseMatIterator_& operator = (const SparseMatIterator_& it);
03172     //! returns the reference to the current element
03173     _Tp& operator *() const;
03174 
03175     //! moves the iterator to the next element
03176     SparseMatIterator_& operator ++();
03177     //! moves the iterator to the next element
03178     SparseMatIterator_ operator ++(int);
03179 };
03180 
03181 
03182 
03183 /////////////////////////////////// NAryMatIterator //////////////////////////////////
03184 
03185 /** @brief n-ary multi-dimensional array iterator.
03186 
03187 Use the class to implement unary, binary, and, generally, n-ary element-wise operations on
03188 multi-dimensional arrays. Some of the arguments of an n-ary function may be continuous arrays, some
03189 may be not. It is possible to use conventional MatIterator 's for each array but incrementing all of
03190 the iterators after each small operations may be a big overhead. In this case consider using
03191 NAryMatIterator to iterate through several matrices simultaneously as long as they have the same
03192 geometry (dimensionality and all the dimension sizes are the same). On each iteration `it.planes[0]`,
03193 `it.planes[1]`,... will be the slices of the corresponding matrices.
03194 
03195 The example below illustrates how you can compute a normalized and threshold 3D color histogram:
03196 @code
03197     void computeNormalizedColorHist(const Mat& image, Mat& hist, int N, double minProb)
03198     {
03199         const int histSize[] = {N, N, N};
03200 
03201         // make sure that the histogram has a proper size and type
03202         hist.create(3, histSize, CV_32F);
03203 
03204         // and clear it
03205         hist = Scalar(0);
03206 
03207         // the loop below assumes that the image
03208         // is a 8-bit 3-channel. check it.
03209         CV_Assert(image.type() == CV_8UC3);
03210         MatConstIterator_<Vec3b> it = image.begin<Vec3b>(),
03211                                  it_end = image.end<Vec3b>();
03212         for( ; it != it_end; ++it )
03213         {
03214             const Vec3b& pix = *it;
03215             hist.at<float>(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f;
03216         }
03217 
03218         minProb *= image.rows*image.cols;
03219 
03220         // initialize iterator (the style is different from STL).
03221         // after initialization the iterator will contain
03222         // the number of slices or planes the iterator will go through.
03223         // it simultaneously increments iterators for several matrices
03224         // supplied as a null terminated list of pointers
03225         const Mat* arrays[] = {&hist, 0};
03226         Mat planes[1];
03227         NAryMatIterator itNAry(arrays, planes, 1);
03228         double s = 0;
03229         // iterate through the matrix. on each iteration
03230         // itNAry.planes[i] (of type Mat) will be set to the current plane
03231         // of the i-th n-dim matrix passed to the iterator constructor.
03232         for(int p = 0; p < itNAry.nplanes; p++, ++itNAry)
03233         {
03234             threshold(itNAry.planes[0], itNAry.planes[0], minProb, 0, THRESH_TOZERO);
03235             s += sum(itNAry.planes[0])[0];
03236         }
03237 
03238         s = 1./s;
03239         itNAry = NAryMatIterator(arrays, planes, 1);
03240         for(int p = 0; p < itNAry.nplanes; p++, ++itNAry)
03241             itNAry.planes[0] *= s;
03242     }
03243 @endcode
03244  */
03245 class CV_EXPORTS NAryMatIterator
03246 {
03247 public:
03248     //! the default constructor
03249     NAryMatIterator();
03250     //! the full constructor taking arbitrary number of n-dim matrices
03251     NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1);
03252     //! the full constructor taking arbitrary number of n-dim matrices
03253     NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1);
03254     //! the separate iterator initialization method
03255     void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1);
03256 
03257     //! proceeds to the next plane of every iterated matrix
03258     NAryMatIterator& operator ++();
03259     //! proceeds to the next plane of every iterated matrix (postfix increment operator)
03260     NAryMatIterator operator ++(int);
03261 
03262     //! the iterated arrays
03263     const Mat** arrays;
03264     //! the current planes
03265     Mat* planes;
03266     //! data pointers
03267     uchar** ptrs;
03268     //! the number of arrays
03269     int narrays;
03270     //! the number of hyper-planes that the iterator steps through
03271     size_t nplanes;
03272     //! the size of each segment (in elements)
03273     size_t size;
03274 protected:
03275     int iterdepth;
03276     size_t idx;
03277 };
03278 
03279 
03280 
03281 ///////////////////////////////// Matrix Expressions /////////////////////////////////
03282 
03283 class CV_EXPORTS MatOp
03284 {
03285 public:
03286     MatOp();
03287     virtual ~MatOp();
03288 
03289     virtual bool elementWise(const MatExpr& expr) const;
03290     virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0;
03291     virtual void roi(const MatExpr& expr, const Range& rowRange,
03292                      const Range& colRange, MatExpr& res) const;
03293     virtual void diag(const MatExpr& expr, int d, MatExpr& res) const;
03294     virtual void augAssignAdd(const MatExpr& expr, Mat& m) const;
03295     virtual void augAssignSubtract(const MatExpr& expr, Mat& m) const;
03296     virtual void augAssignMultiply(const MatExpr& expr, Mat& m) const;
03297     virtual void augAssignDivide(const MatExpr& expr, Mat& m) const;
03298     virtual void augAssignAnd(const MatExpr& expr, Mat& m) const;
03299     virtual void augAssignOr(const MatExpr& expr, Mat& m) const;
03300     virtual void augAssignXor(const MatExpr& expr, Mat& m) const;
03301 
03302     virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
03303     virtual void add(const MatExpr& expr1, const Scalar & s, MatExpr& res) const;
03304 
03305     virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
03306     virtual void subtract(const Scalar & s, const MatExpr& expr, MatExpr& res) const;
03307 
03308     virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
03309     virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const;
03310 
03311     virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
03312     virtual void divide(double s, const MatExpr& expr, MatExpr& res) const;
03313 
03314     virtual void abs(const MatExpr& expr, MatExpr& res) const;
03315 
03316     virtual void transpose(const MatExpr& expr, MatExpr& res) const;
03317     virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
03318     virtual void invert(const MatExpr& expr, int method, MatExpr& res) const;
03319 
03320     virtual Size size(const MatExpr& expr) const;
03321     virtual int type(const MatExpr& expr) const;
03322 };
03323 
03324 /** @brief Matrix expression representation
03325 @anchor MatrixExpressions
03326 This is a list of implemented matrix operations that can be combined in arbitrary complex
03327 expressions (here A, B stand for matrices ( Mat ), s for a scalar ( Scalar ), alpha for a
03328 real-valued scalar ( double )):
03329 -   Addition, subtraction, negation: `A+B`, `A-B`, `A+s`, `A-s`, `s+A`, `s-A`, `-A`
03330 -   Scaling: `A*alpha`
03331 -   Per-element multiplication and division: `A.mul(B)`, `A/B`, `alpha/A`
03332 -   Matrix multiplication: `A*B`
03333 -   Transposition: `A.t()` (means A<sup>T</sup>)
03334 -   Matrix inversion and pseudo-inversion, solving linear systems and least-squares problems:
03335     `A.inv([method]) (~ A<sup>-1</sup>)`,   `A.inv([method])*B (~ X: AX=B)`
03336 -   Comparison: `A cmpop B`, `A cmpop alpha`, `alpha cmpop A`, where *cmpop* is one of
03337   `>`, `>=`, `==`, `!=`, `<=`, `<`. The result of comparison is an 8-bit single channel mask whose
03338     elements are set to 255 (if the particular element or pair of elements satisfy the condition) or
03339     0.
03340 -   Bitwise logical operations: `A logicop B`, `A logicop s`, `s logicop A`, `~A`, where *logicop* is one of
03341   `&`, `|`, `^`.
03342 -   Element-wise minimum and maximum: `min(A, B)`, `min(A, alpha)`, `max(A, B)`, `max(A, alpha)`
03343 -   Element-wise absolute value: `abs(A)`
03344 -   Cross-product, dot-product: `A.cross(B)`, `A.dot(B)`
03345 -   Any function of matrix or matrices and scalars that returns a matrix or a scalar, such as norm,
03346     mean, sum, countNonZero, trace, determinant, repeat, and others.
03347 -   Matrix initializers ( Mat::eye(), Mat::zeros(), Mat::ones() ), matrix comma-separated
03348     initializers, matrix constructors and operators that extract sub-matrices (see Mat description).
03349 -   Mat_<destination_type>() constructors to cast the result to the proper type.
03350 @note Comma-separated initializers and probably some other operations may require additional
03351 explicit Mat() or Mat_<T>() constructor calls to resolve a possible ambiguity.
03352 
03353 Here are examples of matrix expressions:
03354 @code
03355     // compute pseudo-inverse of A, equivalent to A.inv(DECOMP_SVD)
03356     SVD svd(A);
03357     Mat pinvA = svd.vt.t()*Mat::diag(1./svd.w)*svd.u.t();
03358 
03359     // compute the new vector of parameters in the Levenberg-Marquardt algorithm
03360     x -= (A.t()*A + lambda*Mat::eye(A.cols,A.cols,A.type())).inv(DECOMP_CHOLESKY)*(A.t()*err);
03361 
03362     // sharpen image using "unsharp mask" algorithm
03363     Mat blurred; double sigma = 1, threshold = 5, amount = 1;
03364     GaussianBlur(img, blurred, Size(), sigma, sigma);
03365     Mat lowContrastMask = abs(img - blurred) < threshold;
03366     Mat sharpened = img*(1+amount) + blurred*(-amount);
03367     img.copyTo(sharpened, lowContrastMask);
03368 @endcode
03369 */
03370 class CV_EXPORTS MatExpr
03371 {
03372 public:
03373     MatExpr();
03374     explicit MatExpr(const Mat& m);
03375 
03376     MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(),
03377             const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar & _s = Scalar ());
03378 
03379     operator Mat() const;
03380     template<typename _Tp> operator Mat_<_Tp>() const;
03381 
03382     Size size() const;
03383     int type() const;
03384 
03385     MatExpr row(int y) const;
03386     MatExpr col(int x) const;
03387     MatExpr diag(int d = 0) const;
03388     MatExpr operator()( const Range& rowRange, const Range& colRange ) const;
03389     MatExpr operator()( const Rect& roi ) const;
03390 
03391     MatExpr t() const;
03392     MatExpr inv(int method = DECOMP_LU) const;
03393     MatExpr mul(const MatExpr& e, double scale=1) const;
03394     MatExpr mul(const Mat& m, double scale=1) const;
03395 
03396     Mat cross(const Mat& m) const;
03397     double dot(const Mat& m) const;
03398 
03399     const MatOp* op;
03400     int flags;
03401 
03402     Mat a, b, c;
03403     double alpha, beta;
03404     Scalar  s;
03405 };
03406 
03407 //! @} core_basic
03408 
03409 //! @relates cv::MatExpr
03410 //! @{
03411 CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b);
03412 CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar & s);
03413 CV_EXPORTS MatExpr operator + (const Scalar & s, const Mat& a);
03414 CV_EXPORTS MatExpr operator + (const MatExpr& e, const Mat& m);
03415 CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e);
03416 CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar & s);
03417 CV_EXPORTS MatExpr operator + (const Scalar & s, const MatExpr& e);
03418 CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2);
03419 
03420 CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b);
03421 CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar & s);
03422 CV_EXPORTS MatExpr operator - (const Scalar & s, const Mat& a);
03423 CV_EXPORTS MatExpr operator - (const MatExpr& e, const Mat& m);
03424 CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e);
03425 CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar & s);
03426 CV_EXPORTS MatExpr operator - (const Scalar & s, const MatExpr& e);
03427 CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2);
03428 
03429 CV_EXPORTS MatExpr operator - (const Mat& m);
03430 CV_EXPORTS MatExpr operator - (const MatExpr& e);
03431 
03432 CV_EXPORTS MatExpr operator * (const Mat& a, const Mat& b);
03433 CV_EXPORTS MatExpr operator * (const Mat& a, double s);
03434 CV_EXPORTS MatExpr operator * (double s, const Mat& a);
03435 CV_EXPORTS MatExpr operator * (const MatExpr& e, const Mat& m);
03436 CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e);
03437 CV_EXPORTS MatExpr operator * (const MatExpr& e, double s);
03438 CV_EXPORTS MatExpr operator * (double s, const MatExpr& e);
03439 CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2);
03440 
03441 CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b);
03442 CV_EXPORTS MatExpr operator / (const Mat& a, double s);
03443 CV_EXPORTS MatExpr operator / (double s, const Mat& a);
03444 CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m);
03445 CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e);
03446 CV_EXPORTS MatExpr operator / (const MatExpr& e, double s);
03447 CV_EXPORTS MatExpr operator / (double s, const MatExpr& e);
03448 CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2);
03449 
03450 CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b);
03451 CV_EXPORTS MatExpr operator < (const Mat& a, double s);
03452 CV_EXPORTS MatExpr operator < (double s, const Mat& a);
03453 
03454 CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b);
03455 CV_EXPORTS MatExpr operator <= (const Mat& a, double s);
03456 CV_EXPORTS MatExpr operator <= (double s, const Mat& a);
03457 
03458 CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b);
03459 CV_EXPORTS MatExpr operator == (const Mat& a, double s);
03460 CV_EXPORTS MatExpr operator == (double s, const Mat& a);
03461 
03462 CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b);
03463 CV_EXPORTS MatExpr operator != (const Mat& a, double s);
03464 CV_EXPORTS MatExpr operator != (double s, const Mat& a);
03465 
03466 CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b);
03467 CV_EXPORTS MatExpr operator >= (const Mat& a, double s);
03468 CV_EXPORTS MatExpr operator >= (double s, const Mat& a);
03469 
03470 CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b);
03471 CV_EXPORTS MatExpr operator > (const Mat& a, double s);
03472 CV_EXPORTS MatExpr operator > (double s, const Mat& a);
03473 
03474 CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b);
03475 CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar & s);
03476 CV_EXPORTS MatExpr operator & (const Scalar & s, const Mat& a);
03477 
03478 CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b);
03479 CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar & s);
03480 CV_EXPORTS MatExpr operator | (const Scalar & s, const Mat& a);
03481 
03482 CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b);
03483 CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar & s);
03484 CV_EXPORTS MatExpr operator ^ (const Scalar & s, const Mat& a);
03485 
03486 CV_EXPORTS MatExpr operator ~(const Mat& m);
03487 
03488 CV_EXPORTS MatExpr min(const Mat& a, const Mat& b);
03489 CV_EXPORTS MatExpr min(const Mat& a, double s);
03490 CV_EXPORTS MatExpr min(double s, const Mat& a);
03491 
03492 CV_EXPORTS MatExpr max(const Mat& a, const Mat& b);
03493 CV_EXPORTS MatExpr max(const Mat& a, double s);
03494 CV_EXPORTS MatExpr max(double s, const Mat& a);
03495 
03496 /** @brief Calculates an absolute value of each matrix element.
03497 
03498 abs is a meta-function that is expanded to one of absdiff or convertScaleAbs forms:
03499 - C = abs(A-B) is equivalent to `absdiff(A, B, C)`
03500 - C = abs(A) is equivalent to `absdiff(A, Scalar::all(0), C)`
03501 - C = `Mat_<Vec<uchar,n> >(abs(A*alpha + beta))` is equivalent to `convertScaleAbs(A, C, alpha,
03502 beta)`
03503 
03504 The output matrix has the same size and the same type as the input one except for the last case,
03505 where C is depth=CV_8U .
03506 @param m matrix.
03507 @sa @ref MatrixExpressions, absdiff, convertScaleAbs
03508  */
03509 CV_EXPORTS MatExpr abs(const Mat& m);
03510 /** @overload
03511 @param e matrix expression.
03512 */
03513 CV_EXPORTS MatExpr abs(const MatExpr& e);
03514 //! @} relates cv::MatExpr
03515 
03516 } // cv
03517 
03518 #include "opencv2/core/mat.inl.hpp"
03519 
03520 #endif // OPENCV_CORE_MAT_HPP