Search code examples
onvif

How to read video frames continuously from an ONVIF camera?


I want to read video frame data from an ONVIF camera so that frame data can be later used for post-processing/Analyzing it. Using SnapshotUri I can get a snapshot but I want to read frames continuously. Is it possible to obtain video frame data in an ONVIF client?


Solution

  • Not sure what programming language you are using for your analysis but if Python and OpenCV are an option (or C++ with OpenCV for that matter; although below code is for Python) you can grab frames using the VideoCapture class in OpenCV. Similarly to this:

    import cv2
    
    address = "RTSP URI YOU USE WITH YOUR CAMERA HERE"
    cap = cv2.VideoCapture(address)
    
    while True:
        ok, frame = cap.read()
        # do whatever else you want with the frame
    

    It wasn't entirely clear whether you might want to do processing in real time since, if not, you could capture the RTSP stream with ffmpeg and then cut it into frames later but you could also save out frames by adding a call to cv2.imwrite in the while loop in the code snippet above. You would have to have some code generating unique (and probably sequential, depending on your purposes) filenames to use in the call to cv2.imwrite so that you weren't just overwriting the same image. I can add such code to this answer if that is indeed along the lines of what you need.

    If you only want to capture the stream into frames in real time, you could use ffmpeg on the command line:

    ffmpeg -i rtsp://USERNAME:PASSWORD@CAMERA_IP_ADDRESS:554 -vf fps=15 out%04d.png
    

    where USERNAME and PASSWORD are the credentials of an account on the camera and CAMERA_IP_ADDRESS is the IP address of the camera on your network. You can set the fps to whatever frame rate you desire.

    This will create a sequence of images named outXXXX.png starting with XXXX = 0001. You can change the zero-padding amount by changing the number that is 4 in the example command.