簡體   English   中英

Python:如何使用 OpenCV 在單擊時從網絡攝像頭捕獲圖像

[英]Python: how to capture image from webcam on click using OpenCV

我想使用 OpenCV 從我的網絡攝像頭捕獲並保存一些圖像。 這是我目前的代碼:

import cv2

camera = cv2.VideoCapture(0)
for i in range(10):
    return_value, image = camera.read()
    cv2.imwrite('opencv'+str(i)+'.png', image)
del(camera)

這樣做的問題是我不知道圖像是什么時候拍攝的,所以很多圖像最終都很模糊。 我的問題是:有沒有辦法通過單擊鍵盤鍵來拍攝圖像?

還有沒有更好的方法來拍攝多張圖像,而不是范圍?

這是一個簡單的程序,它在cv2.namedWindow中顯示相機提要,並在您點擊SPACE時拍攝快照。 如果您點擊ESC它也會退出。

import cv2

cam = cv2.VideoCapture(0)

cv2.namedWindow("test")

img_counter = 0

while True:
    ret, frame = cam.read()
    if not ret:
        print("failed to grab frame")
        break
    cv2.imshow("test", frame)

    k = cv2.waitKey(1)
    if k%256 == 27:
        # ESC pressed
        print("Escape hit, closing...")
        break
    elif k%256 == 32:
        # SPACE pressed
        img_name = "opencv_frame_{}.png".format(img_counter)
        cv2.imwrite(img_name, frame)
        print("{} written!".format(img_name))
        img_counter += 1

cam.release()

cv2.destroyAllWindows()

我認為這應該在很大程度上回答你的問題。 如果您有任何不明白的地方,請告訴我,我會添加評論。

如果您需要每次按SPACE鍵抓取多個圖像,您將需要一個內部循環,或者可能只是創建一個抓取特定數量圖像的函數。

請注意,關鍵事件來自cv2.namedWindow因此它必須具有焦點。

分解您的代碼示例(說明在代碼行下方。)

import cv2

導入 openCV 以供使用

camera = cv2.VideoCapture(0)

使用連接到計算機的相機列表中的第一個相機創建一個名為相機的對象,類型為 openCV 視頻捕捉。

for i in range(10):

告訴程序將以下縮進代碼循環 10 次

    return_value, image = camera.read()

使用它的 read 方法從相機對象讀取值。 它與 2 個值產生共鳴,將 2 個數據值保存到兩個名為“return_value”和“image”的臨時變量中

    cv2.imwrite('opencv'+str(i)+'.png', image)

使用 openCV 方法 imwrite(將圖像寫入磁盤)並使用臨時數據變量中的數據寫入圖像

更少的縮進意味着循環現在已經結束......

del(camera)

刪除 camrea 對象,我們不再需要它。

您可以通過多種方式滿足您的要求,一種可能是用 while 循環替換 for 循環,(永遠運行,而不是 10 次),然后等待按鍵(就像我打字時由danidee回答)

或者創建一個隱藏在后台並在每次有人按下鍵盤時捕獲圖像的更邪惡的服務......

我對 open cv 不太有經驗,但是如果您希望在按下某個鍵時調用 for 循環中的代碼,則可以使用 while 循環和一個 raw_input 以及一個條件來防止循環永遠執行

import cv2

camera = cv2.VideoCapture(0)
i = 0
while i < 10:
    raw_input('Press Enter to capture')
    return_value, image = camera.read()
    cv2.imwrite('opencv'+str(i)+'.png', image)
    i += 1
del(camera)

這是一個使用默認相機捕獲圖像的簡單程序。 此外,它可以檢測人臉

import cv2
import sys
import logging as log
import datetime as dt
from time import sleep

cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)

video_capture = cv2.VideoCapture(0)
anterior = 0

while True:
    if not video_capture.isOpened():
        print('Unable to load camera.')
        sleep(5)
        pass

    # Capture frame-by-frame
    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30)
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    if anterior != len(faces):
        anterior = len(faces)
        log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))


    # Display the resulting frame
    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('s'): 

        check, frame = video_capture.read()
        cv2.imshow("Capturing", frame)
        cv2.imwrite(filename='saved_img.jpg', img=frame)
        video_capture.release()
        img_new = cv2.imread('saved_img.jpg', cv2.IMREAD_GRAYSCALE)
        img_new = cv2.imshow("Captured Image", img_new)
        cv2.waitKey(1650)
        print("Image Saved")
        print("Program End")
        cv2.destroyAllWindows()

        break
    elif cv2.waitKey(1) & 0xFF == ord('q'):
        print("Turning off camera.")
        video_capture.release()
        print("Camera off.")
        print("Program ended.")
        cv2.destroyAllWindows()
        break

    # Display the resulting frame
    cv2.imshow('Video', frame)

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()

輸出

在此處輸入圖片說明

另外,您可以查看我的 GitHub 代碼

這是一個使用筆記本電腦默認相機捕獲圖像的簡單程序。我希望這對所有人來說都是非常簡單的方法。

import cv2

# 1.creating a video object
video = cv2.VideoCapture(0) 
# 2. Variable
a = 0
# 3. While loop
while True:
    a = a + 1
    # 4.Create a frame object
    check, frame = video.read()
    # Converting to grayscale
    #gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    # 5.show the frame!
    cv2.imshow("Capturing",frame)
    # 6.for playing 
    key = cv2.waitKey(1)
    if key == ord('q'):
        break
# 7. image saving
showPic = cv2.imwrite("filename.jpg",frame)
print(showPic)
# 8. shutdown the camera
video.release()
cv2.destroyAllWindows 

你可以在這里看到我的github代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM