In Java when doing some operation on Mat (Background Subtraction) the memory is dramatically using by JVM

asked 2017-11-12 21:18:41 -0500

BAHRAMUDIN ADIL gravatar image

I am wondering that what is the reason for dramatical memory using Java program with OpenCV, If only read and show the image, then no problem, but when I want to perform so operation, such as

 Background Subtraction -> cleaning operation (`OPEN`, `CLOSE`, etc) -> find counters -> draw contours

I tried my best to write the most optimized code (avoiding newing Mat in every loop, trying to reuse the previous object etc), so for example, if I have 8GB RAM, then in every second the memory used about 40Mb, then in few minutes the RAM become 100%.

My question is: what is wrong whit OpenCV in Java, Or what should I do with Mats objects? Does Mat object need to be released after every loop? Or I must not use the global Mat object in every loop, in this case, I must new a Mat in every loop?

OpenCV version is: 3.331

edit retag flag offensive close merge delete

Comments

show your code, please.

berak gravatar imageberak ( 2017-11-13 05:54:26 -0500 )edit

The code is long enough to put here, but the routine I have already mentioned above. OK, I think the problem is with Mat object must be released at the end of work done, the Java JVM not (on time) collect the garbage which produces from OpenCV DLL, so it must be released manually. The other way is to call System.gc()

BAHRAMUDIN ADIL gravatar imageBAHRAMUDIN ADIL ( 2017-11-13 20:55:48 -0500 )edit

System.gc() won't do, it never sees memory allocated from c++. so yes, you'll have to manually release() every Mat, you created with new()

berak gravatar imageberak ( 2017-11-14 00:20:17 -0500 )edit

But it really do :) I have tested if I did not release the mat but use System.gc() it works great, I use the latest version of JVM, but Mat which newed, cloned, submated, all must be released.

BAHRAMUDIN ADIL gravatar imageBAHRAMUDIN ADIL ( 2017-11-14 07:01:17 -0500 )edit

ok, if you call it manually ... just saying, that the (java) Mat objects are so small, that it'll never trigger automatically.

berak gravatar imageberak ( 2017-11-14 07:07:04 -0500 )edit