Home > Software engineering >  What happens to submats if the original mat is released
What happens to submats if the original mat is released

Time:11-28

In OpenCV, I am getting an image and crop some ROIs out (using mat.submat(...)). I would like to avoid cloning the submats to save time and memory, but I am afraid that the image might be released before the rois are. Given that submat returns a Mat that uses the original Mat as its backing storage, my question is: What happens to sub-mats after their parent mat has been released? Is it safe to use the submats afterwards?

Here's the code to explain the question:

// Some big image that I get from somewhere
Mat image = Mat.zeros(1080, 1920, CvType.CV_8UC3);

Mat roi = image.submat(10, 20, 10, 20);

image.release();

// Still safe to use roi? 
Mat blurredRoi = new Mat();
Imgproc.blur(roi, blurredRoi, new Size(5, 5));

CodePudding user response:

OpenCV uses reference counting.

submat adds another reference to the data memory.

.release() does not deallocate the memory, unless the last reference was removed/decremented.

  • Related