2014-12-13 33 views
0

我有一個問題: 我創建一個小程序,打開攝像頭,並進行臉部識別。 現在我想完成這項任務:按下按鍵(空格)後,程序必須進入階段2(面部識別)。爲此,我使用了cv2.waitkey()。主要的問題是,當我的功能按下空格鍵時,程序將進入階段2,但僅持續幾秒鐘(當空間被按下時它將進入階段2,當它被釋放時它會停止)。強制waitkey()做一個操作{OpenCV} {PY}

你有什麼建議嗎?

我會給我的意思的例子:

cam = cv2.VideoCapture(0) ##Load Cam 
cv2.namedWindow(name, cv2.WINDOW_AUTOSIZE) 

while True: 
    s, img = cam.read() 
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 

    cv2.imshow(name, img)  
    k = cv2.waitKey(1) 

    if k == 13: ## if return is pressed, on the screen will appear the text 'instruction',but when it 
       ## released the text disappear, and i don't want this... 
     s, img = cam.read() 
     gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
     cv2.putText(img,'instructions',(10,25), font, 0.7,(255,255,255),1,cv2.LINE_AA) 

     cv2.imshow(name, img) 

解決方案:

cv2.namedWindow(name, cv2.WINDOW_AUTOSIZE) 

while True: 
    s, img = cam.read() 
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 

    cv2.imshow(name, img)  
    k = cv2.waitKey(1) 

    if k == 13: 
     break 
while True: 
    s, img = cam.read() 
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    cv2.putText(img,'instructions',(10,25), font, 0.7,(255,255,255),1,cv2.LINE_AA) 

    cv2.imshow(name, img) 
+0

創建一個名爲phase的新變量,該變量用1初始化。然後如果k == 13:phase = 2。在循環中,詢問階段是1還是2,然後在每個階段中做任何你喜歡的事情。 – Micka 2014-12-13 17:27:42

+0

一個狀態機;) – berak 2014-12-13 17:35:11

回答

1

的問題是,你的條件指令是在 - 只要條件被評估爲真正他們只運行。爲避免這種情況,請考慮break退出循環並遵循進一步的說明。

cam = cv2.VideoCapture(0) ##Load Cam 
cv2.namedWindow(name, cv2.WINDOW_AUTOSIZE) 

while True: 
    s, img = cam.read() 
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 

    cv2.imshow(name, img)  
    k = cv2.waitKey(1) 

    if k == 13: 
     break 

s, img = cam.read() 
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
cv2.putText(img,'instructions',(10,25), font, 0.7,(255,255,255),1,cv2.LINE_AA) 
cv2.imshow(name, img) 
cv2.waitKey(1) 
+0

^^ final waitKey()失蹤! (否則最後的imshow()就不會) – berak 2014-12-13 17:20:35

+0

waitKey用於暫停(ms)間隔的執行並獲取一個鍵。它主要用於循環,因此'階段2'並不意味着任何(<=>抽取圖像時沒有循環) – Gabe 2014-12-13 17:23:20

+0

..它也封裝了窗口的內部消息循環。沒有它,窗口將不會更新。只是嘗試自己! – berak 2014-12-13 17:24:36

1

也許你需要某種形式的 '超時' 的?

cam = cv2.VideoCapture(0) ##Load Cam 
cv2.namedWindow(name, cv2.WINDOW_AUTOSIZE) 

timeout = 0 
while True: 
    s, img = cam.read() 

    if timeout > 0: # show message as long as timeout is valid 
     cv2.putText(img,'instructions',(10,25), font, 0.7,(255,255,255),1,cv2.LINE_AA) 
     timeout = timeout - 1 

    cv2.imshow(name, img) 

    k = cv2.waitKey(1)  
    if k == 13:     
     timeout = 100 # show message for 100 frames 
    if k == 27:     
     break   # bail out on 'escape'