Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV Matrix memory release after imread command

I have a for loop in which I create a local cv::Mat object to store an image. The code looks like this:

for (int iter = 0; iter < totalNumberOfIterations; iter++)
{
    cv::Mat I = cv::imread(argv[1], 0);
    std::cout << "Reference count I: " << *I.refcount << std::endl;
    I.release();
}

During the first iteration of the loop, I found that memory is allocated for the variable "I" and it is deallocated when I call I.release(). During subsequent iterations, memory is not deallocated, the RAM consumption for my program remains constant. It seems as if OpenCV reserves memory for variable "I" for optimization purposes. Is this true?

The reference count for the variable "I" (*I.refcount) remains as 1 through all iterations of the for loop.

I am using OpenCV 2.4.4 and I am compiling my code using gcc 4.6.4. To check memory consumption, I was using the command "top" in my Ubuntu 13.04 machine.

EDIT: When I do not force OpenCV to read grayscale image, I notice that memory is being deallocated for variable "I". (Note second parameter is set to "1" in the imread command).

cv::Mat I = cv::imread(argv[1], 1);
like image 213
Kaushik Pavani Avatar asked Sep 02 '13 03:09

Kaushik Pavani


1 Answers

Have you tried declaring the Mat before the for-loop, overwriting it each iteration, and then releasing it?

I.E.

cv::Mat I;
for (int iter = 0; iter < totalNumberOfIterations; iter++)
{
    I = cv::imread(argv[1], 0);
    std::cout << "Reference count I: " << *I.refcount << std::endl;
}
I.release();

Granted, this doesn't solve the underlying problem of it only releasing once, but it would have the same effect, I believe. Or is there a reason you don't want to do it that way?

like image 158
Alexander Avatar answered Oct 10 '22 01:10

Alexander