OpenCV中的cv::Mat释放方法

5
当使用 openCV 的 cv::Mat 时, http://docs.opencv.org/modules/core/doc/basic_structures.html 我知道会使用某种智能指针。 我的问题是,为了进行一些内存优化,
我应该调用 cv::Mat release() 来释放未使用的矩阵吗?
还是应该相信编译器会自动处理? 例如,考虑以下代码:
cv::Mat filterContours = cv::Mat::zeros(bwImg.size(),CV_8UC3);  
bwImg.release();
for (int i = 0; i < goodContours.size(); i++)
{
    cv::RNG rng(12345);
    cv::Scalar color = cv::Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
    cv::drawContours(filterContours,goodContours,i,color,CV_FILLED);        
}

/*% Fill any holes in the objects
bwImgLabeled = imfill(bwImgLabeled,'holes');*/


imageData = filterContours;
filterContours.release(); //should I call this line or not ?

2
当矩阵超出范围时,它将被释放(除非该矩阵的数据有不同的引用)。 - Micka
@Micka 如果这是一个计算时间很长的函数,释放会有帮助吗? - Gilad
1
它将为您释放一些内存,这可能会或可能不会帮助您。 - Micka
使用RAII - 这是C++最好的东西。 - Boyko Perfanov
1个回答

3
cv::release()函数释放内存,在Mat实例的作用域结束时,析构函数会自动处理。因此,在您发布的代码片段中,无需显式调用它。需要使用它的一个示例是如果矩阵的大小在同一循环中的不同迭代中可能会变化。
using namespace cv;
int i = 0;
Mat myMat;
while(i++ < relevantCounter )
{
    myMat.create(sizeForThisIteration, CV_8UC1);

    //Do some stuff where the size of Mat can vary in different iterations\\

    mymat.release();
}

在这里,使用cv::release()可以避免编译器在每次循环中创建指针的开销。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接