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

时间:2015-10-18 19:10:37

标签: android c++ opencv memory-leaks android-ndk

我想将函数参数中的frame(<?php const _JEXEC = 1; if (file_exists(dirname(__DIR__) . '/defines.php')) { require_once dirname(__DIR__) . '/defines.php'; } if (!defined('_JDEFINES')) { define('JPATH_BASE', dirname(__DIR__)); require_once JPATH_BASE . '/includes/defines.php'; } require_once JPATH_LIBRARIES . '/import.legacy.php'; require_once JPATH_LIBRARIES . '/cms.php'; require_once JPATH_CONFIGURATION . '/configuration.php'; class AddArticle extends JApplicationCli { public function doExecute() { $count = 10; while ($count > 0) { $count--; $jarticle = new stdClass(); $jarticle->title = 'New article added programmatically' . rand(); $jarticle->introtext = '<p>A programatically created article</p>'; $table = JTable::getInstance('content', 'JTable'); $data = (array)$jarticle; // Bind data if (!$table->bind($data)) { die('bind error'); return false; } // Check the data. if (!$table->check()) { die('check error'); return false; } // Store the data. if (!$table->store()) { die('store error'); return false; } } } } JApplicationCli::getInstance('AddArticle')->execute(); object)分配给对象变量,如下面的代码所示。应该可以调用此函数次数(对于来自摄像机的每个帧),但是此行

Mat

导致内存泄漏(评论时没有错误!)。

注意 函数this->nFrame = frame; setCurrentFrame函数内部调用,每次我想从摄像机处理帧时调用此JNI函数。

JNI功能如下:

JNI

C ++函数的代码(setCurrentFrame)

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();

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

请帮助我解决这个问题?我试着通过调用:

释放帧
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++;
}

什么都没发生,就像这样:

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

仍然是同样的错误!

修改

MyClass.h

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

1 个答案:

答案 0 :(得分:0)

在jni文件中,释放帧对象的顺序可能是错误的:

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

应该是

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

因为当你释放源帧时,gsys中的帧引用无效。