Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

free cv::Mat without releasing memory

Tags:

c++

opencv

I pass the Mat data (not a cv::Mat object) to a function, And make this function the new owner of this data. however, I need a method to free the original object, without freeing the data buffer it points to.

I know that this will happen to cv::Mat that were created from external data, I just need to use this feature for general cv::Mat.

Is there a way to do this?

like image 766
Ophir Yoktan Avatar asked Dec 09 '22 05:12

Ophir Yoktan


2 Answers

You can use addref() method but you will have a memory leak.

Actually it is not a good idea to detach data from Mat:

  • It was not designed for that;
  • You can not guarantee that pointer obtained from general cv::Mat points to the beginning of allocated memory block;
  • Most probably you will be unable to release that memory by yourself because cv::Mat may use own memory allocation routines (there are a lot of reasons to do that, for example alignment).
  • Even if you find a way to solve all the problems with data pointer, you still can not avoid memory leak for Mat reference counter.

So there are only two ways that Mat is guaranteed to support:

  • Provide your pointer on Mat creation;
  • Copy data to you buffer.

Any other way can be broken in future versions even if it works in current.

like image 111
Andrey Kamaev Avatar answered Dec 11 '22 18:12

Andrey Kamaev


You can capture the Mat with a lambda, and you can use this lambda as a deleter to extend and bound its life to a shared_ptr/unique_ptr.

Mat matrix;
...
std::shared_ptr<uchar*> ptr(matrix.ptr(),[matrix](uchar*){});

Its useful when you don't want to use the opencv on your public interface, and you can't provide your pointer on Mat creation or don't want to copy data to your buffer.

like image 38
soyer Avatar answered Dec 11 '22 19:12

soyer