Overview
The Mat class is the primary data structure in OpenCV for representing n-dimensional dense arrays. It can store real or complex-valued vectors, matrices, grayscale or color images, voxel volumes, vector fields, point clouds, tensors, and histograms.
Constructors
Default Constructor
Creates an empty matrix with no allocated data.
Size and Type Constructor
Mat(int rows, int cols, int type)
Mat(Size size, int type)
Number of rows in a 2D array
Number of columns in a 2D array
2D array size: Size(cols, rows)
Array type. Use CV_8UC1, …, CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), …, CV_64FC(n) to create multi-channel matrices (up to CV_CN_MAX channels)
Example:
// Create a 100x100 8-bit unsigned single-channel matrix
Mat img(100, 100, CV_8UC1);
// Create a 640x480 8-bit 3-channel color image
Mat colorImage(Size(640, 480), CV_8UC3);
Constructor with Initialization
Mat(int rows, int cols, int type, const Scalar& s)
Mat(Size size, int type, const Scalar& s)
Optional value to initialize each matrix element with
Example:
// Create a 7x7 complex matrix filled with 1+3j
Mat M(7, 7, CV_32FC2, Scalar(1, 3));
// Create a 100x100 matrix filled with zeros
Mat zeros(100, 100, CV_64F, Scalar(0));
Multi-dimensional Constructor
Mat(int ndims, const int* sizes, int type)
Mat(const std::vector<int>& sizes, int type)
Mat(int ndims, const int* sizes, int type, const Scalar& s)
Array of integers specifying an n-dimensional array shape
Example:
// Create a 100x100x100 8-bit 3D array
int sz[] = {100, 100, 100};
Mat bigCube(3, sz, CV_8U, Scalar::all(0));
User Data Constructor
Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP)
Mat(Size size, int type, void* data, size_t step=AUTO_STEP)
Pointer to user data. No data is copied; the matrix header points to the specified data
Number of bytes each matrix row occupies. If AUTO_STEP, no padding is assumed
The external data is not automatically deallocated, so you should manage it manually.
Copy Constructor
Creates a matrix header for the same data. This is an O(1) operation that does not copy data but increments the reference counter.
ROI Constructors
Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all())
Mat(const Mat& m, const Rect& roi)
Mat(const Mat& m, const Range* ranges)
Range of rows to take from the source matrix
Range of columns to take from the source matrix
Region of interest rectangle
Example:
Mat img(320, 240, CV_8UC3);
// Select a ROI
Mat roi(img, Rect(10, 10, 100, 100));
// Fill the ROI with green color
roi = Scalar(0, 255, 0);
Key Methods
create
void create(int rows, int cols, int type)
void create(Size size, int type)
void create(int ndims, const int* sizes, int type)
Allocates new array data if needed. If the array already has the specified size and type, the method does nothing.
clone
Creates a full copy of the array and underlying data.
Example:
Mat A = Mat::eye(3, 3, CV_32F);
Mat B = A.clone(); // B is an independent copy
copyTo
void copyTo(OutputArray m) const
void copyTo(OutputArray m, InputArray mask) const
Destination matrix. Reallocated if needed
Operation mask (8-bit single channel). Non-zero elements indicate which matrix elements to copy
convertTo
void convertTo(OutputArray m, int rtype, double alpha=1, double beta=0) const
Desired output matrix type or depth
Optional delta added to scaled values
Converts array to another data type with optional scaling: m(x,y) = saturate_cast<rType>(alpha*(*this)(x,y) + beta)
row / col
Mat row(int y) const
Mat col(int x) const
Creates a matrix header for the specified matrix row or column. This is an O(1) operation.
Example:
// Add the 5-th row, multiplied by 3 to the 3rd row
M.row(3) = M.row(3) + M.row(5) * 3;
rowRange / colRange
Mat rowRange(int startrow, int endrow) const
Mat rowRange(const Range& r) const
Mat colRange(int startcol, int endcol) const
Mat colRange(const Range& r) const
Creates a matrix header for the specified row or column span.
diag
Mat diag(int d=0) const
static Mat diag(const Mat& d)
Index of the diagonal. d=0 is the main diagonal, d<0 is below, d>0 is above
Extracts a diagonal from a matrix or creates a diagonal matrix.
reshape
Mat reshape(int cn, int rows=0) const
Mat reshape(int cn, int newndims, const int* newsz) const
New number of channels. If 0, the number of channels remains unchanged
New number of rows. If 0, the number of rows remains unchanged
Changes the shape and/or number of channels without copying data.
template<typename _Tp> _Tp& at(int i0, int i1)
template<typename _Tp> const _Tp& at(int i0, int i1) const
template<typename _Tp> _Tp& at(Point pt)
template<typename _Tp> _Tp& at(int i0, int i1, int i2)
Returns a reference to the specified array element.
Example:
Mat M(100, 100, CV_64F);
M.at<double>(i, j) += 1.0;
Mat colorImage(480, 640, CV_8UC3);
Vec3b& pixel = colorImage.at<Vec3b>(y, x);
pixel[0] = 255; // Blue channel
No bounds checking is performed in Release builds. Use with caution.
ptr
template<typename _Tp> _Tp* ptr(int i0=0)
template<typename _Tp> const _Tp* ptr(int i0=0) const
Returns a pointer to the specified matrix row.
Example:
// Efficient row-wise processing
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.);
}
Static Initialization Methods
zeros
static Mat zeros(int rows, int cols, int type)
static Mat zeros(Size size, int type)
static Mat zeros(int ndims, const int* sz, int type)
Returns a zero array of the specified size and type.
Example:
Mat Z = Mat::zeros(3, 3, CV_32F);
ones
static Mat ones(int rows, int cols, int type)
static Mat ones(Size size, int type)
static Mat ones(int ndims, const int* sz, int type)
Returns an array of all 1’s of the specified size and type.
eye
static Mat eye(int rows, int cols, int type)
static Mat eye(Size size, int type)
Returns an identity matrix of the specified size and type.
Example:
// Add identity matrix to M
M += Mat::eye(M.rows, M.cols, CV_64F);
Properties
Data Layout
Number of rows (for 2D arrays)
Number of columns (for 2D arrays)
Number of matrix dimensions (≥ 2)
Array of strides (step[0] contains the full row length in bytes)
Returns the matrix element type (CV_8UC1, CV_32FC3, etc.)
Returns the depth of the matrix elements (CV_8U, CV_32F, etc.)
Returns the number of channels
Returns element size in bytes
Returns size of each element channel in bytes
Returns the matrix size (for 2D matrices)
Returns the total number of array elements
Returns true if the array has no elements
Returns true if the matrix is continuous (no gaps at the end of rows)
Returns true if the matrix is a submatrix of another matrix
Operators
Assignment
Mat& operator=(const Mat& m)
Mat& operator=(const MatExpr& expr)
Matrix assignment is an O(1) operation that copies the header and increments the reference counter.
Element Access
template<typename _Tp> _Tp& operator()(int row, int col)
template<typename _Tp> _Tp& operator()(Point pt)
template<typename _Tp> _Tp& operator()(const int* idx)
Provides element access similar to at() method.
Arithmetic Operators
Matrix arithmetic operators (+, -, *, /) are supported through matrix expressions:
Mat A, B, C;
C = A + B; // Addition
C = A - B; // Subtraction
C = A * B; // Matrix multiplication
C = A / 2.0; // Scalar division
Memory Management
Mat uses reference counting for automatic memory management. When no one references the data, it’s automatically deallocated.
Example:
Mat A(100, 100, CV_32F);
Mat B = A; // B references the same data (O(1) operation)
Mat C = A.clone(); // C is an independent copy
// Manually release data before destructor
A.release();
Data Layout
For a 2D array, element (i,j) address is computed as:
addr(M[i,j]) = M.data + M.step[0]*i + M.step[1]*j
Matrices are stored row-by-row, with step[0] being the row length in bytes.
The data is stored continuously if isContinuous() returns true, meaning there are no gaps between rows. This allows for more efficient processing.