【问题标题】:Force waitkey() to do an operation {OpenCV}{PY}强制 waitkey() 执行操作 {OpenCV}{PY}
【发布时间】:2014-12-13 17:10:16
【问题描述】:

我有一个问题: 我创建了一个小程序来打开网络摄像头并进行人脸识别。 现在我想做这个任务:当按下一个键(空格)时,程序必须进入阶段 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)

【问题讨论】:

  • 创建一个名为 phase 的新变量,初始化为 1。然后如果 k == 13:phase = 2。在你的循环中,然后询问 phase 是 1 还是 2,并在每个变量中做任何你喜欢的事情那些阶段。

标签: opencv


【解决方案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)

【讨论】:

  • ^^ 最终 waitKey() 丢失! (否则最后一个 imshow() 不会)
  • waitKey 用于暂停执行(毫秒)间隔并获取密钥。它主要用于循环,因此“阶段 2”并不意味着任何( 获取图像时不涉及循环)
  • .. 它还封装了窗口的内部消息循环。没有它,窗口将不会更新。自己试试吧!
  • 谢谢你给我解决方案的提示!!
  • @berak 是的,你是对的。没有检查聚合方法。
【解决方案2】:

也许您需要某种“超时”?

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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 2015-10-24
    • 2021-01-27
    相关资源
    最近更新 更多