【问题标题】:Memory Leak while using CvSeq in cvFindContours在 cvFindContours 中使用 CvSeq 时出现内存泄漏
【发布时间】:2011-12-22 01:12:09
【问题描述】:

我是 OpenCV 的新手,在使用它时遇到了一些问题。

目前我正在研究二进制分区树 (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;
}

有什么办法可以解决这个问题吗?或者有什么替代方法我不需要为每个区域向量创建一个新的内存存储?提前谢谢你

【问题讨论】:

    标签: opencv


    【解决方案1】:

    你应该在循环之前只创建一次内存存储,cvFindContours 可以使用它,在循环之后你应该释放存储:

    void cvReleaseMemStorage(CvMemStorage** storage)
    

    您还可以在此处查看 CvMemStorage 规范: http://opencv.itseez.com/modules/core/doc/dynamic_structures.html?highlight=cvreleasememstorage#CvMemStorage

    编辑:

    您的下一个问题是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.
    

    如您所见,如果您不指定不同的内存存储,它会将序列克隆到与输入相同的内存块中。当您在循环之后释放内存存储时,您还释放了最后一个轮廓,它是您在列表中推送的克隆。

    【讨论】:

    • 我将创建内存存储语句移到了 for 循环之外。它可以工作,但是当我释放内存时,最后一个矢量块的 RegionContour 也被释放了。有什么建议可以避免这种情况吗?
    • 为您的新问题编辑了回复。希望对您有所帮助。
    猜你喜欢
    • 2013-11-09
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    • 1970-01-01
    相关资源
    最近更新 更多