python - 将视频帧保存为图像时如何添加延迟
问题描述
我有一系列视频,我想将其中的帧保存为图像。这是我的代码:
import os, cv2
current_dir = os.getcwd()
training_videos = '../../Videos/training_videos/'
if not os.path.exists(current_dir + '/training_images/'):
os.mkdir(current_dir + '/training_images/')
for i in os.listdir(training_videos):
video = cv2.VideoCapture('../../Videos/training_videos/' + i)
currentFrame = 0
while (True):
# Capture frame-by-frame
ret, frame = video.read()
# Saves image of the current frame in jpg file
name = current_dir + '/training_images/frame' + str(currentFrame) + '.png'
print('Creating...' + name)
cv2.imwrite(name, frame)
# To stop duplicate images
currentFrame += 1
此代码有效,但不幸的是,它每毫秒需要一帧。这不是我想要的。相反,我想每 5 或 10 秒保存一帧。我考虑过添加时间延迟,但这不会真正起作用,因为视频不是实时流,所以 5 秒后,它只会在前一毫秒后截取屏幕截图。
解决方案
可能有一种更有效的方法,但您可以通过使用视频的帧速率然后每FRAME_RATE * 5
帧处理图像来做到这一点。
您的代码看起来像这样(让我知道这是否不起作用,因为我没有在我的 PC 上运行它):
import os, cv2
current_dir = os.getcwd()
training_videos = '../../Videos/training_videos/'
if not os.path.exists(current_dir + '/training_images/'):
os.mkdir(current_dir + '/training_images/')
for i in os.listdir(training_videos):
video = cv2.VideoCapture('../../Videos/training_videos/' + i)
fps = video.get(cv2.CAP_PROP_FPS)
currentFrame = 0
while video.isOpened():
# Capture frame-by-frame
ret, frame = video.read()
if (video):
# Write current frame
name = current_dir + '/training_images/frame' + str(currentFrame) + '.png'
print('Creating...' + name)
cv2.imwrite(name, frame)
currentFrame += fps * 5
# Skip to next 5 seconds
video.set(cv2.CAP_PROP_POS_FRAMES, currentFrame)
推荐阅读
- matlab - 在 MATLAB 中预训练的 VGG-16 和 PyTorch 一样吗?
- scala - 如何在scala程序中连接hive
- logging - 从 SMTPAppender 配置日志级别
- xcode - 如何以特定顺序在 Xcode 项目中构建源文件
- javascript - JS在PHP中传递日期时日期错误
- java - Java - 查找第一个和最后两个不同的值
- node.js - TypeScript:节点 11 的“正确”“目标”是什么?
- javascript - 从 JSON 数组中获取具有最低键值的数组
- android - GetActiveNotifications 返回 null
- php - Magento 2 管理菜单中不可点击的按钮