OpenCV cv::Mat causing potential memory leak with std::vector

淺唱寂寞╮ 提交于 2019-12-08 05:00:26

问题


As it stands right now im trying to save an entire list of images in the form of cv::Mats inside of a vector for later processing. Right now I have something that looks like this:

do
{
 image = readimage();
 cv::Mat mat = cv::Mat((length, width, CV_8UC4, image));
 cv::Mat temp = mat.clone();
 saved_images.push_back();

 mat.release();
 temp.release();
 freeimagememory(image);
}
while(hasimage);

This actually works. For exceptionally small lists of images it will store them just fine. However as I get to large amounts of images the program consistently crashes saying Abort() was called, and upon inspection it says it's throwing a cv::exception.

Does anyone know why this is? I've thought about changing the vector to a vector of pointers to cv::Mats in order to save space (cloning seems expensive) but I'm not sure how well that will work.

Can anyone help?

EDIT1: The exact error being thrown is failed to allocated X bytes. I assume this is because it's eating up all of the available memory somehow (even though I'm sitting on 8 gigs of memory and definitely have memory free).

EDIT2:

The below code also seems to work.

std::vector<cv::Mat*> ptrvec;
do{

 image.readimage();
 ptrvec.push_back(new cv::Mat((length, width, CV_8UC4, image)));
 freeimagememory(image);
}
while(hasimage);

This one doesn't have a problem with memory (I can push all the images I want to it) but I get an access violation when I try to do

cv::imshow("Test Window", *ptrvec[0]);

EDIT3:

Is there a chance I'm hitting the upper limit of 32 bit? I'm more than capable of recompiling this into a 64 bit project.


回答1:


You may be running out of memory when you store 3000 color images 800 x 600 in a vector. Storing Mat pointers in memory will not solve your problem, since the data is still allocated in RAM.

Check whether there is enough memory in your system to store all the images. If not you can upload images in batches, for example, process the first 500 images, then process the next 500 images, etc.

In your program you allocate the vector on the stack. Allocating on the heap is recommended when you need a large block of memory (your case). So can try to allocate the vector on the heap instead (provided that you have enough memory to store the vector). See, stack vs heap, or this cpp-tutorial for more information.



来源:https://stackoverflow.com/questions/18189934/opencv-cvmat-causing-potential-memory-leak-with-stdvector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!