python cv2 无限记录10s片段

python cv2 record 10s clips infinitely

问题陈述: 本质上,我正在尝试制作一个 raspberry pi 零基础行车记录仪。 我需要一个 10 秒的剪辑,文件名是当前日期和时间。只要 pi 有电源,这个循环就应该继续。 我已经编写了如图所示的脚本,但它不会创建 10 秒剪辑的单独文件,而是创建一个大文件。关于我做错了什么的任何线索?

import cv2
import time

cv2.namedWindow("dashcam")
video = cv2.VideoCapture(1)

if video.isOpened():  # try to get the first frame
    rval, frame = video.read()
else:
    rval = False

frame_width = int(video.get(3))
frame_height = int(video.get(4))
timestr = time.strftime("%Y_%m_%d__%H_%M_%S")
out = cv2.VideoWriter(timestr+'.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 10, (frame_width, frame_height))

now = time.time()
while rval:
    rval, frame = video.read()
    if time.time() - now < 5:
        cv2.imshow('dashcam', frame)
        out.write(frame)
    elif time.time() - now > 5:
        now = time.time()
    key = cv2.waitKey(1)
    if key == 27:  # exit on ESC
        break

video.release()
out.release()
cv2.destroyAllWindows()

因为您只创建一次“out”,所以您的代码只会保存 1 个视频。您可以在下面尝试我的代码。如果您对我的代码有任何错误,请向我报告。

import cv2
import time 
cv2.namedWindow("dashcam")
video = cv2.VideoCapture(1)
last_save_time = -10
while video.isOpened():
    rval, frame = video.read()
    if not rval:
        break
    frame_width = int(video.get(3))
    frame_height = int(video.get(4))
    current_time = time.time()
    if current_time - last_save_time > 10:
        last_save_time = current_time
        timestr = time.strftime("%Y_%m_%d__%H_%M_%S")
        out = cv2.VideoWriter(timestr+'.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 25, (frame_width, frame_height))
    cv2.imshow('dashcam', frame)
    out.write(frame)
    key = cv2.waitKey(1)
    if key == 27:  # exit on ESC
        break
video.release()
cv2.destroyAllWindows()