OpenCV uses automatic memory management with reference counting for Mat objects. This eliminates most manual memory management while providing efficiency through shallow copying.
Reference counter: Tracks how many Mat objects share the data
Mat A(100, 100, CV_8UC1); // Allocates data, refcount = 1Mat B = A; // Shares data, refcount = 2Mat C = A; // Shares data, refcount = 3// When C goes out of scope, refcount = 2// When B goes out of scope, refcount = 1 // When A goes out of scope, refcount = 0, data freed
// Efficient: No copy due to return value optimizationMat createImage() { Mat img(480, 640, CV_8UC3); // ... initialize return img; // No actual copy}Mat result = createImage(); // Moves or shallow copy
// User manages memoryunsigned char* data = new unsigned char[640*480*3];// OpenCV wraps it (no copy, no ownership)Mat img(480, 640, CV_8UC3, data);// Process with OpenCVcvtColor(img, gray, COLOR_BGR2GRAY);// User must freedelete[] data;
Mat A(1000, 1000, CV_8UC3);// Manually release (rarely needed)A.release(); // Decrements refcount, frees if zero// Check if emptyif(A.empty()) { // A has no data}
// Check if continuous (no padding between rows)if(img.isContinuous()) { // Can treat as 1D array size_t total = img.total() * img.elemSize(); processData(img.ptr<uchar>(), total);}
Mat img = imread("image.jpg"); // ContinuousMat roi = img(Rect(10, 10, 100, 100)); // NOT continuous// Make continuousMat roiCopy = roi.clone(); // Now continuous
Mat getROI() { Mat img(480, 640, CV_8UC3); return img(Rect(0, 0, 100, 100)); // Dangerous!} // img destroyed, ROI points to freed memoryMat roi = getROI(); // roi is invalid!
Fix: Return a clone or the full image.
Shared Data Modification
Mat A = imread("img.jpg");Mat B = A; // Shares dataGaussianBlur(B, B, Size(5,5), 0); // Modifies A too!
Fix: Use B = A.clone() if independent data needed.