【问题标题】:OpenCV input delay in capturing frames捕获帧时的 OpenCV 输入延迟
【发布时间】:2020-01-12 14:19:56
【问题描述】:

我编写了一个代码,可以使用 OpenCV 从网络摄像头馈送中捕获图像。但是,每当我按下键捕获我的帧时,都会出现输入延迟。当我使用它退出时没有延迟,但是当我使用捕获时有一个明显的延迟。我通过在两种情况下都打印一条语句来衡量这一点,按下c 时,该语句在打印前需要延迟。在我看来,这个问题类似于......相机资源正在被使用并且没有及时释放以供下一次按键或类似的事情......但不确定。

import cv2 as cv
import numpy as np
import glob
import matplotlib.pyplot as plt

cap = cv.VideoCapture(1)

img_counter = 0

while True:
    ret, frame = cap.read()
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    # cv.imshow('frame',frame)
    cv.imshow('gray', gray)
    if not ret:
        break

    if cv.waitKey(1) & 0xFF == ord('q'):
        print('helloq')
        break

    elif cv.waitKey(1) & 0xFF == ord('c'):
        print('hello{}'.format(img_counter))
        img_name = "opencv_frame_{}.png".format(img_counter)
        cv.imwrite(img_name, gray)
        img_counter += 1

我正在使用外部网络摄像头,并且 cv2.__version__ = 3.4.2`

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    解决了你的问题,好像是你的key检查造成的。

    您不应多次调用 waitKey(1)。它会导致延迟。

    试试这个解决方案:

    cap = cv.VideoCapture(0)
    
    img_counter = 0
    
    while True:
        ret, frame = cap.read()
        gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
        # cv.imshow('frame',frame)
        cv.imshow('gray', gray)
        if not ret:
            break
    
        key = cv.waitKey(1)
    
        if key==ord('c'):
            print('img{}'.format(img_counter))
            img_name = "opencv_frame_{}.png".format(img_counter)
            cv.imwrite(img_name, gray)
            img_counter += 1
            print("Succesfully saved!")
    
        if key==ord('q'):
            print('Closing cam...')
            break
    
    # When everything done, release the capture
    cap.release()
    cv.destroyAllWindows()
    

    【讨论】:

    • 有效!您能解释一下您是如何找到解决方案的吗?
    • 检查两次按下的键会导致延迟cv.waitKey(1) & 0xFF == ord('q'),一次就足够了:key = cv.waitKey(1)
    猜你喜欢
    • 2014-06-03
    • 2019-12-09
    • 2013-04-15
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    相关资源
    最近更新 更多