倒計時器使用開放CV與Python我創建它採用了跟蹤對象(這在目前是藍筆),當虛擬鍵盤所述被跟蹤對象在矩形邊界內進行打印(此時我只有一個矩形,當對象相交時打印出「A」)。這一切都工作正常,但正如你可以想象,當對象進入矩形的邊界內的字母很快打印出多次。
我的問題
我需要一種方法來確保用戶能夠正確輸入正確的密鑰,所述鍵字符打印出來的原先設想的數額。我打算這樣做的方式是創建一個定時器,只有當對象在矩形內部持續3秒鐘時纔會註冊「按鍵」。然而,我實際上正在創建計時器時遇到了麻煩,但這可能是非常簡單的事情,但實際上我很難提出解決方案。
我曾嘗試到目前爲止
我已經創建了一個簡單的for循環,其設置一個整數變量爲一個高值,然後一旦對象與所述矩形相交由一個那麼一旦降低了整數它等於0打印字母。代碼如下:
n = 600000
while n > 0:
n=n-1
print("A")
這樣做的問題是,該方案几乎涉及到當它進入循環停滯,這使程序令人難以置信的跳躍和視覺效果慘不忍睹。我認爲這是由代碼執行的常量減法造成的,因此這不是完成我的目標的好方法。
我已經使用time.sleep()並將其設置爲說3秒然而,因爲這會暫停程序再次是不適合作爲視覺上在屏幕嘗試的另一種方法是冷凍當物體進入矩形。
我的代碼
import cv2
import numpy as np
import time
import os
cap = cv2.VideoCapture(0)
pressed = 0
while(1):
# read the frames
_,frame = cap.read()
# smooth it
frame = cv2.blur(frame,(3,3))
# convert to hsv and find range of colors
hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
thresh = cv2.inRange(hsv,np.array((75, 96, 205)), np.array((144, 233, 255)))
thresh2 = thresh.copy()
# find contours in the threshold image
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
# finding contour with maximum area and store it as best_cnt
max_area = 0
for cnt in contours:
area = cv2.contourArea(cnt)
if area > max_area:
max_area = area
best_cnt = cnt
# finding centroids of best_cnt and draw a circle there
M = cv2.moments(best_cnt)
cx,cy = int(M['m10']/M['m00']), int(M['m01']/M['m00'])
cv2.circle(frame,(cx,cy),5,255,-1)
if cx < 100 and cy < 100:
cv2.rectangle(frame,(10,0),(100,100),(255,0,0),3)
pressed = 1
if pressed == 1:
n = 9000000
while n > 0:
n=n-1
print("A")
pressed = 0
else:
cv2.rectangle(frame,(10,0),(100,100),(0,255,0),3)
pressed = 0
# Show it, if key pressed is 'Esc', exit the loop
cv2.imshow('frame',frame)
cv2.imshow('thresh',thresh2)
if cv2.waitKey(33)== 27:
break
# Clean up everything before leaving
cv2.destroyAllWindows()
cap.release()
任何建議,將不勝感激 感謝。
有關使用狀態/標誌,而不是一個計時器什麼?並在筆*離開跟蹤的矩形時觸發事件。那個計時器的想法也不會擴展到很多字母.. – berak