'Save a video with different file name each time we give a Trigger in opencv

This is the process I am trying to achieve :

  1. Live Stream is captured from webcam and the Image frames are stored in a particular folder.

  2. Now, If I give a trigger the frames in that folder at that moment should be converted into a video and get saved with name eg. video1.mp4.

  3. Now again if I press a trigger another video should be saved as video2.mp4.

I have attached the code here . If I press R , it is saving one video as a0.mp4 . But If I press again, nothing seems to happen.

def frametovideo(img_array):

for i in range(len(img_array)):
    out.write(img_array[i])

if name == "main":

img_array = []
videono = 0
cap = cv2.VideoCapture(0)

for filename in glob.glob('./output/*.jpg'):
    img = cv2.imread(filename)
    height, width, layers = img.shape
    size = (width,height)
    img_array.append(img)

path = 'a' + str(videono) + '.mp4'
out = cv2.VideoWriter(path,cv2.VideoWriter_fourcc(*'mp4v'), 15, size)

while True:
    
    ret, frame = cap.read()
    
    if ret == True:
        
        cv2.imshow("frame",frame)
        k = cv2.waitKey(5) & 0xff
        if k == ord('r'):
            frametovideo(img_array)
            videono += 1


Solution 1:[1]

You do not understanding how to save filenames Do not used operator. Used string format python 3.8 or later. Try this in below. Actually, you can modified key press.

import cv2
import os


i = 1

wait = 0


video = cv2.VideoCapture(0)

while video.isOpened():
    ret, img = video.read()

    cv2.imshow('live video', img)

    # wait for user to press any key
    key = cv2.waitKey(100)

    # wait variable is to calculate waiting time
    wait = wait+100

    if key == ord('q'):
        break
    # when it reaches to 5000 milliseconds
    # we will save that frame in given folder
    if wait == 5000:
        filename = f'Frame_{str(i)}.jpg'
        
        # Save the images in given path
        cv2.imwrite(filename, img)
        i += 1
        wait = 0

# close the camera
video.release()

# close open windows
cv2.destroyAllWindows()

Btw,look in line #27-34. Correct way to do this if __name__ == "__main__":

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1