简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM