Search code examples
pythonopencvvideo-capture

How to save videos recorded from a loop as different files?


I'm recording videos in a loop using opencv and python. I've managed to get it to record and save all the videos from the loop to a single output file, but my goal is to get every video recorded in the loop saved as a different file, with the date and time as the identifier for each video. I don't use python very much and I'm sure there is a simple way to do it but I just can't find it. Any help is much appreciated!

import cv2
import time as t1
import numpy as np

def save_video(outPath,fps,mirror=False):
    cap = cv2.VideoCapture(0)

    currentFrame = 0
    width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)  # float
    height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)  # float

    fourcc = cv2.VideoWriter_fourcc(*"XVID")
    out = cv2.VideoWriter(outPath, fourcc, 20.0, (int(width), int(height)))

    while (cap.isOpened()):
        ret, frame = cap.read()
        if ret == True:
            if mirror == True:
                frame = cv2.flip(frame, 1)
            out.write(frame)
        cv2.imshow('frame', frame)
    else:
        break
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

    currentFrame +=1


    cap.release()
    out.release()
    cv2.destroyAllWindows()

date_string = t1.strftime("%Y-%m-%d-%H:%M")

count=0
while(True):
    if count < 6:
    print('Recording started: recording video number ' + str(count))
    save_video('/Documents/0222_video_recordings/video' + date_string + '.avi', 
    30.0,mirror=True)
    count += 1

Solution

  • Select different file name in each iteration.

    Example:

    save_video('/Documents/0222_video_recordings/video_' + str(count) + '_' + date_string + '.avi',