How do I fix a Julia OpenCV Cxx memory leak in image capturing?

Viewed 142

I have a local build of OpenCV on an intel Ubuntu system per these instructions. Nearly identical python, c++, and julia demo programs to capture 1000 images execute mostly as expect. The python and c++ versions work perfectly, but "top" shows that the julia version exhibits a growing use of system memory in tens of MB per second as it runs. If left long enough the system runs out of memory and locks up.

Why does the julia code seem to result in a memory leak and how can I fix that?

using OpenCV
using Printf
cv = OpenCV


function main( )
    vidDevice="/dev/video0"
    cap = cv.VideoCapture(vidDevice)
    count = 1000
    while (cv.isOpened(cap) && count > 0)
        @printf("Capturing %4d\r", count)
        ret,img = cv.read(cap)
        count = count - 1
        
    end
    cv.release(cap)
    cv.destroyAllWindows()

end

main()
1 Answers

The code results in a memory leak because Julia GC does not "know" the real size of Mat Objects and thinks it is only the size of a pointer. You can get this code to work similar to Python by forcing the GC to run by inserting GC.gc() inside the loop but that doesn't fix the core issue which is that GC does not run automatically even when system is running out of memory.

This modified version of your code should work without any issues -

using OpenCV
using Printf
cv = OpenCV


function main( )
    vidDevice="/dev/video0"
    cap = cv.VideoCapture(vidDevice)
    count = 1000
    while (cv.isOpened(cap) && count > 0)
        @printf("Capturing %4d\r", count)
        GC.gc()
        ret,img = cv.read(cap)
        count = count - 1
        
    end
    cv.release(cap)
    cv.destroyAllWindows()

end

main()

I have created a tracker for this issue at https://github.com/opencv/opencv_contrib/issues/2766

Related