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