2017-05-04 165 views
0

我正在使用Python OpenCV作爲第一步涉及從網絡攝像頭捕獲圖像的項目;我試圖通過使用capture = cv2.VideoCapturecapture.read()來自動執行此過程,但相機的視頻模式激活及其隨後的自我調整對於我最終想實現的速度來說太慢。直接獲取攝像頭截圖的方法

是否有一個更直接的方法來自動捕捉與Python(和OpenCV)截圖?如果不是,你有其他建議嗎? 感謝

+0

我有同樣的問題,但找不到更好的解決方案。 – arsho

+0

如果我理解正確,你目前所做的是在屏幕截圖功能中初始化視頻捕捉? ('capture = cv2.VideoCapture',然後'capture.read()') –

+0

沒錯,但我想知道是否有更直接的方式來訪問相機畫面,但我猜想初始化是需要的一步。 – Eggman

回答

0

如果你希望你的相機截圖功能是響應,你需要初始化相機捕捉這個功能之外

在下面的代碼段中,screenshot功能通過按下Ç觸發:

import cv2 

def screenshot(): 
    global cam 
    cv2.imshow("screenshot", cam.read()[1]) # shows the screenshot directly 
    #cv2.imwrite('screenshot.png',cam.read()[1]) # or saves it to disk 

if __name__ == '__main__': 

    cam = cv2.VideoCapture(0) # initializes video capture 

    while True: 
     ret, img = cam.read() 
     cv2.imshow("cameraFeed", img) # a window is needed as a context for key capturing (here, I display the camera feed, but there could be anything in the window) 
     ch = cv2.waitKey(5) 
     if ch == 27: 
      break 
     if ch == ord('c'): # calls screenshot function when 'c' is pressed 
      screenshot() 

    cv2.destroyAllWindows() 

爲了澄清cameraFeed窗口只這裏演示的目的(其中screenshot手動觸發)。如果您的程序中自動調用screenshot,則不需要此部分。

希望它有幫助!

0

基本上你需要做3件事情:

#init the cam 
video_capture = cv2.VideoCapture(0) 
#get a frame from cam 
ret, frame = video_capture.read() 
#write that to disk 
cv2.imwrite('screenshot.png',frame) 
當然

之前,您應該等待一段時間,如果不是你能救一個奇怪的黑屏(或只是第一件事相機了: - ))