Not sure if this is relevant, but I'm using opencv4nodejs
for my project, and I did run in this situation where if I don't call .release()
on each Mat object, the memory consumption goes up ~10MB/s.
This simple example code will crate the issue.
function loop(camera, display)
{
let mat = camera.read();
let grey_mat = mat.bgrToGray();
loop(camera, display);
}
Where as, this one fixes the problem:
function loop(camera, display)
{
let mat = camera.read();
let grey_mat = mat.bgrToGray();
grey_mat.release();
mat.release();
loop(camera, display);
}
If I search for why OpenCV Mat object causes leaks I get answers where people say that Mat is capable of taking care of memory usage on its own.
If the last statement is true, what am I doing wrong? And if I'm not doing anything wrong, why do I have to explicitly tell a Mat object to release its memory? Or, is there a potential issue with the npm module opencv4nodejs
itself?
That is because your are using recursion
. At the end of the function you call loop
again so it stacks new instances of these Mat
a every recursion. The objects mat and grey_mat are never destroyed, they would if you were to return from the function tough.
If you change the loop for something iterative
you shouldn't encounter the issue anymore as the function returns everytime and the mats are destroyed.
function doLoopWork(camera, display)
{
let mat = camera.read();
let grey_mat = mat.bgrToGray();
}
function loop(camera, display)
{
while (1) {
doLoopWork(camera, display);
}
}