2013-04-08 145 views
4

我想确认在C编程中,cv::Mat::release()方法是否类似于free(),即它从存储器中取消分配Matrix数据。cv :: Mat的发布方法

特别是,我想了解这种方法在内存泄漏方面的行为,并确保可能程序中没有泄漏。

+0

封装你的代码,而内(真){//循环},并让它运行。与此同时,使用任务管理器监视你的记忆,以推断你的记忆。 – William 2013-04-08 09:16:26

+0

有特定的工具来衡量内存泄漏和其他编程错误(使用未初始化的变量等)。看看«valgrind»。 – 2013-04-08 13:35:14

回答

6

如果参考计数器等于1,那么是的,cv::Mat::release()会将其递减至零并释放结构(如C中的free)。

如果参考计数器大于1(即存在一些对该结构感兴趣的其他物体),则cv::Mat::release()将只有递减参考计数器。

通过调用cv::Mat::addref()方法,您可以递增cv::Mat结构的引用计数器(即标记您对其感兴趣并且不希望它被解除分配)。

+0

我有一个cv :: Mat v,并且这是在一个循环内的v.create(),并且v的大小对于不同的迭代是不同的。然后为了下一次迭代,我喜欢删除旧的创建新的。我可以使用release()或deallocate()吗? – Bryanyan 2013-04-08 13:07:51

4

你不必手动释放cv :: Mat对象,因为它是自动管理的,除非你在这种情况下从Iplimage初始化了Mat,所以你应该手动释放它的deallocate()。

请参阅此主题。

openCV mixing IplImage with cv::Mat

3

我在使用的码结构是这样的(OpenCV中与C++)内存泄漏:

int i; 
while(true){ 
    Mat x = imread("C:/pics"+i+".jpg"); 
    //do something with x 
} 

后100次左右的迭代它总是坠毁,然后我改变了代码以这样的:

int i; 
while(true){ 
    Mat x = imread("C:/pics"+i+".jpg"); 
    //do something with x 
    x.refcount = 0; 
    x.release(); 
} 

它停止崩溃并做了完整的迭代。但是,当手动将refcount设置为0时,您必须确定不再需要该对象。这可能是某人投票回答我的答案的原因,但我使用这种方法解决了我的问题。那么为什么我不应该分享它呢?

+0

你能否澄清你的倒票的原因?是否因为你错过了我的观点? – kiltek 2014-04-13 18:33:43

+2

是'refcount'公共领域?我找不到它... – zhangxaochen 2015-07-26 16:17:17

0

下面的程序片断测试垫的行为::释放() (改编自opencv-org-answer

using namespace std; 
using namespace cv; 

int main(int argc, char **argv) { 
    cout << "test_mat_release.cpp" << endl; 

    { 
     //memory is released 
     const char *pzInputImg = "data/em_sample.png"; 

     Mat img; 
     img = imread(pzInputImg); 
     assert(img.data); 
     img.release(); 
     assert(!img.data); 
    } 
    { 
     //memory is released 
     Mat img(100, 100, CV_32FC1); 
     assert(img.data); 
     img.release(); 
     assert(!img.data); 
    } 

    { 
     //Since Mat does not owns data , data is not released 
     //you have to explicitly release data 
     int cols=17; 
     int rows=15; 
     unsigned char * data = new unsigned char[rows*cols*3]; 
     Mat img(rows, cols, CV_8UC3, data); 
     assert(img.data); 
     img.release(); 
     assert(!img.data); 
     delete [] data; 
    } 



    Mat imgRef; 
    { 
     //memory is not released 
     //since there img.data is now shared with imgRef 
     Mat img(100, 100, CV_32FC1); 
     imgRef=img; 
     assert(img.data); 
     assert(img.data == imgRef.data); 
     img.release(); 
     assert(img.empty()); 
     assert(!img.data); 
     //img.data is NULL, but imgRef.data is not NULL, so data is not de-allocated 
     assert(!imgRef.empty()); 
     assert(imgRef.data); 
    } 
    return 0; 
} 
+0

会超级好,如果在最后一个例子中你展示了一种释放内存的方式,我想通过释放imgRef然后img ...? – VirgileD 2017-03-20 07:49:33