Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV Python QueryFrame function leaks memory

I'm using the Python interface for OpenCV 2.2.0. The following code works correctly for grabbing frames from a video file:

for f in range(1, frameCount):
    # grab the left and right frames
    frameL = cv.QueryFrame(videoL)
    frameR = cv.QueryFrame(videoR)
    # create the image for the first frame
    if f==1:
        imageL = cv.CreateImage(cv.GetSize(frameL), frameL.depth, frameL.channels)
        imageR = cv.CreateImage(cv.GetSize(frameR), frameR.depth, frameR.channels)
    # update the images
    cv.Copy(frameL, imageL)
    cv.Copy(frameR, imageR)

However, as I process more video frames, the memory consumption keeps increasing. According to the OpenCV documentation, we don't need to release the memory for the image data obtained by cv.QueryFrame. Is this still correct? I tried "del frameL" and "del frameR", but it didn't solve the problem. Is there a bug in the Python wrapper for OpenCV in this particular function?

Thanks.

like image 781
Chang Avatar asked Feb 01 '26 07:02

Chang


1 Answers

You should allocate memory for both images once: imageL = cv.CreateImageHeader(cv.GetSize(frameL), frameL.depth, frameL.channels) imageR = cv.CreateImageHeader(cv.GetSize(frameR), frameR.depth, frameR.channels)

then begin your loop and set the data:

cv.SetData(frameL, imageL)
cv.SetData(frameR, imageR)

so something like

for f in range(1, frameCount):
    # grab the left and right frames
    frameL = cv.QueryFrame(videoL)
    frameR = cv.QueryFrame(videoR)
    # create the image for the first frame
    if f==1:
        imageL = cv.CreateImageHeader(cv.GetSize(frameL), frameL.depth, frameL.channels)
        imageR = cv.CreateImageHeader(cv.GetSize(frameR), frameR.depth, frameR.channels)
    # update the images
    cv.SetData(frameL, imageL)
    cv.SetData(frameR, imageR)
like image 127
meduz Avatar answered Feb 03 '26 20:02

meduz