Search code examples
pythonopencvvideovideo-encoding

Opencv save last N seconds of a camera stream


Is there a way to save last N seconds of a video stream to a file with openCV? E.g. The camera recording starts at 0s and ends at 20s leading to a recorded file which contains the video from 10s -> 20s.

One way I can think of is to save last N seconds in a memory buffer and write them to file once the process finishes, but this is not a desireable solution because of the latency involved at the end as well as memory limitations when multiple HD streams are involved.


Solution

  • I found a working solution, in case anyone needs it.

    t = cv2.VideoWriter('appsrc ! videoconvert ! x264enc tune=zerolatency ! '
                      'mpegtsmux ! hlssink location=/var/www/segment-%05d.ts '
                      'playlist-location=/var/www/index.m3u8 max-files=20 target-duration=15',
                      0, framerate, (640, 480))
    

    Essentially you create a gstreamer pipline with opencv and control the target-duration property to achieve the desired result.

    Here is a Link to the post