[Python] Python OpenCV set timeout on VideoCapture

Discussão em 'Python' iniciado por Stack, Setembro 3, 2025.

  1. Stack

    Stack Membro Participativo

    Trying to set a max timeout for VideoCapture to catch the exception and print a message if the stream is down. For example, I need it to try for 10 seconds and then assume the stream is offline. I have the following code so far.

    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.")


    Edit: Tried to simplify the answer below and it kind of works as expected but still with its own timeout decision.

    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.")

    Continue reading...

Compartilhe esta Página