Will cv::Mat reuse memory if it was declared inside a loop?

asked 2015-05-27 17:45:11 -0500

dkprog gravatar image

I'm moving from legacy IplImage * to new cv::Mat.

If I declare a Mat inside camera's loop, just to get a copy of current frame, will it alloc and release the memory storage at every run?


edit retag flag offensive close merge delete



no, it won't.

if you assign a cv::Mat to another like Mat a=...; Mat b=a; this will do a 'shallow' copy, both Mats will share the same data

so, even if you create a new Mat in the webcam loop, capture.read(frame) will just link it to whatever data is underneath.

berak gravatar imageberak ( 2015-05-28 01:03:38 -0500 )edit

And if I need some sort of temporary image, just to run a threshold or something like that, if I declare it inside the loop, will it be created and destroyed every time?

dkprog gravatar imagedkprog ( 2015-05-28 12:12:35 -0500 )edit

yes. different story. if you really care about that, declare them outside the loop, so they will get allocaed only once (unless you change the cam resolution, or similar)

but again, cv::Mat is a smartpointer, you do not leak any memory this way, we're only talking about allocation/deallocation costs, right ? (usually, you should not need to worry about this too much, unless you're on a really small box, like a raspi or smartphone)

berak gravatar imageberak ( 2015-05-28 12:28:03 -0500 )edit

I care about allocation/deallocation costs. When working on Windows, this kind of "ask OS for permission to get some memory" always slows down the algorithm's process, mainly when the code should run above than 100 fps. I've disliked it when Mat has become standard on 2.x. However, I'm still a C programmer who doesn't like to lost control to objects :)

dkprog gravatar imagedkprog ( 2015-05-28 13:06:16 -0500 )edit