How do I pass ownership of pixel data to cv::Mat
I am creating a cv::Mat passing in pixel data that I have allocated externally.
cv::Mat transformedResult(vImageResult.height,
vImageResult.width,
CV_8UC1,
vImageResult.data);
I would like the cv::Mat to take ownership of the bytes (i.e. create a refCount and free the bytes when it reaches zero) . However the documentation says
Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it.
- If I free the underlying
vImageResult.data
immediately, the I will get a bad access crash somewhere down the line. - If I don't free the underlying
vImageResult.data
then the data will leek.
Is there a way to pass ownership?
cv::Mat transformedResult = Mat(vImageResult.height, vImageResult.width, CV_8UC1, vImageResult.data).clone(); // yea, expensive copy, but at least you can release vImageResult.data without further worries, and transformedResult is refcounted now
Good suggestion - that would do the job. However, the reason why I have external data is because I want to see if Apple's Accelerate framework speeds up a affine transform. So Ideally, I would like to avoid the copy.
Ah I think I am being an Idiot... Instead of allocating the buffer myself, then doing the external framework operation then passing it in to the Mat constructor I can get the Mat constructor to allocate the buffer for me then pass that to the external framework. That way the buffer will be memory managed by the Mat
you're not an idiot. ...
Thanks :) I was just frustrated since I asked the question then figured it out. Ill post the code once I confirm it works.
it's called : rubber duck debugging ;)