is there a way of creating a cv::Mat from external data pointer, but making that object responsible for deleting the data?
i.e., I have a function creating a cv::Mat from a void * pointer,
cv::Mat createMat() {
void *data = (...);
cv::Mat data_m(rows, cols, CV_8UC1, data);
return data_m;
}
and I want that my returned cv::Mat to be responsible for releasing the data. How can I do this?
解决方案
All OpenCV functions expect cv::Mat::data to be a void*, so you cannot change that. If you inherit from cv::Mat and write your own destructor, you become incompatible from OpenCV because they do not return your derived type.
I would suggest to contain your cv::Mat as an attribute of a class, and keep a std::shared_ptr or other smart pointer to manage the lifetime of the underlying void*.
Just initialize the OpenCV matrix with the raw pointer from the shared pointer with std::shared_ptr::get()
http://www.cplusplus.com/reference/memory/shared_ptr/get/ and make sure they have the same lifetime, i.e. in the same class.