You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在dlib.image_window()中检测按键(如ESC键)?

如何在dlib窗口中检测按键(例如ESC键)?

我现在有这段使用dlib和OpenCV的代码,用来从摄像头获取画面并在dlib窗口显示:

import dlib
import cv2
from lib.capture import Capture
win = dlib.image_window()
cap = Capture() # Capture image from webcam
cap.start()
while(True):
    frame = cap.get() # Get current frame from webcam
    if frame is not None:
        frame = cv2.flip(frame, 1)
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) # Converting from RGB to BGR (as dlib.image_window requires)
        win.set_image(frame) # Display the resulting frame

请问怎么在这个dlib窗口里检测按键,比如按下ESC键就退出程序?


解决方案

其实dlib的image_window自带了get_key()方法来检测按键输入,咱们直接把这个逻辑加到循环里就行,判断是否按下了ESC键(对应的ASCII码是27)。

给你修改好的代码:

import dlib
import cv2
from lib.capture import Capture
win = dlib.image_window()
cap = Capture() # Capture image from webcam
cap.start()
while(True):
    frame = cap.get() # Get current frame from webcam
    if frame is not None:
        frame = cv2.flip(frame, 1)
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) # Converting from RGB to BGR (as dlib.image_window requires)
        win.set_image(frame) # Display the resulting frame
    
    # 检测按键输入
    key = win.get_key()
    # ESC键的ASCII码是27,按下就退出循环
    if key == 27:
        break

# 退出后别忘了清理资源
cap.stop()
win.close()

小提示:

  • win.get_key()会返回当前按下按键的ASCII码,没按键的时候返回-1,所以每次循环检查一下就行。
  • 要是你想检测其他按键,比如字母'a',可以直接写if key == ord('a'),这样比记ASCII码直观多了。
  • 最后一定要记得停止摄像头捕获和关闭窗口,不然可能会有资源残留的问题哦。

内容的提问来源于stack exchange,提问作者decadenza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:35:46