2011-12-22 156 views
2

我是OpenCV的新手,我在使用它时遇到了一些问题。在cvFindContours中使用CvSeq时发生内存泄漏

目前我正在研究二进制分区树(BPT)算法。基本上我需要将图像分成许多区域,并基于某些参数。 2个地区将合并并形成1个新地区,由这2个地区组成。

我设法通过使用cvWatershed得到初始区域。我还创建了一个矢量来存储这些区域,每个区域位于1个矢量块中。但是,当我尝试将轮廓信息移入矢量时,出现内存泄漏。它说,内存泄漏。

for (int h = 0; h <compCount; h++) // compCount - Amount of regions found through cvWaterShed 
{ 
    cvZero(WSRegion);    // clears out an image, used for painting 
    Region.push_back(EmptyNode); // create an empty vector slot 
    CvScalar RegionColor = colorTab[h]; // the color of the region in watershed 

    for (int i = 0; i <WSOut->height; i++) 
    { 
     for (int j = 0; j <WSOut->width; j++) 
     { 
      CvScalar s = cvGet2D(WSOut, i, j); // get pixel color in watershed image 
      if (s.val[0] == RegionColor.val[0] && s.val[1] == RegionColor.val[1] && s.val[2] == RegionColor.val[2]) 
      { 
       cvSet2D(WSRegion, i, j, cvScalarAll(255)); // paint the pixel to white if it has the same color with the region[h] 

      } 
     } 
    } 

    MemStorage = cvCreateMemStorage(); // create memory storage 
    cvFindContours(WSRegion, MemStorage, &contours, sizeof(CvContour), CV_RETR_LIST); 
    Region[h].RegionContour = cvCloneSeq(contours); // clone and store in vector Region[h] 
    Region[h].RegionContour->h_next = NULL; 
} 

难道我能解决这个问题吗?或者有什么替代方案,我不需要为每个区域矢量创建新的内存存储空间?预先感谢您

回答

2

您应该在循环之前创建内存存储器,cvFindContours可以使用该循环,并且在循环之后你应该释放与存储:

void cvReleaseMemStorage(CvMemStorage** storage) 

您还可以看看这里的CvMemStorage规格: http://opencv.itseez.com/modules/core/doc/dynamic_structures.html?highlight=cvreleasememstorage#CvMemStorage

编辑:

你的下一个p与cvCloneSeq()。这里有一些规范它:

CvSeq* cvCloneSeq(const CvSeq* seq, CvMemStorage* storage=NULL) 
Parameters: 

seq – Sequence 
storage – The destination storage block to hold the new sequence header and the copied data, if any. If it is NULL, the function uses the storage block containing the input sequence. 

正如你可以看到,如果你不指定一个不同的存储器,它会在相同的内存块作为输入克隆序列。当你在循环后释放内存时,你也释放最后一个轮廓,并且它是你在列表中推送的克隆。

+0

我将创建内存存储语句移至for循环之外。 它可以工作,但是当我释放内存时,最后一个矢量块的RegionContour也被释放了。任何建议,以避免这一点? – 2011-12-26 05:07:00

+0

针对您的新问题编辑回复。希望能帮助到你。 – Adrian 2012-01-03 07:40:33

相关问题