python - 以预定间隔从摄像机视频中提取图像

标签 python opencv

我有从笔记本电脑的视频流中获取图像的代码。我想将照片保存间隔减少到每分钟一张照片。原始代码如下所示

# Importing all necessary libraries 
import cv2 
import os 

# Read the video from specified path 
cam = cv2.VideoCapture(0) 

try: 

    # creating a folder named data 
    if not os.path.exists('data'): 
        os.makedirs('data') 

# if not created then raise error 
except OSError: 
    print ('Error: Creating directory of data') 

# frame 
currentframe = 0

while(True): 

    # reading from frame 
    ret,frame = cam.read() 

    if ret: 
        # if video is still left continue creating images 
        name = './data/frame' + str(currentframe) + '.jpg'
        print ('Creating...' + name) 

        # writing the extracted images 
        cv2.imwrite(name, frame) 

        # increasing counter so that it will 
        # show how many frames are created 
        currentframe += 1
    else: 
        break

# Release all space and windows once done 
cam.release() 
cv2.destroyAllWindows() 

对于此任务,我尝试使用参数CAP_PROP_POS_MSEC
[...]
# Read the video from specified path 
cam = cv2.VideoCapture(0)
cam.set(cv2.CAP_PROP_POS_MSEC,20000)
[...]

while(True): 
[...]    
        # writing the extracted images 
        cv2.imwrite(name, frame)
        cv2.waitKey() 
[...]

但是,保存速度保持不变,我看到以下错误

videoio error v4l2 property pos_msec is not supported



我使用Ubuntu 18.04,Python 3.7和OpenCV 4.1。

我在哪里出错?是否选择了正确的方法来最大程度地减少计算机资源的负担?

UPD

使用J.D.的建议,此代码有效
import cv2
import os

import time

prev_time = time.time()
delay = 1 # in seconds
# Read the video from specified path
cam = cv2.VideoCapture(0)
currentframe = 0

while (True):
    # reading from frame
    ret, frame = cam.read()
    if ret:
        if time.time() - prev_time > delay:
            # if video is still left continue creating images
            name = './data/frame' + str(currentframe) + '.jpg'
            print('Creating...' + name)
            # writing the extracted images
            cv2.imwrite(name, frame)
            currentframe += 1
            prev_time = time.time()
    else:
        break

最佳答案

编辑:这个答案不是一个好的解决方案-由于帧缓冲,如注释中所述。由于评论中的相关信息,我将留下答案。

如果您不打算扩展代码来执行其他操作,则可以使用waitkey:
cv2.waitKey(60000)将冻结代码执行60秒。

如果要扩展代码,则必须创建一个基于时间的循环:

import time

prev_time = time.time()
count = 0
delay = 1 # in seconds

while True:
    if time.time()-prev_time > delay:
        count += 1
        print(count)
        prev_time = time.time()

关于python - 以预定间隔从摄像机视频中提取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58878148/

相关文章:

python - 解析包含一系列条目的行,推断数据

python - 在Python中循环写入命令以分别从列表中输出许多不同的索引

python - 如何轻松地在列表中找到具有给定类属性的类实例?

python - OpenCV findContours()仅在图像已保存并事先读取的情况下才检测轮廓

c++ - 使用 OpenCV 在轮廓线上标记点

opencv - 如何更改 Opencv 图像查看器?

python - Tensorflow Keras 也使用 tfrecords 进行验证

c# - 使用OpenCV识别小物体

c++ - 当我在 opencv 3.1.0 中包含 dnn 模块时出现链接错误

python - 根据列的值有效地将一个文件拆分成多个文件