Ask Your Question
0

Doing a deep copy causes memory leak

asked 2018-03-17 14:31:29 -0600

Vusa360 gravatar image

I am writing an android app and I am using method Mat.clone() to do a deep clone of one mat to another.

The issue is this is causing a memory leak in my app that automatically closes the app after 10 or so seconds.

I have tried numerous ways to solve the issue, however, some ways have no effect and others just crash the program.

My code for the OpenCV CameraBridgeViewBase.CvCameraViewListener2, where the memory leak is happening, looks like this.

mOpenCvCameraView.setCvCameraViewListener(new CameraBridgeViewBase.CvCameraViewListener2() {
    Mat mRgba;
    Mat mask;
    @Override
    public void onCameraViewStarted(int width, int height) { }

    @Override
    public void onCameraViewStopped() { }

    @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
        mRgba = inputFrame.rgba();

        //Way One
        mask = new Mat();
        mRgba.copyTo(mask); //Causes massive memory leak

        //Way 2
        //mask = mRgba.clone(); //Same issue

        //Way 3
        mask = mRgba; //Solves initial issue but causes crash when later trying to modify mRgba

        //Way 4 - Same issue as way 3
        //mRgba = inputFrame.rgba();
        //mask = inputFrame.rgba();


        mRgba.release(); //No Effect
        //mask.release(); //Few seconds of black then crash
        System.gc(); //No Effect
        return mask;
    }
});

Is there a way to get round this issue?


For those after extra information. I have uploaded a copy of the LogCat information to Paste Bin

An image of the device profiler can be seen below

Device profiler

The repository storing the source code can be found here

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2018-03-18 01:51:39 -0600

berak gravatar image

updated 2018-03-18 02:25:38 -0600

  • mask = new Mat() should go into some initalization routine (like onCameraViewStarted, done once only)
  • mRgba.release(); that's the wrong one.
  • //mask.release(); well, if you return it, you must not release it before.

again, the problem is the reocurring new there. move all your temporary allocations to onCameraViewStarted(), and release all of them in onCameraViewStopped()

edit flag offensive delete link more

Comments

1

Thanks. Strangely, whilst declaring mask = new Mat() in onCameraViewStarted() worked for copyTo() it did not work for clone()

Vusa360 gravatar imageVusa360 ( 2018-03-18 02:18:04 -0600 )edit
1

apologies, you're right about clone(). it reassigns the Mat pointer, so it would count as another new

berak gravatar imageberak ( 2018-03-18 02:26:53 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2018-03-17 14:31:29 -0600

Seen: 2,397 times

Last updated: Mar 18 '18