尝试为VideoCapture设置最大超时以捕获异常,并在流关闭时打印消息。例如,我需要它尝试10秒,然后假设流离线。到目前为止,我有以下代码。
import cv2
try:
cap = cv2.VideoCapture("rtsp://Username:Password@IP_ADDRESS:PORT")
print("Stream found.")
cap.release()
cv2.destroyAllWindows()
except:
# It actually never reaches the exception
print("Stream not found.")编辑:试图简化下面的答案,它像预期的那样工作,但仍然有自己的超时决定。
import cv2
import time
try:
cap = cv2.VideoCapture("rtsp://DNA:DNA2020!@98.173.8.28:5514")
try:
success, video_frame = cap.read()
if success:
print('Frame read')
else:
print('No frame read')
except cv2.error as e:
print(f'CV2 Exception: {str(e)}')
cap.release()
except:
print("Stream not found.")发布于 2022-10-29 11:13:44
打开流时,只会得到一个视频对象。然后你必须开始从视频对象中读取帧。这会告诉你是否有视频流。
超时:如果10秒内没有收到任何帧,代码就会停止。
重置超时:如果在10秒内收到新帧,则接收恢复,超时时间将再次为10秒。
我在一个视频文件上测试了这段代码。我认为它也应该在你的相机上工作。
import cv2
import time
try:
cap = cv2.VideoCapture("rtsp://Username:Password@IP_ADDRESS:PORT")
print("Stream found.")
stream_ok = True
while True:
try:
success, video_frame = cap.read()
if success:
print('Frame read')
frame_ok = True
# show frame
cv2.imshow("Image", video_frame)
cv2.waitKey(1)
else:
print('No frame read')
frame_ok = False
except cv2.error as e:
print(f'CV2 Exception: {str(e)}')
frame_ok = False
if stream_ok:
if not frame_ok:
# start of missing video
stream_ok = False
no_frame_start_time = time.time()
else:
if not frame_ok:
# still no video
if time.time() - no_frame_start_time > 10:
print('NO VIDEO - CAPTURE ABORTED')
break
else:
# video restarted
stream_ok = True
cap.release()
cv2.destroyAllWindows()
except:
# It actually never reaches the exception
print("Stream not found.")https://stackoverflow.com/questions/74244577
复制相似问题