0

I used OpenCV 2.4 with Qt 5.7 for a while and allocating those arrays dynamically was a quite simple task:

cv::Mat vector[n] = cv::Mat::zeros(h, w, CV_8UC3);

allocated dynamically a vector called vector with n cv::Mat elements starting them as zero matrices. I could easily access any cv::Mat in the vector by vector[k], giving a position k. Whenever they were not needed, C++ automatically deleted them and released their memory.

With OpenCV 4.0.0 and Qt 5.9, if I try to compile this code, I get array must be initialized with a brace-enclosed initializer, and I figured out (C++ error: "Array must be initialized with a brace enclosed initializer") that I have to start the vector using braces like cv::Mat vector[n] = {cv::Mat::zeros(h, w, CV_8UC3)}; in order to compile. Probably, a new C++ standard (maybe C++ 11 instead of C++ 99?). However, it does not work, because the vector is no longer dynamically allocated, but rather statically. So, the resulting length of vector is the size I pre declared as the int n, equal to 1, in my code. But it changes to some other value in runtime.

An option that works for declaring the vector dynamically was:

std::vector <cv::Mat> vect(n, cv::Mat::zeros(h, w, CV_8UC3))

where int h and int w are the matrix dimensions. But this is actually only creating instances, pointers which are pointing to the same matrix in the memory. So, if I change one, all positions vect[k] change.

I found on OpenCV - Creating an Array of Mat Objects and I could allocate a vector dynamically creating copies of the matrices. I wrote:

cv::Mat mat_zeros = cv::Mat::zeros(h, w, CV_8UC3);
std::vector <cv::Mat> vect;
for (int k = 0; k < tracks_count; k++)
{
    vect.push_back(mat_zeros.clone());
}

It seemed perfect, I got a vect of different matrices cv::Mat. But now I notice in runtime that the used RAM memory gets higher until I get stack overflow. After researching around I tried to call img_buffer_sep_tracks[k].release(); or img_buffer_sep_tracks[k].~Mat();, (https://docs.opencv.org/3.1.0/d3/d63/classcv_1_1Mat.html#ae48d4913285518e2c21a3457017e716e , http://answers.opencv.org/question/14285/how-to-free-memory-through-cvmat/) after using it, to call vect.clear(); after using the whole vector, tried vect.clear(); and vect.swap(std::vector<cv::Mat>(vect)); together ("Right" way to deallocate an std::vector object) with no success. Still getting RAM overflow.

Why did C++ or OpenCV get worse in the newer versions? And how to free this memory, then?

  • 1
    push_back and clear should work if there are no other usages of the cv::Mat data left. – Micka Aug 11 '18 at 05:31
  • Problem is quite likely in your code, please provide a [mcve] that reproduces it. | Given that OpenCV 4.0.0 has not been released yet, you're probably using some random revision of the in-development master branch. Unless working on OpenCV itself, it may be wise to use a stable release. – Dan Mašek Aug 11 '18 at 13:09

0 Answers0