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

h5qlskok  于 2023-03-07  发布在  Python
关注(0)|答案(1)|浏览(171)

我想每分钟重复地创建一个新的以当前日期和时间命名的录像文件保存到目录路径中。
在下面的代码中,它所能做的就是制作一个长度为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()
7cjasjjr

7cjasjjr1#

只需将所有内容 Package 在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:,例如当计数器达到某个值时跳出循环。

相关问题