pythonpython-3.xopencvsurveillance

Python: Automatically reconnect IP camera


My IP camera seems to be a little unstable and disconnects randomly. I'd like my script to be able to determine when its disconnected and attempt to reconnect a few times, probably waiting 5-10 seconds between attempts. I've tried a few things, but nothing is working.

This is my basic script, when ret is false the script ends:

#!/usr/local/bin/python3

import cv2
import time
import datetime

print("start time: " + datetime.datetime.now().strftime("%A %d %B %Y %I:%M:%S%p"))

cap = cv2.VideoCapture('rtsp://<ip><port>/live0.264')

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Confirm we have a valid image returned
    if not ret:
        print("disconnected!")
        break

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA)

    # Display the resulting frame
    cv2.imshow('frame', gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

print("end time: " + time.strftime("%X"))
# When everything is done, release the capture
cap.release()
cv2.destroyAllWindows()

Edit: I would also like the script to try to reconnect to the camera in the event that my network goes down temporarily or anything like that as well.


Solution

  • I was finally able to solve this myself. Hopefully this is useful for anyone else looking to do the same thing.

    This is actually a shell of a more complex script that has logic for motion detection and video recording when motion is detected. Everything is working very well with this basic logic (and my crappy IP camera) although I am still doing testing.

    #!/usr/local/bin/python3
    
    import cv2
    import datetime
    import time
    
    
    def reset_attempts():
        return 50
    
    
    def process_video(attempts):
    
        while(True):
            (grabbed, frame) = camera.read()
    
            if not grabbed:
                print("disconnected!")
                camera.release()
    
                if attempts > 0:
                    time.sleep(5)
                    return True
                else:
                    return False
    
    
    recall = True
    attempts = reset_attempts()
    
    while(recall):
        camera = cv2.VideoCapture("rtsp://<ip><port>/live0.264")
    
        if camera.isOpened():
            print("[INFO] Camera connected at " +
                  datetime.datetime.now().strftime("%m-%d-%Y %I:%M:%S%p"))
            attempts = reset_attempts()
            recall = process_video(attempts)
        else:
            print("Camera not opened " +
                  datetime.datetime.now().strftime("%m-%d-%Y %I:%M:%S%p"))
            camera.release()
            attempts -= 1
            print("attempts: " + str(attempts))
    
            # give the camera some time to recover
            time.sleep(5)
            continue