I believe I am witnessing a memory leak in the following Python code that calls OpenCV functions.
Can you reproduce this? Why does this happen? How can I work around it or fix it?
My environment:
I've now also tested it on another machine in Python 3.9.1 with OpenCV 4.10.0 and NumPy 2.02 and experience the same behavior.
I believe it's linked to cv2.imshow
. With each loop iteration (i.e. every time the image updates) the memory usage of Python increases by an amount relative to the size of the image.
Adding small = cv2.resize(img,(640,360))
and changing the imshow line to cv2.imshow('Image',small)
makes the RAM increase by a much smaller amount.
By inserting a continue
statement above the imshow
call, and thereby skipping imshow
altogether, makes the RAM stay more or less unchanged throughout the loop.
So, I guess this isolates the problem to cv2.imshow
.
import cv2, numpy as np
flag = False
while True:
img = np.zeros((2160,3840,3),np.uint8)
if flag:
img = cv2.circle(img, (1920,1080),128,(255,255,255),-1)
flag = not flag
cv2.imshow('Image',img)
k = cv2.waitKey()
cv2.destroyAllWindows()
if k == 27:
break
Thanks to user Christoph Rackwitz, the cause of the problem was identified as cv2.destroyAllWindows()
.
It seems to be present only on Mac systems and a bug report was filed, but apparently, there aren't currently any plans on fixing it.