2011-12-22 155 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

相關問題