What's the correct way to release cv::Mat?

asked 2016-12-05 08:11:17 -0500

bivalvo gravatar image

Hi there.

I'm not sure if I'm right, please correct me if I'm missing.

A cv::Mat struct contains the field 'refcount', that can point at value 1 or greater. This is the number of references to the cv::Mat on memory from different elements (for example, a cv::vector<cv::mat> element>). If the number is greater than 1, applying the release method onto the cv::Mat, it will decrease the refcount variable (pointing to the last number minus one). If refcount value equals 1 when calling release() method, it will deallocate the image from memory, so this is the unique value that allow us to free memory.

That was the theory. Now, the practice.

My problem comes when I try to do the next:

if(*output_image.refcount > 1)
      *output_image.refcount = 1;

In this code I'm trying to force the cv::Mat for deallocating memory (I doesn't care if there's still any reference to the cv::Mat, because I'm not going to use them). My problem comes when I reach this block with refcount = 0. Apparently there is no problem, but the line

if(*output_image.refcount > 1)

makes a call to release() method. I don't know why exactly, but it does.

Entering on release() method, it tries to deallocate memory (it enters on the first if):

inline void Mat::release()
    if( refcount && CV_XADD(refcount, -1) == 1 )
    data = datastart = dataend = datalimit = 0;
    size.p[0] = 0;
    refcount = 0;

And obviously it throws a memory violation exception. What's the problem on my code? How can I avoid this exception? What means refcount = 0?

I'm checking refcount on my code in order to avoid the exception c0000005 on opencv_core249.dll. This exception appears when a strange value is added to refcount. Or that's what I think, maybe I'm wrong.

Thank you for your help.

My best regards,


edit retag flag offensive close merge delete


can you check, if you accidentally link release build to debug libs (or vice versa ?)

berak gravatar imageberak ( 2016-12-05 09:32:39 -0500 )edit

Checked. They're OK. This is a unusual problem. The application can be running around half an hour before crashing, and then suddenly appears this exception. But there's no more useful info that the exception number and the library when appears.

bivalvo gravatar imagebivalvo ( 2016-12-05 09:42:59 -0500 )edit

"Global Mat objects may not work properly in some cases. To resolve such problems use cv::Ptr<mat> and allocate Mat in the main." It is a comment about a Pull Request may be it can help you.

LBerger gravatar imageLBerger ( 2016-12-05 11:23:40 -0500 )edit

Thank you, LBerger. I will take care about not using global Mat objects. Anyway, what does the c0000005 exception means?

bivalvo gravatar imagebivalvo ( 2016-12-07 02:00:50 -0500 )edit