我想做以下事情:
我使用的代码是:
cv::Mat m(...); //here is source image
cv::Mat *img = new cv::Mat(m.clone());// copy the data
//do transformations
(*result)->pdata = img->data; // pointer to data gois to out parameter
img->addref(); //to prevent freeing the image data after tempo
delete img; //dispose of temporary object
...
delete [] outparam->pdata; //result == &outparam; free data after use
但是,执行时,此代码会在以下位置生成断言失败:
_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
我应该如何实现目标?
答案 0 :(得分:3)
您可以为预先分配的内存创建Mat
个对象。在这种情况下,将禁用引用计数,并且对象不会在析构函数中释放此内存:
cv::Mat m(...);
Mat img(rows, cols, type, (*result)->pdata);
m.copyTo(img);
...
delete [] (*result)->pdata;
答案 1 :(得分:2)
您想要做的是通过OpenCV的引用计数来实现。依靠它而不是自己使用积分和分配是一个更好的主意。
cv::Mat m(...);
cv::Mat img = m; // this does not copy data, all the changes in img will be in m as well
// ... use img
// no delete necessary
请注意,如果要在不删除原始内容的情况下转换数据,则需要复制数据。在这种情况下:
cv::Mat m(...)
cv::Mat img = m.clone(); // this copies data, m and img can be used as two different Mats
// ... use img
// no delete necessary, img will be automatically deallocated
如果发生重新分配很重要,您可以使用范围控制它:
cv::Mat m(...)
{
cv::Mat img = m.clone();
...
} // img is automatically deleted here
// img is no longer available