Assignment Operators
The cv::Mat class provides several asignment operators to handle data transfer, expression evaluation, and memory managemnet.
Mat& operator=(const Mat& m)
Assigns one matrix to another. This is a shallow copy; both matrices will point to the same underlying data buffer, incrementing the reference counter.
Mat& operator=(const MatExpr& expr)
Assigns the result of a matrix expression (e.g., addition, multiplication) to the matrix. This typically involves temporary allocation and calculation.
Mat& operator=(const Scalar& s)
Sets all elements in the matrix to the specified scalar value.
Mat& operator=(Mat&& m)
Move assignment operator. It transfers resource ownership from the source matrix to the target without copying data, which is highly efficient for temporary objects.
#include <opencv2/opencv.hpp>
#include <iostream>
int main() {
cv::Mat image = cv::imread("data.jpg");
if (image.empty()) return -1;
// Shallow copy via assignment
cv::Mat target = image;
// Expression assignment
cv::Mat alpha = (cv::Mat_<float>(2, 2) << 1, 2, 3, 4);
cv::Mat beta = (cv::Mat_<float>(2, 2) << 5, 6, 7, 8);
cv::Mat result = alpha.mul(beta);
// Scalar assignment
cv::Mat canvas(400, 400, CV_8UC3);
canvas = cv::Scalar(0, 255, 0); // Fill with green
// Move assignment
cv::Mat movedMat = std::move(image);
return 0;
}
Row Management: pop_back and push_back
These methods allow a cv::Mat to behave similarly to a std::vector by managing rows at the bottom of the matrix.
- pop_back(size_t nelems = 1): Removes the specified number of rows from the bottom.
- push_back(const _Tp& elem): Appends one or more rows to the bottom. The type and column count must match the existing matrix.
cv::Mat matrix = (cv::Mat_<int>(3, 2) << 10, 20, 30, 40, 50, 60);
matrix.pop_back(1); // Removes the last row
cv::Mat newRow = (cv::Mat_<int>(1, 2) << 100, 200);
matrix.push_back(newRow); // Appends [100, 200] to the bottom
Accessing Data with the ptr Method
The ptr() method provides raw pointer access to matrix rows or specific elements, offering high-performance data manipulation.
Common Overloads
uchar* ptr(int row): Pointer to the start of a specific row.template<typename _Tp> _Tp* ptr(int row, int col): Typed pointer to a specific element.
cv::Mat rawData(5, 5, CV_32FC1, cv::Scalar(0.0f));
// Accessing via row pointer
for (int r = 0; r < rawData.rows; ++r) {
float* rowPtr = rawData.ptr<float>(r);
for (int c = 0; c < rawData.cols; ++c) {
rowPtr[c] = static_cast<float>(r + c);
}
}
// Accessing specific coordinates
float* pixel = rawData.ptr<float>(2, 2);
*pixel = 99.9f;
Reverse Iterators
Similar to STL containers, cv::Mat supports reverse iteration through rbegin() and rend().
cv::Mat seq = (cv::Mat_<uchar>(1, 5) << 1, 2, 3, 4, 5);
auto it = seq.rbegin<uchar>();
auto itEnd = seq.rend<uchar>();
while (it != itEnd) {
std::cout << (int)(*it) << " ";
++it;
} // Outputs: 5 4 3 2 1
Memory and Buffer Control
- release(): Decrements the reference count. If the count hits zero, the buffer is deallocated.
- reserve(size_t sz): Pre-allocates memory for a specific number of rows to avoid frequent reallocations during
push_backoperations. - reserveBuffer(size_t sz): Reserves a specific number of bytes for the data buffer.
Structural Transformations
reshape
Changes the dimensions or channel count of a matrix without copying data.
cv::Mat original = cv::Mat::eye(4, 4, CV_32F);
// Change to 2 channels, 8 rows
cv::Mat reshaped = original.reshape(2, 8);
resize
Adjusts the number of rows in a matrix. If the new size is larger, it can be padded with a scalar value.
cv::Mat sample(10, 10, CV_8U, cv::Scalar(0));
sample.resize(15, cv::Scalar(255)); // Increases to 15 rows, new rows are white
Sub-region Selection
- row(int y): Returns a matrix header for a specific row.
- rowRange(int start, int end): Returns a header for a specific range of rows.
Value Initialization and Masking
setTo
Sets matrix elements to a specific value. It supports a optional mask to selectively update elements.
cv::Mat data = cv::Mat::zeros(5, 5, CV_8U);
cv::Mat mask = (cv::Mat_<uchar>(5, 5) << 1, 0, 1, 0, 1,
0, 1, 0, 1, 0,
1, 0, 1, 0, 1,
0, 1, 0, 1, 0,
1, 0, 1, 0, 1);
data.setTo(cv::Scalar(255), mask); // Sets elements to 255 where mask is non-zero
Matrix Metadata and Utilities
- step1(int i=0): Returns the normalized step (step divided by element size). Useful for calculating offsets.
- t(): Returns the transposed matrix.
- total(): Returns the total number of elements.
- type(): Returns the OpenCV type identifier (e.g., CV_8UC3).
cv::Mat m = cv::Mat::ones(3, 10, CV_32FC3);
std::cout << "Total elements: " << m.total() << std::endl;
std::cout << "Matrix Type: " << m.type() << std::endl;
std::cout << "Step1: " << m.step1() << std::endl;
cv::Mat transposed = m.t(); // Results in a 10x3 matrix