Mat and imread memory management
Hey there,
I am looking for the "best practice" to save a lot of images of type cv::Mat in the cache. Is it okay if I just push_back them in a vector< Mat > and get back as soon as I need them? Reason for my question is, that I tried to load ~150 images (300 Mb) with imread and after 100 the system starts to slow down extremely. After having a look at the monitoring I noticed that the RAM of 5 GB is getting trashed until it breaks down. Code snippet for my image reading below:
cout << "Start reading image inputs..." << endl;
vector<Mat> imagesArg;
for (int i = 1; i < argc; i++) {
Mat img = imread(argv[i]);
if (argc == 1){
cout << "Not enough image data." << endl;
}
if (img.empty()) {
cout << "Can't read image " << argv[i] << "." << endl;
return 1;
}
imagesArg.push_back(img);
img.release();
}
cout << "Finished reading " << imagesArg.size() << " images." << endl;
Thanks in advance for an answer!
Lax
have you tried to declare
Mat img
outside the for loop?When you do
imagesArg.push_back(img)
you push back a pointer to the local variableMat img
which soon goes out of scope. If you want to save the data you shouldimagesArg.push_back(img.clone())
instead. Also becauseimg
already goes out of scope on the next iteration you don't have to release it@bjorn89: Doesn't change anything :< @strann: But my problem is not that my data goes out of scope, my cache is flooded until the system stops working? Plus I don't think you are right. It may be a push_back of a local variable, but cv::Mat is smart enough to realize it can be called by imagesArg.
300mb on Disc can easily expand to several GB of images in memory
@berak: Hm okay, but do 100 images sound too much for a RAM to handle for you (4000 x 3000 px)? And 300 mb expanding to 3 GB?
do the maths:
3.6 gb. enough, to get your os into trouble. (how much ram is there ? your webbrowser will already eat half of it..)
Point for you. Sometimes I lack the basic skills. :D I got 5.8 gb of rams following the system monitor. The 3.6 Gb would be enough to kill it.