我有一个问题: 我创建了一个小程序,打开网络摄像头并进行人脸识别。 现在我想完成这个任务:当按下一个键(空格)时,程序必须进入第2阶段(人脸识别)。为此,我使用了cv2.waitkey()。主要的问题是,当按下空格时我的功能,程序将进入阶段2,但只持续几秒钟(当按下空格时它进入阶段2,并且当它被释放时它停止)。
你有什么建议吗?
我将举例说明我的意思:
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 :(得分:1)
也许你需要某种“超时”#39; ?
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'
答案 1 :(得分:1)
问题在于您的条件说明属于循环 - 只有在条件评估为 true 时才会运行它们。为避免这种情况,请考虑中断退出循环并遵循进一步说明。
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)