0

我想做以下事情:

  1. 制作我以某种方式检索到的 Cv::mat 的副本
  2. 改造它
  3. 将指向数据的指针连同元信息(大小、格式等)一起返回给调用者
  4. 完成后,释放数据

我正在使用的代码是:

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));

我应该如何实现我的目标?

4

2 回答 2

3

Mat您可以为预分配的内存创建对象。在这种情况下,引用计数将被禁用,并且对象不会在析构函数中释放此内存:

cv::Mat m(...);
Mat img(rows, cols, type, (*result)->pdata);
m.copyTo(img);
...
delete [] (*result)->pdata;
于 2013-07-26T13:31:05.997 回答
2

What you want to do is implemented by the reference counting of OpenCV. It is a much better idea to rely on it rather than using points and allocations yourself.

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

Note that if you want to transform the data without deleting the original content, you do need to copy the data. In such a case:

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

If when the deallocation occurs is important, you can control it with the scope:

cv::Mat m(...)
{
  cv::Mat img = m.clone();
  ...
} // img is automatically deleted here
// img is no longer available
于 2013-07-26T13:37:39.073 回答