2016-12-31 110 views
2

我正在使用OpenCV2使用摄像头拍摄一些timelapse照片。我想提取摄像头看到的最近的视图。我试图做到这一点。从网络摄像头获取最新帧

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)] 

现在这个工作,但它是烦人不科学的和缓慢的。有没有办法只专门询问缓冲区中最新的图像?或者说,更好的方法来清除缓冲区?

回答

-1

我从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() 
+0

它可能没有一个缓冲的问题,因为它是不断清空缓冲区。缓冲问题对我来说是显而易见的,因为图像捕获之间存在延迟。 – Richard

0

我已阅读,在VideoCapture对象是有5帧缓冲器,并且在.grab方法,它采用的帧,但不对其进行解码。

所以,你可以

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

你在哪里读到这个?请提供一个链接。 – Richard

+0

那么这里提到的缓冲区和设置它的大小的方式(不适用于我)https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-set –

+0

这里是特别提到5帧,http://answers.opencv.org/question/29957/highguivideocapture-buffer-introducing-lag/ –