2016-12-31 139 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/ –