PV floripa
PV floripa

Reputation: 31

Release Mat inside std::vector

Using OpenCV 2.2, I am trying to free memory be calling release to a Mat image inside a std::vector, such as:

std::vector < Mat > matVec;

However, it seems like

for (int k = 0; k < matVec.size(); k++)
{

   matVec[k].release();

}

is not releasing any memory (it still compiles, though).

I know there is new memory management in OpenCV 2.2, but I couldn't spot the issue.

A similar example with IplImage* type instead of Mat (using cvReleaseImage() instead of the Mat member function .release()) works just fine.

Any hints?

Upvotes: 3

Views: 3965

Answers (2)

etarion
etarion

Reputation: 17149

.release() should only be called in exceptional circumstances, it's not for everyday use. Just clear the vector:

std::vector<cv::Mat>().swap(matVec);

This calls the destructor of each of the Mats, releasing the memory (if no other cv::Mat points to it - remember cv::Mat is, unlike IplImage, a reference-counted datatype. If it is referenced somewhere else, you have to clear that reference too). If you want to keep the vector, but get rid of the contents, replace the .release() line in your code with:

matVec[k] = cv::Mat();

Upvotes: 7

Jacob
Jacob

Reputation: 34621

The best way would be to activate the destructor of each matVec[k] object. You can do this by letting matVec fall out of scope or by defining matVec as a vector of Mat* and manually allocating and deallocating each object.

This is always safer since OpenCV using a reference counting mechanism for Mat objects and so you don't want to deallocate the data in Mat directly.

Upvotes: 1

Related Questions