在使用vector< Mat>时避免内存泄漏. [英] Avoiding memory leaks while using vector<Mat>
问题描述
我正在尝试编写使用opencv Mat对象的代码,它的内容类似于
I am trying to write a code that uses opencv Mat objects it goes something like this
Mat img;
vector<Mat> images;
for (i = 1; i < 5; i++)
{
img.create(h,w,type) // h,w and type are given correctly
// input an image from somewhere to img correctly.
images.push_back(img);
img.release()
}
for (i = 1; i < 5; i++)
images[i].release();
但是我似乎仍然存在内存泄漏,谁能告诉我为什么会这样吗? 我认为,如果mat对象的refcount = 0,则应该自动释放内存
I however still seem to have memory leakage can anyone tell me why it is so? I thought that if the refcount of a mat object = 0 then the memory should be automatically deallocated
推荐答案
您几乎不需要显式调用release
,因为OpenCV Mat
对象会自动处理内部内存.
You rarely need to call release
explicitly, since OpenCV Mat
objects take automatically care of internal memory.
还要注意,Mat
副本只是副本会创建一个指向相同数据的新标头.如果原始的Mat
超出范围,则会留下无效的矩阵.因此,当您将图像推送到向量中时,请使用深层副本(clone()
)以避免它进入向量中的图像变得无效.
Also take care that Mat
copy just copies creates a new header pointing to the same data. If the original Mat
goes out of scope you are left with an invalid matrix. So when you push the image into the vector, use a deep copy (clone()
) to avoid that it the image into the vector becomes invalid.
自从您提到:
我在Mat对象中存储了一个大型3D图像.我正在使用for循环运行它.创建一个称为图像"的2D垫,将切片放入图像中,然后将图像推回矢量图像.释放图像.然后对图像向量进行for循环,一张一张地释放所有矩阵.
I have a large 3D image stored in a Mat object. I am running over it using for loops. creating a 2D mat called "image" putting the slices into image, pushing back image to vector images. releasing the image. And later doing a for loop on the images vector releasing all the matrices one by one.
您可以使用以下代码将所有切片存储到向量中.要释放矢量中的图像,只需clear
矢量.
You can store all slices into the vector with the following code. To release the images in the vector, just clear
the vector.
#include <opencv2/opencv.hpp>
#include <vector>
using namespace cv;
using namespace std;
int main()
{
// Init the multidimensional image
int sizes[] = { 10, 7, 5 };
Mat data(3, sizes, CV_32F);
randu(data, Scalar(0, 0, 0), Scalar(1,1,1));
// Put slices into images
vector<Mat> images;
for (int z = 0; z < data.size[2]; ++z)
{
// Create the slice
Range ranges[] = { Range::all(), Range::all(), Range(z, z + 1) };
Mat slice(data(ranges).clone()); // with clone slice is continuous, but still 3d
Mat slice2d(2, &data.size[0], data.type(), slice.data); // make the slice a 2d image
// Clone the slice into the vector, or it becomes invalid when slice goes of of scope.
images.push_back(slice2d.clone());
}
// You can deallocate the multidimensional matrix now, if needed
data.release();
// Work with slices....
// Release the vector of slices
images.clear();
return 0;
}
这篇关于在使用vector< Mat>时避免内存泄漏.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!