I am trying to use RTSP stream, but I just want the last frame every certain execution time:
while True
image.get()
#EXECUTE STUFF AROUND 0.1seconds
I am using the following code on a RTSP stream of a 25fps camera. The problem is that after around 5 minutes of working perfectly fine, the cv2.VideoCapture stream stops to return an image (returns False flag). Why is that?
import threading
from threading import Lock
import cv2
rtsp_link = "rtsp://url"
vcap = cv2.VideoCapture(rtsp_link)
latest_frame = None
last_ret = None
lo = Lock()
def rtsp_cam_buffer(vcap):
global latest_frame, lo, last_ret
while True:
with lo:
last_ret, latest_frame = vcap.read()
t1 = threading.Thread(target=rtsp_cam_buffer,args=(vcap,),name="rtsp_read_thread")
t1.daemon=True
t1.start()
while True :
if (last_ret is not None) and (latest_frame is not None):
img = latest_frame.copy()
else:
print("unable to read the frame")
time.sleep(0.2)
continue
The time until the cv2.videocapture stream stops receiving frames it's irregular, sometimes it's seconds, and now it has been working 15 minutes. How?!
No error is shown on the screen when RTSP stream stops receiving images.
As some people in the comments have said, the issue was not the code. Doing it with threading works perfectly fine.
The issue was that the connection to the camera was very bad. I lost 50% of the packets when I did PING cameraIP.
Nonetheless, I change the code, and added a condition, that if none image is received during more than 30 seconds, reconnect the camera, executing cv2.VideoCapture again.