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

OpenCV中cv2.waitKey(1)无法识别按键输入问题求助

解决cv2.waitKey无法识别按键的问题

问题根源及修复方案

  • 字符串与整数比较错误
    代码中if key & 0xff == ('q')一行存在类型不匹配问题:key & 0xff返回整数,而'q'是字符串,两者永远无法匹配。需修改为与其他按键判断一致的写法:

    if key & 0xff == ord('q'):
        break
    
  • Matplotlib显示阻塞OpenCV事件循环
    循环内调用的plt.show()会完全阻塞程序,直到关闭Matplotlib窗口才会继续执行,导致cv2.waitKey()无法实时捕获按键。如果不需要Matplotlib预览,直接删除plt.imshow(frame)和plt.show()这两行;若必须保留Matplotlib显示,需改用非阻塞渲染方式,或仅保留OpenCV窗口用于按键交互。

  • 可选优化:过滤无效按键值
    cv2.waitKey(1)在无按键输入时返回-1,先判断key != -1再处理按键逻辑,可避免无效判断:

    key = cv2.waitKey(1)
    if key != -1:
        # 按键判断逻辑
    

    另外,保存帧时建议使用frame.copy(),避免后续帧修改影响已存入列表的内容。


修正后的完整代码

import cv2

CAMERA = cv2.VideoCapture(0)
camera_height = 500

raw_frames_type_1 = []
raw_frames_type_2 = []
raw_frames_type_3 = []
raw_frames_type_4 = []

while CAMERA.isOpened():
    ret, frame = CAMERA.read()
    if not ret:
        break

    frame = cv2.flip(frame, 1)

    aspect = frame.shape[1] / float(frame.shape[0]) 
    res = int(aspect * camera_height)
    frame = cv2.resize(frame, (res, camera_height))

    cv2.rectangle(frame, (300, 75), (650, 425), (0,255,0), 2)
    
    cv2.imshow("Capturing", frame)

    key = cv2.waitKey(1)

    if key != -1:
        if key & 0xff == ord('q'):
            break
        elif key & 0xFF == ord('1'):
            raw_frames_type_1.append(frame.copy())
        elif key & 0xFF == ord('2'):
            raw_frames_type_2.append(frame.copy())
        elif key & 0xFF == ord('3'):
            raw_frames_type_3.append(frame.copy())
        elif key & 0xFF == ord('4'):
            raw_frames_type_4.append(frame.copy())

CAMERA.release()
cv2.destroyAllWindows()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 03:42:43