从网络摄像头获取最新的帧

时间:2016-12-31 22:16:27

标签: python opencv webcam

我正在使用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)]

现在这种方法有效,但它却非常不科学和缓慢。有没有办法专门询问缓冲区中最近的图像?或者,禁止这样,清除缓冲区的更好方法是什么?

2 个答案:

答案 0 :(得分:1)

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

所以你可以

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

答案 1 :(得分:-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()