How do I pass ownership of pixel data to cv::Mat

asked 2014-03-19 10:59:24 -0500

_Robert gravatar image

updated 2014-03-19 11:12:21 -0500

berak gravatar image

I am creating a cv::Mat passing in pixel data that I have allocated externally.

cv::Mat transformedResult(vImageResult.height,

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 immediately, the I will get a bad access crash somewhere down the line.
  • If I don't free the underlying then the data will leek.

Is there a way to pass ownership?

edit retag flag offensive close merge delete



cv::Mat transformedResult = Mat(vImageResult.height, vImageResult.width, CV_8UC1,; // yea, expensive copy, but at least you can release without further worries, and transformedResult is refcounted now

berak gravatar imageberak ( 2014-03-19 11:15:10 -0500 )edit

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.

_Robert gravatar image_Robert ( 2014-03-19 11:19:23 -0500 )edit

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

_Robert gravatar image_Robert ( 2014-03-19 11:30:37 -0500 )edit

you're not an idiot. ...

berak gravatar imageberak ( 2014-03-19 11:37:13 -0500 )edit

Thanks :) I was just frustrated since I asked the question then figured it out. Ill post the code once I confirm it works.

_Robert gravatar image_Robert ( 2014-03-19 12:29:07 -0500 )edit

it's called : rubber duck debugging ;)

berak gravatar imageberak ( 2014-03-19 12:40:05 -0500 )edit