Search code examples
javaandroidopencvmat

How to release a Mat that's being returned from a function?


If inside a function I'm creating a new Mat and then I return that Mat, when does that Mat object ever get released?

Say I have this sample function:

    Mat sampleFunction(Mat frameHSV) {
    Mat filtered2 = new Mat();  // create a new Mat object 
    Mat frameRGB = new Mat();    // create a new Mat object
    Imgproc.cvtColor(frameHSV, frameRGB, Imgproc.COLOR_HSV2RGB); // convert to RGB

    Core.subtract(frameRGB, frameHSV, filtered2); // subtract Mats, just a made up operation here
    frameRGB.release(); // release the RGB mat to clear up memory
    return filtered2;
    }

So I'm passing in frameHSV, then I create two Mats inside the sample Function- filtered2 and frameRGB. FrameRGB is released by the end of the function, but Filtered2 is returned and so never released.

How do I release filtered2? Or is the release automatic when I return the Mat?


Solution

  • Silly question, but thank you Selvin for the quick answer.

    As Selvin said, just release the result that's being called

      result = sampleFunction(frameHSV)
      result.release()  // releases the Mat that was returned from the function