简体   繁体   English

分配OpenCV Mat对象会导致内存泄漏

[英]Assigning OpenCV Mat object causes a memory leak

I want to assign frame ( Mat object) from function parameter into object variable, as shown in the code below. 我想将功能参数的框架( Mat对象)分配给对象变量,如下面的代码所示。 This function should be called may times (for each frame from the video camera), but this line 此功能应被调用可能的次数(对于摄像机的每一帧),但是这一行

this->nFrame = frame;

causes a memory leak (when commented there is no error!). 导致内存泄漏(在注释时没有错误!)。

NOTE The function setCurrentFrame is called inside JNI function, where this JNI function is called every time I want to process the frame from the video camera. 注意函数setCurrentFrameJNI函数内部被调用,每次我要处理摄像机的帧时都在此JNI函数被调用。

The JNI function is like: JNI函数类似于:

JNIEXPORT jbyteArray JNICALL Java_com_adhamenaya_Native_run(JNIEnv * env,
        jobject obj, jstring faceCascadeFile, jstring noseCascadeFile,
        jstring landmarks, jlong frame) {

    MyClass gsys;
    cv::Mat& inFrame = *(cv::Mat*) frame;
    gsys.setCurrentFrame(inFrame);


    // SOME PROCESSING FOR THE FRAME 


    inFrame.release();
    gsys.release();

    ......
    ......
}

The code for C++ function (setCurrentFrame) C ++函数的代码(setCurrentFrame)

void MyClass::setCurrentFrame(cv::Mat& frame) {
    cv::Size2d imgRes;
    float resRatio;

    if (frame.cols > frame.rows) {
        //landscape
        imgRes.width = 640.0f;
        resRatio = frame.cols / 640.0f;
        imgRes.height = floor(frame.rows / resRatio);
    } else {
        //portrait
        imgRes.height = 640.0f;
        resRatio = frame.rows / 640.0f;
        imgRes.width = floor(frame.cols / resRatio);
    }

    //save scaled height, width for further use
    this->frameWidth = nFrame.cols;
    this->frameHeight = nFrame.rows;

    //set frame and increment frameCount
    this->nFrame = frame;
    this->frameCount++;
}

Kindly, can you help me to solve this problem ? 请您帮我解决这个问题? I tried to release the frame by calling : 我试图通过调用释放框架:

void MyClass::release(void) {
    this->nFrame = cv::Mat();
}

nothing happened, even like this: 什么也没发生,即使这样:

void MyClass::release(void) {
    this->nFrame.release();
}

Still the same error! 还是一样的错误!

Edit 编辑

MyClass.h MyClass.h

class MyClass {

public:
    cv::Mat nFrame;

    MyClass ();
    ~MyClass ();
    void release (void);
    void setCurrentFrame(cv::Mat& frame);

};

In the jni file, the order of releasing frame objects can be erroneus: 在jni文件中,释放框架对象的顺序可能是错误的:

inFrame.release();
gsys.release();

should be 应该

gsys.release();
inFrame.release();

because when you free source frame then frame reference in gsys is invalidated. 因为当您释放源框架时,gsys中的框架引用将无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM