I would like to confirm whether cv::Mat::release()
method is similar to free()
in C programming, i.e., its deallocates the Matrix data from the memory.
In particular, I would like to understand the behaviour of this method with respect to memory leaks and make sure there is no leak in may programs.
If you want to release the memory of the Mat variable use release() . Mat m; // initialize m or do some processing m. release(); For a vector of cv::Mat objects you can release the memory of the whole vector with myvector.
The Mat class of OpenCV library is used to store the values of an image. It represents an n-dimensional array and is used to store image data of grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms, etc.
That is, image of type CV_64FC1 is simple grayscale image and has only 1 channel: image[i, j] = 0.5. while image of type CV_64FC3 is colored image with 3 channels: image[i, j] = (0.5, 0.3, 0.7) (in C++ you can check individual pixels as image.at<double>(i, j) ) CV_64F is the same as CV_64FC1 .
CV_8UC3 - 3 channel array with 8 bit unsigned integers. CV_8UC4 - 4 channel array with 8 bit unsigned integers. CV_8UC(n) - n channel array with 8 bit unsigned integers (n can be from 1 to 512) )
If the reference counter is equal to one, then yes, cv::Mat::release()
will decrement it to zero and deallocate the structure (like free
in C).
If the reference counter is greater than one (ie. there's some other object interested in the structure), then cv::Mat::release()
will only decrement the reference counter.
You can increment the reference counter of a cv::Mat
structure (that is, to flag that you are interested in it and you don't want it to be deallocated) by invoking the cv::Mat::addref()
method.
you don't have to manually deallocated cv::Mat objects since it is automatically managed , unless you have initialized the Mat from an Iplimage in this case you should manually deallocate it deallocate().
please refer to this thread .
openCV mixing IplImage with cv::Mat
I was having memory leaks using a code structure like this (OpenCV with C++):
int i;
while(true){
Mat x = imread("C:/pics"+i+".jpg");
//do something with x
}
After 100 or so iterations it always crashed, then i changed the code to this:
int i;
while(true){
Mat x = imread("C:/pics"+i+".jpg");
//do something with x
x.refcount = 0;
x.release();
}
It stopped crashing and did the full iteration. But when setting the refcount manually to 0 you must be really sure that you dont need the object anymore. Thats probably the reason for someone to down-vote my answer, but I solved my problem using this approach. So why shouldn't i share it?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With