我有一个从 github 的相机捕获视频的代码https://gist.github.com/keithweaver/4b16d3f05456171c1af1f1300ebd0f12#file-save-video-w-opencv-py。
但是如何设置此捕获的时间限制?。我想连续捕获多个视频,持续时间例如 3 分钟,没有任何帧丢失。
我对编程有点陌生,任何人都可以帮助编写代码吗?非常感谢
你可以这样做:
startTime = time.time()
timeElapsed = startTime - time.time()
几秒钟内secElapsed = int(timeElapsed)
while(secElapsed < 100)
代码示例,应该如下所示:
import numpy as np
import cv2
import time
# The duration in seconds of the video captured
capture_duration = 10
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
start_time = time.time()
while( int(time.time() - start_time) < capture_duration ):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
out.write(frame)
cv2.imshow('frame',frame)
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
您也可以使用
moviepy
。
以秒为单位设置 start
和 end
持续时间。假设您想要捕获子剪辑,从第二分钟开始(例如 start=120),您想要录制 5 分钟。 (5 分钟=300 秒)。以下是具体操作方法:
from moviepy import VideoFileClip
clip = VideoFileClip("/path/to/video.mp4")
starting_point = 120 # start at second minute
end_point = 420 # record for 300 seconds (120+300)
subclip = clip.subclip(starting_point, end_point)
subclip.write_videofile("/path/to/new/video.mp4")
从 @Ali Yilmaz 的说法来看,这可能有点过时了。它在带有内核 4.19.x 和 python3 的 Debian Buster 的 32 位 Arm 处理器上以这种方式工作。
from moviepy.editor import VideoFileClip
clip = VideoFileClip("/path/to/yourfile.mp4")
start = 10 # start at 10 seconds
end = 25 # plays for 15 seconds and ends at 25 seconds
subclip = clip.subclip(start, end)
subclip.write_videofile("/path/to/yournewfile.mp4")
我认为我的 moviepy 设置和 Ali 的设置的唯一区别是,两年内,moviepy 发行和安装的情况发生了变化。
OpenCV 已经有这个功能了:
# Set the starting and ending frame numbers
start_frame = int(cap.get(cv2.CAP_PROP_FPS) * start_time)
end_frame = int(cap.get(cv2.CAP_PROP_FPS) * end_time)
# Iterate over the frames and write to the output file
cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
while cap.get(cv2.CAP_PROP_POS_FRAMES) <= end_frame:
# your code here...