Post date: May 06, 2017 3:3:54 PM
To free memory that has been new'ed to a Mat say
cv::Mat* mat = new cv::Mat.......
the idea is to use the release() method. Like si
mat->release();
Only thing is that release() only free's memory when the refcount (number of references to the mat) is 1 i.e. at 0, the memory allocated to the Mat is freed. The refcount of a cv::Mat is hidden in its u object, hence
mat->u->refcount();
Now I am sure there are many ways to create or copy a matrix but if you intend to minimize the refcount so you at least have a gut feeling when you can release() the memory, then the cleanest way I've found so far is you must do this first
cv::Mat* mat = new cv::Mat(prevmat.rows, prevmat.cols, prevmat.type());
then you can do
*mat = prevmat.clone();
or
prevmat.copyTo(*mat);
Using the copy constructor increases the refcount of both prevmat and mat
cv::Mat* mat = new cv::Mat(prevmat);
so you may not be freeing the memory when you put a release() and hence a memory leak occurs.