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

# 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()
[...]

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



我使用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()

10-08 12:03