OpenCV  3.2.0-dev
Open Source Computer Vision
cv::Mat Class Reference

n-dimensional dense array class More...

#include "mat.hpp"

Inheritance diagram for cv::Mat:
Collaboration diagram for cv::Mat:

Public Types

enum  {
  MAGIC_VAL = 0x42FF0000,
  AUTO_STEP = 0,
  CONTINUOUS_FLAG = CV_MAT_CONT_FLAG,
  SUBMATRIX_FLAG = CV_SUBMAT_FLAG
}
 
enum  {
  MAGIC_MASK = 0xFFFF0000,
  TYPE_MASK = 0x00000FFF,
  DEPTH_MASK = 7
}
 

Public Member Functions

 Mat ()
 These are various constructors that form a matrix. More...
 
 Mat (int rows, int cols, int type)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (Size size, int type)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (int rows, int cols, int type, const Scalar &s)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (Size size, int type, const Scalar &s)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (int ndims, const int *sizes, int type)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (const std::vector< int > &sizes, int type)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (int ndims, const int *sizes, int type, const Scalar &s)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (const std::vector< int > &sizes, int type, const Scalar &s)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (const Mat &m)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (int rows, int cols, int type, void *data, size_t step=AUTO_STEP)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (Size size, int type, void *data, size_t step=AUTO_STEP)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (int ndims, const int *sizes, int type, void *data, const size_t *steps=0)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (const std::vector< int > &sizes, int type, void *data, const size_t *steps=0)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (const Mat &m, const Range &rowRange, const Range &colRange=Range::all())
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (const Mat &m, const Rect &roi)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (const Mat &m, const Range *ranges)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (const Mat &m, const std::vector< Range > &ranges)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp >
 Mat (const std::vector< _Tp > &vec, bool copyData=false)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp , int n>
 Mat (const Vec< _Tp, n > &vec, bool copyData=true)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp , int m, int n>
 Mat (const Matx< _Tp, m, n > &mtx, bool copyData=true)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp >
 Mat (const Point_< _Tp > &pt, bool copyData=true)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp >
 Mat (const Point3_< _Tp > &pt, bool copyData=true)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp >
 Mat (const MatCommaInitializer_< _Tp > &commaInitializer)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
 Mat (const cuda::GpuMat &m)
 download data from GpuMat More...
 
 ~Mat ()
 destructor - calls release() More...
 
void addref ()
 Increments the reference counter. More...
 
MatadjustROI (int dtop, int dbottom, int dleft, int dright)
 Adjusts a submatrix size and position within the parent matrix. More...
 
void assignTo (Mat &m, int type=-1) const
 Provides a functional form of convertTo. More...
 
template<typename _Tp >
_Tp & at (int i0=0)
 Returns a reference to the specified array element. More...
 
template<typename _Tp >
const _Tp & at (int i0=0) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp >
_Tp & at (int row, int col)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp >
const _Tp & at (int row, int col) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp >
_Tp & at (int i0, int i1, int i2)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp >
const _Tp & at (int i0, int i1, int i2) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp >
_Tp & at (const int *idx)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp >
const _Tp & at (const int *idx) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp , int n>
_Tp & at (const Vec< int, n > &idx)
 
template<typename _Tp , int n>
const _Tp & at (const Vec< int, n > &idx) const
 
template<typename _Tp >
_Tp & at (Point pt)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. special versions for 2D arrays (especially convenient for referencing image pixels) More...
 
template<typename _Tp >
const _Tp & at (Point pt) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. special versions for 2D arrays (especially convenient for referencing image pixels) More...
 
template<typename _Tp >
MatIterator_< _Tp > begin ()
 Returns the matrix iterator and sets it to the first matrix element. More...
 
template<typename _Tp >
MatConstIterator_< _Tp > begin () const
 
int channels () const
 Returns the number of matrix channels. More...
 
int checkVector (int elemChannels, int depth=-1, bool requireContinuous=true) const
 returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise More...
 
Mat clone () const
 Creates a full copy of the array and the underlying data. More...
 
Mat col (int x) const
 Creates a matrix header for the specified matrix column. More...
 
Mat colRange (int startcol, int endcol) const
 Creates a matrix header for the specified column span. More...
 
Mat colRange (const Range &r) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
void convertTo (OutputArray m, int rtype, double alpha=1, double beta=0) const
 Converts an array to another data type with optional scaling. More...
 
void copySize (const Mat &m)
 internal use function; properly re-allocates _size, _step arrays More...
 
void copyTo (OutputArray m) const
 Copies the matrix to another one. More...
 
void copyTo (OutputArray m, InputArray mask) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
void create (int rows, int cols, int type)
 Allocates new array data if needed. More...
 
void create (Size size, int type)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
void create (int ndims, const int *sizes, int type)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
void create (const std::vector< int > &sizes, int type)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
Mat cross (InputArray m) const
 Computes a cross-product of two 3-element vectors. More...
 
void deallocate ()
 deallocates the matrix data More...
 
int depth () const
 Returns the depth of a matrix element. More...
 
Mat diag (int d=0) const
 Extracts a diagonal from a matrix. More...
 
double dot (InputArray m) const
 Computes a dot-product of two vectors. More...
 
size_t elemSize () const
 Returns the matrix element size in bytes. More...
 
size_t elemSize1 () const
 Returns the size of each matrix element channel in bytes. More...
 
bool empty () const
 Returns true if the array has no elements. More...
 
template<typename _Tp >
MatIterator_< _Tp > end ()
 Returns the matrix iterator and sets it to the after-last matrix element. More...
 
template<typename _Tp >
MatConstIterator_< _Tp > end () const
 
template<typename _Tp , typename Functor >
void forEach (const Functor &operation)
 Runs the given functor over all matrix elements in parallel. More...
 
template<typename _Tp , typename Functor >
void forEach (const Functor &operation) const
 
UMat getUMat (int accessFlags, UMatUsageFlags usageFlags=USAGE_DEFAULT) const
 retrieve UMat from Mat More...
 
MatExpr inv (int method=DECOMP_LU) const
 Inverses a matrix. More...
 
bool isContinuous () const
 Reports whether the matrix is continuous or not. More...
 
bool isSubmatrix () const
 returns true if the matrix is a submatrix of another matrix More...
 
void locateROI (Size &wholeSize, Point &ofs) const
 Locates the matrix header within a parent matrix. More...
 
MatExpr mul (InputArray m, double scale=1) const
 Performs an element-wise multiplication or division of the two matrices. More...
 
template<typename _Tp , int m, int n>
 operator Matx< _Tp, m, n > () const
 
template<typename _Tp >
 operator std::vector< _Tp > () const
 
template<typename _Tp , int n>
 operator Vec< _Tp, n > () const
 
Mat operator() (Range rowRange, Range colRange) const
 Extracts a rectangular submatrix. More...
 
Mat operator() (const Rect &roi) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
Mat operator() (const Range *ranges) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
Mat operator() (const std::vector< Range > &ranges) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
Matoperator= (const Mat &m)
 assignment operators More...
 
Matoperator= (const MatExpr &expr)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
Matoperator= (const Scalar &s)
 Sets all or some of the array elements to the specified value. More...
 
void pop_back (size_t nelems=1)
 Removes elements from the bottom of the matrix. More...
 
ucharptr (int i0=0)
 Returns a pointer to the specified matrix row. More...
 
const ucharptr (int i0=0) const
 
ucharptr (int row, int col)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
const ucharptr (int row, int col) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
ucharptr (int i0, int i1, int i2)
 
const ucharptr (int i0, int i1, int i2) const
 
ucharptr (const int *idx)
 
const ucharptr (const int *idx) const
 
template<int n>
ucharptr (const Vec< int, n > &idx)
 
template<int n>
const ucharptr (const Vec< int, n > &idx) const
 
template<typename _Tp >
_Tp * ptr (int i0=0)
 
template<typename _Tp >
const _Tp * ptr (int i0=0) const
 
template<typename _Tp >
_Tp * ptr (int row, int col)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp >
const _Tp * ptr (int row, int col) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename _Tp >
_Tp * ptr (int i0, int i1, int i2)
 
template<typename _Tp >
const _Tp * ptr (int i0, int i1, int i2) const
 
template<typename _Tp >
_Tp * ptr (const int *idx)
 
template<typename _Tp >
const _Tp * ptr (const int *idx) const
 
template<typename _Tp , int n>
_Tp * ptr (const Vec< int, n > &idx)
 
template<typename _Tp , int n>
const _Tp * ptr (const Vec< int, n > &idx) const
 
template<typename _Tp >
void push_back (const _Tp &elem)
 Adds elements to the bottom of the matrix. More...
 
template<typename _Tp >
void push_back (const Mat_< _Tp > &elem)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
void push_back (const Mat &m)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
void push_back_ (const void *elem)
 internal function More...
 
void release ()
 Decrements the reference counter and deallocates the matrix if needed. More...
 
void reserve (size_t sz)
 Reserves space for the certain number of rows. More...
 
Mat reshape (int cn, int rows=0) const
 Changes the shape and/or the number of channels of a 2D matrix without copying the data. More...
 
Mat reshape (int cn, int newndims, const int *newsz) const
 
void resize (size_t sz)
 Changes the number of matrix rows. More...
 
void resize (size_t sz, const Scalar &s)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
Mat row (int y) const
 Creates a matrix header for the specified matrix row. More...
 
Mat rowRange (int startrow, int endrow) const
 Creates a matrix header for the specified row span. More...
 
Mat rowRange (const Range &r) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
MatsetTo (InputArray value, InputArray mask=noArray())
 Sets all or some of the array elements to the specified value. More...
 
size_t step1 (int i=0) const
 Returns a normalized step. More...
 
MatExpr t () const
 Transposes a matrix. More...
 
size_t total () const
 Returns the total number of array elements. More...
 
int type () const
 Returns the type of a matrix element. More...
 

Static Public Member Functions

static Mat diag (const Mat &d)
 creates a diagonal matrix More...
 
static MatExpr eye (int rows, int cols, int type)
 Returns an identity matrix of the specified size and type. More...
 
static MatExpr eye (Size size, int type)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
static MatAllocatorgetDefaultAllocator ()
 
static MatAllocatorgetStdAllocator ()
 and the standard allocator More...
 
static MatExpr ones (int rows, int cols, int type)
 Returns an array of all 1's of the specified size and type. More...
 
static MatExpr ones (Size size, int type)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
static MatExpr ones (int ndims, const int *sz, int type)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
static void setDefaultAllocator (MatAllocator *allocator)
 
static MatExpr zeros (int rows, int cols, int type)
 Returns a zero array of the specified size and type. More...
 
static MatExpr zeros (Size size, int type)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
static MatExpr zeros (int ndims, const int *sz, int type)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 

Public Attributes

MatAllocatorallocator
 custom allocator More...
 
int cols
 
uchardata
 pointer to the data More...
 
const uchardataend
 
const uchardatalimit
 
const uchardatastart
 helper fields used in locateROI and adjustROI More...
 
int dims
 the matrix dimensionality, >= 2 More...
 
int flags
 includes several bit-fields: More...
 
int rows
 the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions More...
 
MatSize size
 
MatStep step
 
UMatDatau
 interaction with UMat More...
 

Protected Member Functions

template<typename _Tp , typename Functor >
void forEach_impl (const Functor &operation)
 

Detailed Description

n-dimensional dense array class

The class Mat represents an n-dimensional dense numerical single-channel or multi-channel array. It can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms (though, very high-dimensional histograms may be better stored in a SparseMat ). The data layout of the array M is defined by the array M.step[], so that the address of element \((i_0,...,i_{M.dims-1})\), where \(0\leq i_k<M.size[k]\), is computed as:

\[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}\]

In case of a 2-dimensional array, the above formula is reduced to:

\[addr(M_{i,j}) = M.data + M.step[0]*i + M.step[1]*j\]

Note that M.step[i] >= M.step[i+1] (in fact, M.step[i] >= M.step[i+1]*M.size[i+1] ). This means that 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane, and so on. M.step[M.dims-1] is minimal and always equal to the element size M.elemSize() .

So, the data layout in Mat is fully compatible with CvMat, IplImage, and CvMatND types from OpenCV 1.x. It is also compatible with the majority of dense array types from the standard toolkits and SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others, that is, with any array that uses steps (or strides) to compute the position of a pixel. Due to this compatibility, it is possible to make a Mat header for user-allocated data and process it in-place using OpenCV functions.

There are many different ways to create a Mat object. The most popular options are listed below:

  • Use the create(nrows, ncols, type) method or the similar Mat(nrows, ncols, type[, fillValue]) constructor. A new array of the specified size and type is allocated. type has the same meaning as in the cvCreateMat method. For example, CV_8UC1 means a 8-bit single-channel array, CV_32FC2 means a 2-channel (complex) floating-point array, and so on.
    // make a 7x7 complex matrix filled with 1+3j.
    Mat M(7,7,CV_32FC2,Scalar(1,3));
    // and now turn M to a 100x60 15-channel 8-bit matrix.
    // The old content will be deallocated
    M.create(100,60,CV_8UC(15));
    As noted in the introduction to this chapter, create() allocates only a new array when the shape or type of the current array are different from the specified ones.
  • Create a multi-dimensional array:
    // create a 100x100x100 8-bit array
    int sz[] = {100, 100, 100};
    Mat bigCube(3, sz, CV_8U, Scalar::all(0));
    It passes the number of dimensions =1 to the Mat constructor but the created array will be 2-dimensional with the number of columns set to 1. So, Mat::dims is always >= 2 (can also be 0 when the array is empty).
  • Use a copy constructor or assignment operator where there can be an array or expression on the right side (see below). As noted in the introduction, the array assignment is an O(1) operation because it only copies the header and increases the reference counter. The Mat::clone() method can be used to get a full (deep) copy of the array when you need it.
  • Construct a header for a part of another array. It can be a single row, single column, several rows, several columns, rectangular region in the array (called a minor in algebra) or a diagonal. Such operations are also O(1) because the new header references the same data. You can actually modify a part of the array using this feature, for example:
    // add the 5-th row, multiplied by 3 to the 3rd row
    M.row(3) = M.row(3) + M.row(5)*3;
    // now copy the 7-th column to the 1-st column
    // M.col(1) = M.col(7); // this will not work
    Mat M1 = M.col(1);
    M.col(7).copyTo(M1);
    // create a new 320x240 image
    Mat img(Size(320,240),CV_8UC3);
    // select a ROI
    Mat roi(img, Rect(10,10,100,100));
    // fill the ROI with (0,255,0) (which is green in RGB space);
    // the original 320x240 image will be modified
    roi = Scalar(0,255,0);
    Due to the additional datastart and dataend members, it is possible to compute a relative sub-array position in the main container array using locateROI():
    Mat A = Mat::eye(10, 10, CV_32S);
    // extracts A columns, 1 (inclusive) to 3 (exclusive).
    Mat B = A(Range::all(), Range(1, 3));
    // extracts B rows, 5 (inclusive) to 9 (exclusive).
    // that is, C \~ A(Range(5, 9), Range(1, 3))
    Mat C = B(Range(5, 9), Range::all());
    C.locateROI(size, ofs);
    // size will be (width=10,height=10) and the ofs will be (x=1, y=5)
    As in case of whole matrices, if you need a deep copy, use the clone() method of the extracted sub-matrices.
  • Make a header for user-allocated data. It can be useful to do the following:
    1. Process "foreign" data using OpenCV (for example, when you implement a DirectShow* filter or a processing module for gstreamer, and so on). For example:
      void process_video_frame(const unsigned char* pixels,
      int width, int height, int step)
      {
      Mat img(height, width, CV_8UC3, pixels, step);
      GaussianBlur(img, img, Size(7,7), 1.5, 1.5);
      }
    2. Quickly initialize small matrices and/or get a super-fast element access.
      double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
      Mat M = Mat(3, 3, CV_64F, m).inv();
    Partial yet very common cases of this user-allocated data case are conversions from CvMat and IplImage to Mat. For this purpose, there is function cv::cvarrToMat taking pointers to CvMat or IplImage and the optional flag indicating whether to copy the data or not.
    Ptr<IplImage> iplimg(cvLoadImage(imagename.c_str())); // Ptr<T> is safe ref-counting pointer class
    if(!iplimg)
    {
    fprintf(stderr, "Can not load image %s\n", imagename.c_str());
    return -1;
    }
    Mat img = cv::cvarrToMat(iplimg); // cv::Mat replaces the CvMat and IplImage, but it's easy to convert
    // between the old and the new data structures (by default, only the header
    // is converted, while the data is shared)
  • Use MATLAB-style array initializers, zeros(), ones(), eye(), for example:
    // create a double-precision identity martix and add it to M.
    M += Mat::eye(M.rows, M.cols, CV_64F);
  • Use a comma-separated initializer:
    // create a 3x3 double-precision identity matrix
    Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
    With this approach, you first call a constructor of the Mat class with the proper parameters, and then you just put << operator followed by comma-separated values that can be constants, variables, expressions, and so on. Also, note the extra parentheses required to avoid compilation errors.

Once the array is created, it is automatically managed via a reference-counting mechanism. If the array header is built on top of user-allocated data, you should handle the data by yourself. The array data is deallocated when no one points to it. If you want to release the data pointed by a array header before the array destructor is called, use Mat::release().

The next important thing to learn about the array class is element access. This manual already described how to compute an address of each array element. Normally, you are not required to use the formula directly in the code. If you know the array element type (which can be retrieved using the method Mat::type() ), you can access the element \(M_{ij}\) of a 2-dimensional array as:

M.at<double>(i,j) += 1.f;

assuming that M is a double-precision floating-point array. There are several variants of the method at for a different number of dimensions.

If you need to process a whole row of a 2D array, the most efficient way is to get the pointer to the row first, and then just use the plain C operator [] :

// compute sum of positive matrix elements
// (assuming that M isa double-precision matrix)
double sum=0;
for(int i = 0; i < M.rows; i++)
{
const double* Mi = M.ptr<double>(i);
for(int j = 0; j < M.cols; j++)
sum += std::max(Mi[j], 0.);
}

Some operations, like the one above, do not actually depend on the array shape. They just process elements of an array one by one (or elements from multiple arrays that have the same coordinates, for example, array addition). Such operations are called element-wise. It makes sense to check whether all the input/output arrays are continuous, namely, have no gaps at the end of each row. If yes, process them as a long single row:

// compute the sum of positive matrix elements, optimized variant
double sum=0;
int cols = M.cols, rows = M.rows;
if(M.isContinuous())
{
cols *= rows;
rows = 1;
}
for(int i = 0; i < rows; i++)
{
const double* Mi = M.ptr<double>(i);
for(int j = 0; j < cols; j++)
sum += std::max(Mi[j], 0.);
}

In case of the continuous matrix, the outer loop body is executed just once. So, the overhead is smaller, which is especially noticeable in case of small matrices.

Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:

// compute sum of positive matrix elements, iterator-based variant
double sum=0;
MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
for(; it != it_end; ++it)
sum += std::max(*it, 0.);

The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, including std::sort().

Note
Matrix Expressions and arithmetic see MatExpr
Examples:
contours2.cpp, convexhull.cpp, cout_mat.cpp, demhist.cpp, distrans.cpp, edge.cpp, ffilldemo.cpp, filestorage.cpp, fitellipse.cpp, grabcut.cpp, houghcircles.cpp, houghlines.cpp, kmeans.cpp, laplace.cpp, lsd_lines.cpp, minarea.cpp, morphology2.cpp, pca.cpp, polar_transforms.cpp, segment_objects.cpp, and watershed.cpp.

Member Enumeration Documentation

anonymous enum
Enumerator
MAGIC_VAL 
AUTO_STEP 
CONTINUOUS_FLAG 
SUBMATRIX_FLAG 
anonymous enum
Enumerator
MAGIC_MASK 
TYPE_MASK 
DEPTH_MASK 

Constructor & Destructor Documentation

cv::Mat::Mat ( )

These are various constructors that form a matrix.

As noted in the AutomaticAllocation, often the default constructor is enough, and the proper matrix will be allocated by an OpenCV function. The constructed matrix can further be assigned to another matrix or matrix expression or can be allocated with Mat::create . In the former case, the old content is de-referenced.

cv::Mat::Mat ( int  rows,
int  cols,
int  type 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
rowsNumber of rows in a 2D array.
colsNumber of columns in a 2D array.
typeArray type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
cv::Mat::Mat ( Size  size,
int  type 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
size2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the number of columns go in the reverse order.
typeArray type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
cv::Mat::Mat ( int  rows,
int  cols,
int  type,
const Scalar s 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
rowsNumber of rows in a 2D array.
colsNumber of columns in a 2D array.
typeArray type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
sAn optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use the assignment operator Mat::operator=(const Scalar& value) .
cv::Mat::Mat ( Size  size,
int  type,
const Scalar s 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
size2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the number of columns go in the reverse order.
typeArray type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
sAn optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use the assignment operator Mat::operator=(const Scalar& value) .
cv::Mat::Mat ( int  ndims,
const int *  sizes,
int  type 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
ndimsArray dimensionality.
sizesArray of integers specifying an n-dimensional array shape.
typeArray type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
cv::Mat::Mat ( const std::vector< int > &  sizes,
int  type 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
sizesArray of integers specifying an n-dimensional array shape.
typeArray type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
cv::Mat::Mat ( int  ndims,
const int *  sizes,
int  type,
const Scalar s 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
ndimsArray dimensionality.
sizesArray of integers specifying an n-dimensional array shape.
typeArray type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
sAn optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use the assignment operator Mat::operator=(const Scalar& value) .
cv::Mat::Mat ( const std::vector< int > &  sizes,
int  type,
const Scalar s 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
sizesArray of integers specifying an n-dimensional array shape.
typeArray type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
sAn optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use the assignment operator Mat::operator=(const Scalar& value) .
cv::Mat::Mat ( const Mat m)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
mArray that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() .
cv::Mat::Mat ( int  rows,
int  cols,
int  type,
void *  data,
size_t  step = AUTO_STEP 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
rowsNumber of rows in a 2D array.
colsNumber of columns in a 2D array.
typeArray type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
dataPointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it.
stepNumber of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See Mat::elemSize.
cv::Mat::Mat ( Size  size,
int  type,
void *  data,
size_t  step = AUTO_STEP 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
size2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the number of columns go in the reverse order.
typeArray type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
dataPointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it.
stepNumber of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See Mat::elemSize.
cv::Mat::Mat ( int  ndims,
const int *  sizes,
int  type,
void *  data,
const size_t *  steps = 0 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
ndimsArray dimensionality.
sizesArray of integers specifying an n-dimensional array shape.
typeArray type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
dataPointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it.
stepsArray of ndims-1 steps in case of a multi-dimensional array (the last step is always set to the element size). If not specified, the matrix is assumed to be continuous.
cv::Mat::Mat ( const std::vector< int > &  sizes,
int  type,
void *  data,
const size_t *  steps = 0 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
sizesArray of integers specifying an n-dimensional array shape.
typeArray type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
dataPointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it.
stepsArray of ndims-1 steps in case of a multi-dimensional array (the last step is always set to the element size). If not specified, the matrix is assumed to be continuous.
cv::Mat::Mat ( const Mat m,
const Range rowRange,
const Range colRange = Range::all() 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
mArray that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() .
rowRangeRange of the m rows to take. As usual, the range start is inclusive and the range end is exclusive. Use Range::all() to take all the rows.
colRangeRange of the m columns to take. Use Range::all() to take all the columns.
cv::Mat::Mat ( const Mat m,
const Rect roi 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
mArray that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() .
roiRegion of interest.
cv::Mat::Mat ( const Mat m,
const Range ranges 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
mArray that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() .
rangesArray of selected ranges of m along each dimensionality.
cv::Mat::Mat ( const Mat m,
const std::vector< Range > &  ranges 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
mArray that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() .
rangesArray of selected ranges of m along each dimensionality.
template<typename _Tp >
cv::Mat::Mat ( const std::vector< _Tp > &  vec,
bool  copyData = false 
)
explicit

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
vecSTL vector whose elements form the matrix. The matrix has a single column and the number of rows equal to the number of vector elements. Type of the matrix matches the type of vector elements. The constructor can handle arbitrary types, for which there is a properly declared DataType . This means that the vector elements must be primitive numbers or uni-type numerical tuples of numbers. Mixed-type structures are not supported. The corresponding constructor is explicit. Since STL vectors are not automatically converted to Mat instances, you should write Mat(vec) explicitly. Unless you copy the data into the matrix ( copyData=true ), no new elements will be added to the vector because it can potentially yield vector data reallocation, and, thus, the matrix data pointer will be invalid.
copyDataFlag to specify whether the underlying data of the STL vector should be copied to (true) or shared with (false) the newly constructed matrix. When the data is copied, the allocated buffer is managed using Mat reference counting mechanism. While the data is shared, the reference counter is NULL, and you should not deallocate the data until the matrix is not destructed.
template<typename _Tp , int n>
cv::Mat::Mat ( const Vec< _Tp, n > &  vec,
bool  copyData = true 
)
explicit

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp , int m, int n>
cv::Mat::Mat ( const Matx< _Tp, m, n > &  mtx,
bool  copyData = true 
)
explicit

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp >
cv::Mat::Mat ( const Point_< _Tp > &  pt,
bool  copyData = true 
)
explicit

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp >
cv::Mat::Mat ( const Point3_< _Tp > &  pt,
bool  copyData = true 
)
explicit

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp >
cv::Mat::Mat ( const MatCommaInitializer_< _Tp > &  commaInitializer)
explicit

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

cv::Mat::Mat ( const cuda::GpuMat m)
explicit

download data from GpuMat

cv::Mat::~Mat ( )

destructor - calls release()

Member Function Documentation

void cv::Mat::addref ( )

Increments the reference counter.

The method increments the reference counter associated with the matrix data. If the matrix header points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no effect in this case. Normally, to avoid memory leaks, the method should not be called explicitly. It is called implicitly by the matrix assignment operator. The reference counter increment is an atomic operation on the platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in different threads.

Mat& cv::Mat::adjustROI ( int  dtop,
int  dbottom,
int  dleft,
int  dright 
)

Adjusts a submatrix size and position within the parent matrix.

The method is complimentary to Mat::locateROI . The typical use of these functions is to determine the submatrix position within the parent matrix and then shift the position somehow. Typically, it can be required for filtering operations when pixels outside of the ROI should be taken into account. When all the method parameters are positive, the ROI needs to grow in all directions by the specified amount, for example:

A.adjustROI(2, 2, 2, 2);

In this example, the matrix size is increased by 4 elements in each direction. The matrix is shifted by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the filtering with the 5x5 kernel.

adjustROI forces the adjusted ROI to be inside of the parent matrix that is boundaries of the adjusted ROI are constrained by boundaries of the parent matrix. For example, if the submatrix A is located in the first row of a parent matrix and you called A.adjustROI(2, 2, 2, 2) then A will not be increased in the upward direction.

The function is used internally by the OpenCV filtering functions, like filter2D , morphological operations, and so on.

Parameters
dtopShift of the top submatrix boundary upwards.
dbottomShift of the bottom submatrix boundary downwards.
dleftShift of the left submatrix boundary to the left.
drightShift of the right submatrix boundary to the right.
See also
copyMakeBorder
void cv::Mat::assignTo ( Mat m,
int  type = -1 
) const

Provides a functional form of convertTo.

This is an internally used method called by the MatrixExpressions engine.

Parameters
mDestination array.
typeDesired destination array depth (or -1 if it should be the same as the source type).
template<typename _Tp >
_Tp& cv::Mat::at ( int  i0 = 0)

Returns a reference to the specified array element.

The template methods return a reference to the specified array element. For the sake of higher performance, the index range checks are only performed in the Debug configuration.

Note that the variants with a single index (i) can be used to access elements of single-row or single-column 2-dimensional arrays. That is, if, for example, A is a 1 x N floating-point matrix and B is an M x 1 integer matrix, you can simply write A.at<float>(k+4) and B.at<int>(2*i+1) instead of A.at<float>(0,k+4) and B.at<int>(2*i+1,0), respectively.

The example below initializes a Hilbert matrix:

Mat H(100, 100, CV_64F);
for(int i = 0; i < H.rows; i++)
for(int j = 0; j < H.cols; j++)
H.at<double>(i,j)=1./(i+j+1);

Keep in mind that the size identifier used in the at operator cannot be chosen at random. It depends on the image from which you are trying to retrieve the data. The table below gives a better insight in this:

  • If matrix is of type CV_8U then use Mat.at<uchar>(y,x).
  • If matrix is of type CV_8S then use Mat.at<schar>(y,x).
  • If matrix is of type CV_16U then use Mat.at<ushort>(y,x).
  • If matrix is of type CV_16S then use Mat.at<short>(y,x).
  • If matrix is of type CV_32S then use Mat.at<int>(y,x).
  • If matrix is of type CV_32F then use Mat.at<float>(y,x).
  • If matrix is of type CV_64F then use Mat.at<double>(y,x).
Parameters
i0Index along the dimension 0
Examples:
cout_mat.cpp, demhist.cpp, kmeans.cpp, and watershed.cpp.

Referenced by cv::AGAST().

Here is the caller graph for this function:

template<typename _Tp >
const _Tp& cv::Mat::at ( int  i0 = 0) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
i0Index along the dimension 0
template<typename _Tp >
_Tp& cv::Mat::at ( int  row,
int  col 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
rowIndex along the dimension 0
colIndex along the dimension 1
template<typename _Tp >
const _Tp& cv::Mat::at ( int  row,
int  col 
) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
rowIndex along the dimension 0
colIndex along the dimension 1
template<typename _Tp >
_Tp& cv::Mat::at ( int  i0,
int  i1,
int  i2 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
i0Index along the dimension 0
i1Index along the dimension 1
i2Index along the dimension 2
template<typename _Tp >
const _Tp& cv::Mat::at ( int  i0,
int  i1,
int  i2 
) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
i0Index along the dimension 0
i1Index along the dimension 1
i2Index along the dimension 2
template<typename _Tp >
_Tp& cv::Mat::at ( const int *  idx)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
idxArray of Mat::dims indices.
template<typename _Tp >
const _Tp& cv::Mat::at ( const int *  idx) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
idxArray of Mat::dims indices.
template<typename _Tp , int n>
_Tp& cv::Mat::at ( const Vec< int, n > &  idx)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp , int n>
const _Tp& cv::Mat::at ( const Vec< int, n > &  idx) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp >
_Tp& cv::Mat::at ( Point  pt)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. special versions for 2D arrays (especially convenient for referencing image pixels)

Parameters
ptElement position specified as Point(j,i) .
template<typename _Tp >
const _Tp& cv::Mat::at ( Point  pt) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. special versions for 2D arrays (especially convenient for referencing image pixels)

Parameters
ptElement position specified as Point(j,i) .
template<typename _Tp >
MatIterator_<_Tp> cv::Mat::begin ( )

Returns the matrix iterator and sets it to the first matrix element.

The methods return the matrix read-only or read-write iterators. The use of matrix iterators is very similar to the use of bi-directional STL iterators. In the example below, the alpha blending function is rewritten using the matrix iterators:

template<typename T>
void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst)
{
typedef Vec<T, 4> VT;
const float alpha_scale = (float)std::numeric_limits<T>::max(),
inv_scale = 1.f/alpha_scale;
CV_Assert( src1.type() == src2.type() &&
src1.type() == DataType<VT>::type &&
src1.size() == src2.size());
Size size = src1.size();
dst.create(size, src1.type());
MatConstIterator_<VT> it1 = src1.begin<VT>(), it1_end = src1.end<VT>();
MatConstIterator_<VT> it2 = src2.begin<VT>();
MatIterator_<VT> dst_it = dst.begin<VT>();
for( ; it1 != it1_end; ++it1, ++it2, ++dst_it )
{
VT pix1 = *it1, pix2 = *it2;
float alpha = pix1[3]*inv_scale, beta = pix2[3]*inv_scale;
*dst_it = VT(saturate_cast<T>(pix1[0]*alpha + pix2[0]*beta),
saturate_cast<T>(pix1[1]*alpha + pix2[1]*beta),
saturate_cast<T>(pix1[2]*alpha + pix2[2]*beta),
saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale));
}
}
template<typename _Tp >
MatConstIterator_<_Tp> cv::Mat::begin ( ) const
int cv::Mat::channels ( ) const

Returns the number of matrix channels.

The method returns the number of matrix channels.

Examples:
pca.cpp.

Referenced by cv::hpp::getHpp().

Here is the caller graph for this function:

int cv::Mat::checkVector ( int  elemChannels,
int  depth = -1,
bool  requireContinuous = true 
) const

returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise

Mat cv::Mat::clone ( ) const

Creates a full copy of the array and the underlying data.

The method creates a full copy of the array. The original step[] is not taken into account. So, the array copy is a continuous array occupying total()*elemSize() bytes.

Examples:
houghlines.cpp.

Referenced by cv::AGAST_5_8(), cv::AGAST_7_12d(), cv::AGAST_7_12s(), cv::DescriptorMatcher::clone_op(), cv::OAST_9_16(), cv::detail::BundleAdjusterBase::refinementMask(), and cv::detail::BundleAdjusterBase::setRefinementMask().

Here is the caller graph for this function:

Mat cv::Mat::col ( int  x) const

Creates a matrix header for the specified matrix column.

The method makes a new header for the specified matrix column and returns it. This is an O(1) operation, regardless of the matrix size. The underlying data of the new matrix is shared with the original matrix. See also the Mat::row description.

Parameters
xA 0-based column index.
Mat cv::Mat::colRange ( int  startcol,
int  endcol 
) const

Creates a matrix header for the specified column span.

The method makes a new header for the specified column span of the matrix. Similarly to Mat::row and Mat::col , this is an O(1) operation.

Parameters
startcolAn inclusive 0-based start index of the column span.
endcolAn exclusive 0-based ending index of the column span.
Mat cv::Mat::colRange ( const Range r) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
rRange structure containing both the start and the end indices.
void cv::Mat::convertTo ( OutputArray  m,
int  rtype,
double  alpha = 1,
double  beta = 0 
) const

Converts an array to another data type with optional scaling.

The method converts source pixel values to the target data type. saturate_cast<> is applied at the end to avoid possible overflows:

\[m(x,y) = saturate \_ cast<rType>( \alpha (*this)(x,y) + \beta )\]

Parameters
moutput matrix; if it does not have a proper size or type before the operation, it is reallocated.
rtypedesired output matrix type or, rather, the depth since the number of channels are the same as the input has; if rtype is negative, the output matrix will have the same type as the input.
alphaoptional scale factor.
betaoptional delta added to the scaled values.
Examples:
demhist.cpp, distrans.cpp, fitellipse.cpp, and pca.cpp.

Referenced by cv::cv2eigen().

Here is the caller graph for this function:

void cv::Mat::copySize ( const Mat m)

internal use function; properly re-allocates _size, _step arrays

void cv::Mat::copyTo ( OutputArray  m) const

Copies the matrix to another one.

The method copies the matrix data to another matrix. Before copying the data, the method invokes :

m.create(this->size(), this->type());

so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the function does not handle the case of a partial overlap between the source and the destination matrices.

When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data.

Parameters
mDestination matrix. If it does not have a proper size or type before the operation, it is reallocated.
Examples:
edge.cpp, and grabcut.cpp.

Referenced by cv::cv2eigen(), cv::eigen2cv(), and cv::videostab::FastMarchingMethod::run().

Here is the caller graph for this function:

void cv::Mat::copyTo ( OutputArray  m,
InputArray  mask 
) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
mDestination matrix. If it does not have a proper size or type before the operation, it is reallocated.
maskOperation mask. Its non-zero elements indicate which matrix elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels.
void cv::Mat::create ( int  rows,
int  cols,
int  type 
)

Allocates new array data if needed.

This is one of the key Mat methods. Most new-style OpenCV functions and methods that produce arrays call this method for each output array. The method uses the following algorithm:

  1. If the current array shape and the type match the new ones, return immediately. Otherwise, de-reference the previous data by calling Mat::release.
  2. Initialize the new header.
  3. Allocate the new data of total()*elemSize() bytes.
  4. Allocate the new, associated with the data, reference counter and set it to 1.

Such a scheme makes the memory management robust and efficient at the same time and helps avoid extra typing for you. This means that usually there is no need to explicitly allocate output arrays. That is, instead of writing:

Mat color;
...
Mat gray(color.rows, color.cols, color.depth());
cvtColor(color, gray, COLOR_BGR2GRAY);

you can simply write:

Mat color;
...
Mat gray;
cvtColor(color, gray, COLOR_BGR2GRAY);

because cvtColor, as well as the most of OpenCV functions, calls Mat::create() for the output array internally.

Parameters
rowsNew number of rows.
colsNew number of columns.
typeNew matrix type.
Examples:
edge.cpp, ffilldemo.cpp, and grabcut.cpp.

Referenced by cv::hpp::copyHppToMat().

Here is the caller graph for this function:

void cv::Mat::create ( Size  size,
int  type 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
sizeAlternative new matrix size specification: Size(cols, rows)
typeNew matrix type.
void cv::Mat::create ( int  ndims,
const int *  sizes,
int  type 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
ndimsNew array dimensionality.
sizesArray of integers specifying a new array shape.
typeNew matrix type.
void cv::Mat::create ( const std::vector< int > &  sizes,
int  type 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
sizesArray of integers specifying a new array shape.
typeNew matrix type.
Mat cv::Mat::cross ( InputArray  m) const

Computes a cross-product of two 3-element vectors.

The method computes a cross-product of two 3-element vectors. The vectors must be 3-element floating-point vectors of the same shape and size. The result is another 3-element vector of the same shape and type as operands.

Parameters
mAnother cross-product operand.
void cv::Mat::deallocate ( )

deallocates the matrix data

int cv::Mat::depth ( ) const

Returns the depth of a matrix element.

The method returns the identifier of the matrix element depth (the type of each individual channel). For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of matrix types contains the following values:

  • CV_8U - 8-bit unsigned integers ( 0..255 )
  • CV_8S - 8-bit signed integers ( -128..127 )
  • CV_16U - 16-bit unsigned integers ( 0..65535 )
  • CV_16S - 16-bit signed integers ( -32768..32767 )
  • CV_32S - 32-bit signed integers ( -2147483648..2147483647 )
  • CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN )
  • CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN )
Mat cv::Mat::diag ( int  d = 0) const

Extracts a diagonal from a matrix.

The method makes a new header for the specified matrix diagonal. The new matrix is represented as a single-column matrix. Similarly to Mat::row and Mat::col, this is an O(1) operation.

Parameters
dindex of the diagonal, with the following values:
  • d=0 is the main diagonal.
  • d<0 is a diagonal from the lower half. For example, d=-1 means the diagonal is set immediately below the main one.
  • d>0 is a diagonal from the upper half. For example, d=1 means the diagonal is set immediately above the main one.
static Mat cv::Mat::diag ( const Mat d)
static

creates a diagonal matrix

The method creates a square diagonal matrix from specified main diagonal.

Parameters
dOne-dimensional matrix that represents the main diagonal.
double cv::Mat::dot ( InputArray  m) const

Computes a dot-product of two vectors.

The method computes a dot-product of two matrices. If the matrices are not single-column or single-row vectors, the top-to-bottom left-to-right scan ordering is used to treat them as 1D vectors. The vectors must have the same size and type. If the matrices have more than one channel, the dot products from all the channels are summed together.

Parameters
manother dot-product operand.
size_t cv::Mat::elemSize ( ) const

Returns the matrix element size in bytes.

The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 , the method returns 3*sizeof(short) or 6.

size_t cv::Mat::elemSize1 ( ) const

Returns the size of each matrix element channel in bytes.

The method returns the matrix element channel size in bytes, that is, it ignores the number of channels. For example, if the matrix type is CV_16SC3 , the method returns sizeof(short) or 2.

bool cv::Mat::empty ( ) const

Returns true if the array has no elements.

The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and resize() methods M.total() == 0 does not imply that M.data == NULL.

Examples:
grabcut.cpp, and houghlines.cpp.
template<typename _Tp >
MatIterator_<_Tp> cv::Mat::end ( )

Returns the matrix iterator and sets it to the after-last matrix element.

The methods return the matrix read-only or read-write iterators, set to the point following the last matrix element.

template<typename _Tp >
MatConstIterator_<_Tp> cv::Mat::end ( ) const
static MatExpr cv::Mat::eye ( int  rows,
int  cols,
int  type 
)
static

Returns an identity matrix of the specified size and type.

The method returns a Matlab-style identity matrix initializer, similarly to Mat::zeros. Similarly to Mat::ones, you can use a scale operation to create a scaled identity matrix efficiently:

// make a 4x4 diagonal matrix with 0.1's on the diagonal.
Mat A = Mat::eye(4, 4, CV_32F)*0.1;
Parameters
rowsNumber of rows.
colsNumber of columns.
typeCreated matrix type.
static MatExpr cv::Mat::eye ( Size  size,
int  type 
)
static

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
sizeAlternative matrix size specification as Size(cols, rows) .
typeCreated matrix type.
template<typename _Tp , typename Functor >
void cv::Mat::forEach ( const Functor &  operation)

Runs the given functor over all matrix elements in parallel.

The operation passed as argument has to be a function pointer, a function object or a lambda(C++11).

Example 1. All of the operations below put 0xFF the first channel of all matrix elements:

Mat image(1920, 1080, CV_8UC3);
typedef cv::Point3_<uint8_t> Pixel;
// first. raw pointer access.
for (int r = 0; r < image.rows; ++r) {
Pixel* ptr = image.ptr<Pixel>(r, 0);
const Pixel* ptr_end = ptr + image.cols;
for (; ptr != ptr_end; ++ptr) {
ptr->x = 255;
}
}
// Using MatIterator. (Simple but there are a Iterator's overhead)
for (Pixel &p : cv::Mat_<Pixel>(image)) {
p.x = 255;
}
// Parallel execution with function object.
struct Operator {
void operator ()(Pixel &pixel, const int * position) {
pixel.x = 255;
}
};
image.forEach<Pixel>(Operator());
// Parallel execution using C++11 lambda.
image.forEach<Pixel>([](Pixel &p, const int * position) -> void {
p.x = 255;
});

Example 2. Using the pixel's position:

// Creating 3D matrix (255 x 255 x 255) typed uint8_t
// and initialize all elements by the value which equals elements position.
// i.e. pixels (x,y,z) = (1,2,3) is (b,g,r) = (1,2,3).
int sizes[] = { 255, 255, 255 };
typedef cv::Point3_<uint8_t> Pixel;
Mat_<Pixel> image = Mat::zeros(3, sizes, CV_8UC3);
image.forEach<Pixel>([&](Pixel& pixel, const int position[]) -> void {
pixel.x = position[0];
pixel.y = position[1];
pixel.z = position[2];
});
template<typename _Tp , typename Functor >
void cv::Mat::forEach ( const Functor &  operation) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

static MatAllocator* cv::Mat::getDefaultAllocator ( )
static
static MatAllocator* cv::Mat::getStdAllocator ( )
static

and the standard allocator

UMat cv::Mat::getUMat ( int  accessFlags,
UMatUsageFlags  usageFlags = USAGE_DEFAULT 
) const

retrieve UMat from Mat

MatExpr cv::Mat::inv ( int  method = DECOMP_LU) const

Inverses a matrix.

The method performs a matrix inversion by means of matrix expressions. This means that a temporary matrix inversion object is returned by the method and can be used further as a part of more complex matrix expressions or can be assigned to a matrix.

Parameters
methodMatrix inversion method. One of cv::DecompTypes
bool cv::Mat::isContinuous ( ) const

Reports whether the matrix is continuous or not.

The method returns true if the matrix elements are stored continuously without gaps at the end of each row. Otherwise, it returns false. Obviously, 1x1 or 1xN matrices are always continuous. Matrices created with Mat::create are always continuous. But if you extract a part of the matrix using Mat::col, Mat::diag, and so on, or constructed a matrix header for externally allocated data, such matrices may no longer have this property.

The continuity flag is stored as a bit in the Mat::flags field and is computed automatically when you construct a matrix header. Thus, the continuity check is a very fast operation, though theoretically it could be done as follows:

// alternative implementation of Mat::isContinuous()
bool myCheckMatContinuity(const Mat& m)
{
//return (m.flags & Mat::CONTINUOUS_FLAG) != 0;
return m.rows == 1 || m.step == m.cols*m.elemSize();
}

The method is used in quite a few of OpenCV functions. The point is that element-wise operations (such as arithmetic and logical operations, math functions, alpha blending, color space transformations, and others) do not depend on the image geometry. Thus, if all the input and output arrays are continuous, the functions can process them as very long single-row vectors. The example below illustrates how an alpha-blending function can be implemented:

template<typename T>
void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst)
{
const float alpha_scale = (float)std::numeric_limits<T>::max(),
inv_scale = 1.f/alpha_scale;
CV_Assert( src1.type() == src2.type() &&
src1.type() == CV_MAKETYPE(DataType<T>::depth, 4) &&
src1.size() == src2.size());
Size size = src1.size();
dst.create(size, src1.type());
// here is the idiom: check the arrays for continuity and,
// if this is the case,
// treat the arrays as 1D vectors
if( src1.isContinuous() && src2.isContinuous() && dst.isContinuous() )
{
size.width *= size.height;
size.height = 1;
}
size.width *= 4;
for( int i = 0; i < size.height; i++ )
{
// when the arrays are continuous,
// the outer loop is executed only once
const T* ptr1 = src1.ptr<T>(i);
const T* ptr2 = src2.ptr<T>(i);
T* dptr = dst.ptr<T>(i);
for( int j = 0; j < size.width; j += 4 )
{
float alpha = ptr1[j+3]*inv_scale, beta = ptr2[j+3]*inv_scale;
dptr[j] = saturate_cast<T>(ptr1[j]*alpha + ptr2[j]*beta);
dptr[j+1] = saturate_cast<T>(ptr1[j+1]*alpha + ptr2[j+1]*beta);
dptr[j+2] = saturate_cast<T>(ptr1[j+2]*alpha + ptr2[j+2]*beta);
dptr[j+3] = saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale);
}
}
}

This approach, while being very simple, can boost the performance of a simple element-operation by 10-20 percents, especially if the image is rather small and the operation is quite simple.

Another OpenCV idiom in this function, a call of Mat::create for the destination array, that allocates the destination array unless it already has the proper size and type. And while the newly allocated arrays are always continuous, you still need to check the destination array because Mat::create does not always allocate a new matrix.

Referenced by cv::AGAST_5_8(), cv::AGAST_7_12d(), cv::AGAST_7_12s(), cv::flann::GenericIndex< Distance >::getIndexParameters(), cv::flann::hierarchicalClustering(), cv::flann::Index_< T >::Index_(), cv::flann::Index_< T >::knnSearch(), cv::OAST_9_16(), and cv::flann::Index_< T >::radiusSearch().

Here is the caller graph for this function:

bool cv::Mat::isSubmatrix ( ) const

returns true if the matrix is a submatrix of another matrix

void cv::Mat::locateROI ( Size wholeSize,
Point ofs 
) const

Locates the matrix header within a parent matrix.

After you extracted a submatrix from a matrix using Mat::row, Mat::col, Mat::rowRange, Mat::colRange, and others, the resultant submatrix points just to the part of the original big matrix. However, each submatrix contains information (represented by datastart and dataend fields) that helps reconstruct the original matrix size and the position of the extracted submatrix within the original matrix. The method locateROI does exactly that.

Parameters
wholeSizeOutput parameter that contains the size of the whole matrix containing this as a part.
ofsOutput parameter that contains an offset of this inside the whole matrix.
MatExpr cv::Mat::mul ( InputArray  m,
double  scale = 1 
) const

Performs an element-wise multiplication or division of the two matrices.

The method returns a temporary object encoding per-element array multiplication, with optional scale. Note that this is not a matrix multiplication that corresponds to a simpler "\*" operator.

Example:

Mat C = A.mul(5/B); // equivalent to divide(A, B, C, 5)
Parameters
mAnother array of the same type and the same size as *this, or a matrix expression.
scaleOptional scale factor.
static MatExpr cv::Mat::ones ( int  rows,
int  cols,
int  type 
)
static

Returns an array of all 1's of the specified size and type.

The method returns a Matlab-style 1's array initializer, similarly to Mat::zeros. Note that using this method you can initialize an array with an arbitrary value, using the following Matlab idiom:

Mat A = Mat::ones(100, 100, CV_8U)*3; // make 100x100 matrix filled with 3.

The above operation does not form a 100x100 matrix of 1's and then multiply it by 3. Instead, it just remembers the scale factor (3 in this case) and use it when actually invoking the matrix initializer.

Parameters
rowsNumber of rows.
colsNumber of columns.
typeCreated matrix type.
Examples:
demhist.cpp.

Referenced by cv::detail::BundleAdjusterBase::BundleAdjusterBase().

Here is the caller graph for this function:

static MatExpr cv::Mat::ones ( Size  size,
int  type 
)
static

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
sizeAlternative to the matrix size specification Size(cols, rows) .
typeCreated matrix type.
static MatExpr cv::Mat::ones ( int  ndims,
const int *  sz,
int  type 
)
static

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
ndimsArray dimensionality.
szArray of integers specifying the array shape.
typeCreated matrix type.
template<typename _Tp , int m, int n>
cv::Mat::operator Matx< _Tp, m, n > ( ) const
template<typename _Tp >
cv::Mat::operator std::vector< _Tp > ( ) const
template<typename _Tp , int n>
cv::Mat::operator Vec< _Tp, n > ( ) const
Mat cv::Mat::operator() ( Range  rowRange,
Range  colRange 
) const

Extracts a rectangular submatrix.

The operators make a new header for the specified sub-array of *this . They are the most generalized forms of Mat::row, Mat::col, Mat::rowRange, and Mat::colRange . For example, A(Range(0, 10), Range::all()) is equivalent to A.rowRange(0, 10). Similarly to all of the above, the operators are O(1) operations, that is, no matrix data is copied.

Parameters
rowRangeStart and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use Range::all().
colRangeStart and end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use Range::all().
Mat cv::Mat::operator() ( const Rect roi) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
roiExtracted submatrix specified as a rectangle.
Mat cv::Mat::operator() ( const Range ranges) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
rangesArray of selected ranges along each array dimension.
Mat cv::Mat::operator() ( const std::vector< Range > &  ranges) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
rangesArray of selected ranges along each array dimension.
Mat& cv::Mat::operator= ( const Mat m)

assignment operators

These are available assignment operators. Since they all are very different, make sure to read the operator parameters description.

Parameters
mAssigned, right-hand-side matrix. Matrix assignment is an O(1) operation. This means that no data is copied but the data is shared and the reference counter, if any, is incremented. Before assigning new data, the old data is de-referenced via Mat::release .
Mat& cv::Mat::operator= ( const MatExpr expr)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
exprAssigned matrix expression object. As opposite to the first form of the assignment operation, the second form can reuse already allocated matrix if it has the right size and type to fit the matrix expression result. It is automatically handled by the real function that the matrix expressions is expanded to. For example, C=A+B is expanded to add(A, B, C), and add takes care of automatic C reallocation.
Mat& cv::Mat::operator= ( const Scalar s)

Sets all or some of the array elements to the specified value.

Parameters
sAssigned scalar converted to the actual array type.
void cv::Mat::pop_back ( size_t  nelems = 1)

Removes elements from the bottom of the matrix.

The method removes one or more rows from the bottom of the matrix.

Parameters
nelemsNumber of removed rows. If it is greater than the total number of rows, an exception is thrown.
uchar* cv::Mat::ptr ( int  i0 = 0)

Returns a pointer to the specified matrix row.

The methods return uchar* or typed pointer to the specified matrix row. See the sample in Mat::isContinuous to know how to use these methods.

Parameters
i0A 0-based row index.

Referenced by cv::AGAST_5_8(), cv::AGAST_7_12d(), cv::AGAST_7_12s(), cv::flann::GenericIndex< Distance >::getIndexParameters(), cv::flann::hierarchicalClustering(), cv::flann::Index_< T >::Index_(), cv::flann::Index_< T >::knnSearch(), cv::OAST_9_16(), and cv::flann::Index_< T >::radiusSearch().

Here is the caller graph for this function:

const uchar* cv::Mat::ptr ( int  i0 = 0) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

uchar* cv::Mat::ptr ( int  row,
int  col 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
rowIndex along the dimension 0
colIndex along the dimension 1
const uchar* cv::Mat::ptr ( int  row,
int  col 
) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
rowIndex along the dimension 0
colIndex along the dimension 1
uchar* cv::Mat::ptr ( int  i0,
int  i1,
int  i2 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

const uchar* cv::Mat::ptr ( int  i0,
int  i1,
int  i2 
) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

uchar* cv::Mat::ptr ( const int *  idx)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

const uchar* cv::Mat::ptr ( const int *  idx) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<int n>
uchar* cv::Mat::ptr ( const Vec< int, n > &  idx)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<int n>
const uchar* cv::Mat::ptr ( const Vec< int, n > &  idx) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp >
_Tp* cv::Mat::ptr ( int  i0 = 0)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp >
const _Tp* cv::Mat::ptr ( int  i0 = 0) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp >
_Tp* cv::Mat::ptr ( int  row,
int  col 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
rowIndex along the dimension 0
colIndex along the dimension 1
template<typename _Tp >
const _Tp* cv::Mat::ptr ( int  row,
int  col 
) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
rowIndex along the dimension 0
colIndex along the dimension 1
template<typename _Tp >
_Tp* cv::Mat::ptr ( int  i0,
int  i1,
int  i2 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp >
const _Tp* cv::Mat::ptr ( int  i0,
int  i1,
int  i2 
) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp >
_Tp* cv::Mat::ptr ( const int *  idx)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp >
const _Tp* cv::Mat::ptr ( const int *  idx) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp , int n>
_Tp* cv::Mat::ptr ( const Vec< int, n > &  idx)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp , int n>
const _Tp* cv::Mat::ptr ( const Vec< int, n > &  idx) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<typename _Tp >
void cv::Mat::push_back ( const _Tp &  elem)

Adds elements to the bottom of the matrix.

The methods add one or more elements to the bottom of the matrix. They emulate the corresponding method of the STL vector class. When elem is Mat , its type and the number of columns must be the same as in the container matrix.

Parameters
elemAdded element(s).
template<typename _Tp >
void cv::Mat::push_back ( const Mat_< _Tp > &  elem)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
elemAdded element(s).
void cv::Mat::push_back ( const Mat m)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
mAdded line(s).
void cv::Mat::push_back_ ( const void *  elem)

internal function

void cv::Mat::release ( )

Decrements the reference counter and deallocates the matrix if needed.

The method decrements the reference counter associated with the matrix data. When the reference counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers are set to NULL's. If the matrix header points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no effect in this case.

This method can be called manually to force the matrix data deallocation. But since this method is automatically called in the destructor, or by any other method that changes the data pointer, it is usually not needed. The reference counter decrement and check for 0 is an atomic operation on the platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in different threads.

Referenced by cv::hpp::copyHppToMat().

Here is the caller graph for this function:

void cv::Mat::reserve ( size_t  sz)

Reserves space for the certain number of rows.

The method reserves space for sz rows. If the matrix already has enough space to store sz rows, nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method emulates the corresponding method of the STL vector class.

Parameters
szNumber of rows.
Mat cv::Mat::reshape ( int  cn,
int  rows = 0 
) const

Changes the shape and/or the number of channels of a 2D matrix without copying the data.

The method makes a new matrix header for *this elements. The new matrix may have a different size and/or different number of channels. Any combination is possible if:

  • No extra elements are included into the new matrix and no elements are excluded. Consequently, the product rows*cols*channels() must stay the same after the transformation.
  • No data is copied. That is, this is an O(1) operation. Consequently, if you change the number of rows, or the operation changes the indices of elements row in some other way, the matrix must be continuous. See Mat::isContinuous .

For example, if there is a set of 3D points stored as an STL vector, and you want to represent the points as a 3xN matrix, do the following:

std::vector<Point3f> vec;
...
Mat pointMat = Mat(vec). // convert vector to Mat, O(1) operation
reshape(1). // make Nx3 1-channel matrix out of Nx1 3-channel.
// Also, an O(1) operation
t(); // finally, transpose the Nx3 matrix.
// This involves copying all the elements
Parameters
cnNew number of channels. If the parameter is 0, the number of channels remains the same.
rowsNew number of rows. If the parameter is 0, the number of rows remains the same.
Examples:
pca.cpp.
Mat cv::Mat::reshape ( int  cn,
int  newndims,
const int *  newsz 
) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

void cv::Mat::resize ( size_t  sz)

Changes the number of matrix rows.

The methods change the number of matrix rows. If the matrix is reallocated, the first min(Mat::rows, sz) rows are preserved. The methods emulate the corresponding methods of the STL vector class.

Parameters
szNew number of rows.
void cv::Mat::resize ( size_t  sz,
const Scalar s 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
szNew number of rows.
sValue assigned to the newly added elements.
Mat cv::Mat::row ( int  y) const

Creates a matrix header for the specified matrix row.

The method makes a new header for the specified matrix row and returns it. This is an O(1) operation, regardless of the matrix size. The underlying data of the new matrix is shared with the original matrix. Here is the example of one of the classical basic matrix processing operations, axpy, used by LU and many other algorithms:

inline void matrix_axpy(Mat& A, int i, int j, double alpha)
{
A.row(i) += A.row(j)*alpha;
}
Note
In the current implementation, the following code does not work as expected:
Mat A;
...
A.row(i) = A.row(j); // will not work
This happens because A.row(i) forms a temporary header that is further assigned to another header. Remember that each of these operations is O(1), that is, no data is copied. Thus, the above assignment is not true if you may have expected the j-th row to be copied to the i-th row. To achieve that, you should either turn this simple assignment into an expression or use the Mat::copyTo method:
Mat A;
...
// works, but looks a bit obscure.
A.row(i) = A.row(j) + 0;
// this is a bit longer, but the recommended method.
A.row(j).copyTo(A.row(i));
Parameters
yA 0-based row index.
Examples:
pca.cpp.
Mat cv::Mat::rowRange ( int  startrow,
int  endrow 
) const

Creates a matrix header for the specified row span.

The method makes a new header for the specified row span of the matrix. Similarly to Mat::row and Mat::col , this is an O(1) operation.

Parameters
startrowAn inclusive 0-based start index of the row span.
endrowAn exclusive 0-based ending index of the row span.
Examples:
kmeans.cpp.
Mat cv::Mat::rowRange ( const Range r) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
rRange structure containing both the start and the end indices.
static void cv::Mat::setDefaultAllocator ( MatAllocator allocator)
static
Mat& cv::Mat::setTo ( InputArray  value,
InputArray  mask = noArray() 
)

Sets all or some of the array elements to the specified value.

This is an advanced variant of the Mat::operator=(const Scalar& s) operator.

Parameters
valueAssigned scalar converted to the actual array type.
maskOperation mask of the same size as *this.
size_t cv::Mat::step1 ( int  i = 0) const

Returns a normalized step.

The method returns a matrix step divided by Mat::elemSize1() . It can be useful to quickly access an arbitrary matrix element.

MatExpr cv::Mat::t ( ) const

Transposes a matrix.

The method performs matrix transposition by means of matrix expressions. It does not perform the actual transposition but returns a temporary matrix transposition object that can be further used as a part of more complex matrix expressions or can be assigned to a matrix:

Mat A1 = A + Mat::eye(A.size(), A.type())*lambda;
Mat C = A1.t()*A1; // compute (A + lambda*I)^t * (A + lamda*I)

Referenced by cv::cv2eigen().

Here is the caller graph for this function:

size_t cv::Mat::total ( ) const

Returns the total number of array elements.

The method returns the number of array elements (a number of pixels if the array represents an image).

int cv::Mat::type ( ) const

Returns the type of a matrix element.

The method returns a matrix element type. This is an identifier compatible with the CvMat type system, like CV_16SC3 or 16-bit signed 3-channel array, and so on.

Examples:
grabcut.cpp.

Referenced by cv::cv2eigen(), CvMat::CvMat(), cv::hpp::getHpp(), cv::flann::GenericIndex< Distance >::getIndexParameters(), cv::flann::hierarchicalClustering(), cv::flann::Index_< T >::Index_(), cv::flann::Index_< T >::knnSearch(), cv::flann::Index_< T >::radiusSearch(), cv::videostab::FastMarchingMethod::run(), and cv::detail::BundleAdjusterBase::setRefinementMask().

Here is the caller graph for this function:

static MatExpr cv::Mat::zeros ( int  rows,
int  cols,
int  type 
)
static

Returns a zero array of the specified size and type.

The method returns a Matlab-style zero array initializer. It can be used to quickly form a constant array as a function parameter, part of a matrix expression, or as a matrix initializer. :

Mat A;
A = Mat::zeros(3, 3, CV_32F);

In the example above, a new matrix is allocated only if A is not a 3x3 floating-point matrix. Otherwise, the existing matrix A is filled with zeros.

Parameters
rowsNumber of rows.
colsNumber of columns.
typeCreated matrix type.
Examples:
contours2.cpp, and fitellipse.cpp.
static MatExpr cv::Mat::zeros ( Size  size,
int  type 
)
static

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
sizeAlternative to the matrix size specification Size(cols, rows) .
typeCreated matrix type.
static MatExpr cv::Mat::zeros ( int  ndims,
const int *  sz,
int  type 
)
static

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
ndimsArray dimensionality.
szArray of integers specifying the array shape.
typeCreated matrix type.

Member Data Documentation

MatAllocator* cv::Mat::allocator

custom allocator

uchar* cv::Mat::data

pointer to the data

Referenced by cv::hpp::copyHppToMat(), CvMat::CvMat(), and cv::hpp::getHpp().

const uchar* cv::Mat::dataend
const uchar* cv::Mat::datalimit
const uchar* cv::Mat::datastart

helper fields used in locateROI and adjustROI

int cv::Mat::dims

the matrix dimensionality, >= 2

Referenced by CvMat::CvMat().

int cv::Mat::flags

includes several bit-fields:

  • the magic signature
  • continuity flag
  • depth
  • number of channels

Referenced by CvMat::CvMat().

UMatData* cv::Mat::u

interaction with UMat


The documentation for this class was generated from the following files: