如何使用 opencv 连续保存名为日期和时间的 1 分钟视频

问题描述 投票:0回答:1

我想每分钟重复创建一个以当前日期和时间命名的新视频文件保存到目录路径。

在下面的代码中,它只能做一个 1 分钟长度的视频。

import cv2
import time 
from datetime import datetime
import schedule
import os
import sys
import numpy as np
from os import path



cap = cv2.VideoCapture(0)
if (cap.isOpened() == False): 
   print("Error reading video file")
fps = 24
res = '480p'
def change_res(cap, width, height):
   cap.set(3, width)
   cap.set(4, height)
STD_DIMENSIONS =  {"480p": (640, 480),"720p": (1280, 720),}
def get_dims(cap, res='720p'):
   width, height = STD_DIMENSIONS["480p"]
   if res in STD_DIMENSIONS:
       width,height = STD_DIMENSIONS[res]
   change_res(cap, width, height)
   return width, height
PREFIX = 'Cam'
EXTENSION = 'avi'
file_name_format = "{:s}-{:%d-%m-%Y %H:%M-%S}.{:s}"
date = datetime.now()
today=time.strftime('%d-%m-%Y')
file_name = file_name_format.format(PREFIX, date, EXTENSION)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter ("/home/Desktop/CAM/"+str(today)+"/"
                       +file_name, fourcc, 24.0, get_dims(cap, res))

start_time = time.time()
while (time.time() - start_time) < 60:
   ret, frame = cap.read()
   if ret == True:
       out.write(frame)
       cv2.imshow('CAM', frame)
   if cv2.waitKey(1) & 0xFF == ord('q'):
      break

cap.release()
out.release()
cv2.destroyAllWindows()
python opencv video video-processing video-recording
1个回答
0
投票

只需将所有内容包裹在一个

while True:
中,就像这样:

import cv2
import time
from datetime import datetime
import schedule
import os
import sys
import numpy as np
from os import path


while True:
    cap = cv2.VideoCapture(0)
    if (cap.isOpened() == False):
       print("Error reading video file")
    fps = 24
    res = '480p'
    def change_res(cap, width, height):
       cap.set(3, width)
       cap.set(4, height)
    STD_DIMENSIONS =  {"480p": (640, 480),"720p": (1280, 720),}
    def get_dims(cap, res='720p'):
       width, height = STD_DIMENSIONS["480p"]
       if res in STD_DIMENSIONS:
           width,height = STD_DIMENSIONS[res]
       change_res(cap, width, height)
       return width, height
    PREFIX = 'Cam'
    EXTENSION = 'avi'
    file_name_format = "{:s}-{:%d-%m-%Y %H:%M-%S}.{:s}"
    date = datetime.now()
    today=time.strftime('%d-%m-%Y')
    file_name = file_name_format.format(PREFIX, date, EXTENSION)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter (file_name, fourcc, 24.0, get_dims(cap, res))

    start_time = time.time()
    while (time.time() - start_time) < 5:
       ret, frame = cap.read()
       if ret == True:
           out.write(frame)
           cv2.imshow('CAM', frame)
       if cv2.waitKey(1) & 0xFF == ord('q'):
          break

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

或者代替

while True:
,您可以在循环中添加一个计数器,例如当计数器达到某个值等时跳出循环

© www.soinside.com 2019 - 2024. All rights reserved.