Srv19
Srv19

Reputation: 3618

How to get image data from OpenCV matrix without extra allocation?

I want to do the following:

  1. Make a copy of Cv::mat i retrieved somehow
  2. Transform it
  3. Return pointer to data to caller along with meta information (size, format, etc)
  4. When i am done, free the data

The code i am using is:

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

However, when executed, this code produces an assertion failure on:

_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));

How should i achieve my goal?

Upvotes: 0

Views: 3721

Answers (2)

ChronoTrigger
ChronoTrigger

Reputation: 8617

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

Upvotes: 2

vinograd47
vinograd47

Reputation: 6420

You can create Mat object for pre-allocated memory. In such case reference counting will be disabled and object won't free this memory in destructor:

cv::Mat m(...);
Mat img(rows, cols, type, (*result)->pdata);
m.copyTo(img);
...
delete [] (*result)->pdata;

Upvotes: 3

Related Questions