import time
import cv2 as cv
url = "rtsp://10.1.1.15:554"
a = cv.VideoCapture(url)
assert a.isOpened()
rv, frame = a.read()
a.release()
count = 1
while True:
a.open(url)
assert a.isOpened()
rv, frame = a.read()
a.release()
count += 1
print(count)
time.sleep(1)
time.sleep(1)
#The loop stays at ±3MB and never releases the extra 20MB
#Another experiment (added additional camera):
a = cv.VideoCapture(url)
b = cv.VideoCapture(url2)
assert a.isOpened()
assert b.isOpened()
rv, frame = a.read() #Adds 24MB to RAM
rv2, frame2 = b.read() # Adds 15 MB to RAM
a.release() # Removes 1 MB
b.release() # Removes 3MB
count = 1
while True: #After 10 iterations it seems to stabilize at +10MB
a.open(url)
b.open(url)
assert a.isOpened()
assert b.isOpened()
rv, frame = a.read()
rv2, frame2 = b.read()
a.release()
b.release()
count += 1
print(count)
time.sleep(1)
How can I free the extra 45MB?
1. Deleting frame and frame2 freed 10MB
I have 35 MB left which cannot be freed without killing the process. I tried releasing a and b and also deleting them but it won’t help. As can be seen here, in case I had more cameras the memory leak will be worse. What can be done here?
apparently RAM use doesn’t grow from repeated object creation or use. in that case, this is not a leak.
operating systems and runtime libraries are allowed to (and usually do) keep allocated memory for future use even if it’s “freed”.
it does not grow over time. we determined that. you may be dissatisfied by the constant RAM usage but it’s constant.
that means even if you connect to 50 cameras concurrently, RAM usage will be constant (times 50). it may be significant but that’s a different problem.
you seem to require specific optimizations. OpenCV is not intended for that.
please directly use ffmpeg, gstreamer, or other libraries.
Thank you for your answers. I do not mean to use all of them concurrently. Also if I use them with the same VideoCapture but one after the other I still get the memory growing. The only case where it is not is when I use the same video address. For example, in case I want to edit 1000 video files sequentially. I get the memory growing either if I use 1 instance of VideoCapture or multiple. Is that so specific? Is killing the process the only option for opencv?
Here is an easy code for reproducibility. It was run from a folder with ~30 video files. Just reading the first frame from each video, then releasing it. This is just an example so please don’t pick on the details, the same happens with RTSP.