Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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. But 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.

The JNI function is like:

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;




The code for C++ function (setCurrentFrame)

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

    if (frame.cols > frame.rows) {
        imgRes.width = 640.0f;
        resRatio = frame.cols / 640.0f;
        imgRes.height = floor(frame.rows / resRatio);
    } else {
        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;

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) {

Still the same error!