Ask Your Question

Memory management using C++ interface

asked 2013-11-04 19:20:43 -0500

Using the Old C interface I can create static IplImages during initialisation, and just reuse the surfaces across all the executions of my code.

However, the (much nicer) C++ interface doesn't provide this capability. You execute an operation, and you get a different surface as the output.

Is this optimised internally in order to reuse surfaces and this way avoid requiring much more memory, plus allocating and freeing memory per execution of the logic?

edit retag flag offensive close merge delete

1 answer

Sort by » oldest newest most voted

answered 2013-11-05 00:28:24 -0500

Vladislav Vinogradov gravatar image

updated 2013-11-05 00:29:56 -0500

Mat::create method checks Mat's size and reallocate data only if requested size or type differs from existed. So, if you call create twice with the same size and type it won't reallocate data. All OpenCV functions works in the same way. You can declare Mat object outside of processing loop and it will be allocated only once, if all input frames have the same size:

VideoCapture cap;
Mat src;
Mat gray;
Mat edges;
    // all following functions will allocate memory only once on first iteration
    cap >> src; 
    cvtColor(src, gray, COLOR_BGR2GRAY);
    Canny(gray, edges, 50, 100);
edit flag offensive delete link more


Very interesting, thanks for the information.

Does the same apply when the Mat is not passed as a parameter, but returned in a function? I.e.:

Mat src; cap >> src;

Mat src_2 = src.mul(src);


Mat t1 = src1 + src2 + 2;

Jose Gómez gravatar imageJose Gómez ( 2013-11-05 17:00:28 -0500 )edit

On response to this follow-up question, I guess the response is no. I.e. the documentation of the method Mat.t() states: "...returns a temporary matrix transposition object...". So, watch out with those functions that create temporary objects...

Jose Gómez gravatar imageJose Gómez ( 2013-11-09 09:12:26 -0500 )edit
Login/Signup to Answer

Question Tools


Asked: 2013-11-04 19:20:43 -0500

Seen: 222 times

Last updated: Nov 05 '13