【问题标题】:Get most recent frame from webcam从网络摄像头获取最新帧
【发布时间】:2016-12-31 22:16:26
【问题描述】:

我正在使用 OpenCV2 使用网络摄像头拍摄一些延时摄影照片。我想提取网络摄像头看到的最新视图。我尝试这样做。

import cv2
a = cv2.VideoCapture(1)
ret, frame = a.read()
#The following garbage just shows the image and waits for a key press
#Put something in front of the webcam and then press a key
cv2.imshow('a',frame); cv2.waitKey(0); cv2.destroyAllWindows(); [cv2.waitKey(25) for i in range(10)]
#Since something was placed in front of the webcam we naively expect
#to see it when we read in the next image. We would be wrong.
ret, frame = a.read()
cv2.imshow('a',frame); cv2.waitKey(0); cv2.destroyAllWindows(); [cv2.waitKey(25) for i in range(10)]

除了放置在网络摄像头前面的图像不显示。这几乎就像有某种缓冲......

所以我像这样清除缓冲区:

import cv2
a = cv2.VideoCapture(1)
ret, frame = a.read()
#Place something in front of the webcam and then press a key
cv2.imshow('a',frame); cv2.waitKey(0); cv2.destroyAllWindows(); [cv2.waitKey(25) for i in range(10)]

#Purge the buffer
for i in range(10): #Annoyingly arbitrary constant
  a.grab()

#Get the next frame. Joy!
ret, frame = a.read()
cv2.imshow('a',frame); cv2.waitKey(0); cv2.destroyAllWindows(); [cv2.waitKey(25) for i in range(10)]

现在这可行,但它非常不科学且速度慢。有没有办法专门询问缓冲区中的最新图像?还是说,有更好的方法来清除缓冲区?

【问题讨论】:

    标签: python opencv webcam


    【解决方案1】:

    我读到在 VideoCapture 对象中有一个 5 帧缓冲区,并且有 .grab 方法获取帧但不解码。

    所以你可以

    cap = cv2.VideoCapture(0)
    for i in xrange(4):
        cap.grab()
    ret, frame = cap.read()
    ...
    

    【讨论】:

    【解决方案2】:

    我从Capture single picture with opencv 找到了一些有用的代码。我对其进行了修改,使其连续显示最近捕获的图像。它似乎没有缓冲问题,但我可能误解了你的问题。

    import numpy as np
    import cv2
    
    cap = cv2.VideoCapture(0) # video capture source camera (Here webcam of laptop) 
    ret,frame = cap.read() # return a single frame in variable `frame`
    
    
    while(True):
        ret,frame = cap.read() # return a single frame in variable `frame
        cv2.imshow('img1',frame) #display the captured image
        if cv2.waitKey(1) & 0xFF == ord('y'): #save on pressing 'y' 
            cv2.imwrite('images/c1.png',frame)
            cv2.destroyAllWindows()
            break
    
    cap.release()
    

    【讨论】:

    • 它可能没有缓冲区问题,因为它一直在清空缓冲区。缓冲问题对我来说是因为图像捕获之间存在延迟。
    猜你喜欢
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多