首页 > 解决方案 > cv2.waitKey() 适用于“q”键,但不适用于任何其他键

问题描述

我有这段代码,它实际上是我的手语识别项目之一的一部分。因此,我在每一帧中获取用户的手部图像并将其传递给模型并在屏幕上显示对标志的预测,并且我添加了一个功能,如果用户按下“s”键,那么预测将被附加到字符串 sen 和类似地我将在屏幕上显示该字符串 sen 。

但是在运行代码之后,对于键'q'它会关闭窗口而没有任何问题但是当我按下键's'时没有任何反应。

而不是 key 's' ,我尝试了与其他键相同的操作,但仍然没有任何反应。

这是代码:

import cv2
import numpy as np
from model import predict


def capture():
    sen = ''
    cap = cv2.VideoCapture(0)
    while True:

        ret, frame = cap.read()
        frame = cv2.flip(frame, 1)
        frame_height = 480
        frame_width = 640
        # a standard frame window of size 640*480
        frame = cv2.resize(frame, (frame_width, frame_height))

        # drawing a rectangle in a frame which will capture hand
        cv2.rectangle(frame, (300, 100), (500, 300), (0, 300, 0), 2)

        # rectangle of background of text s
        cv2.rectangle(frame, (0, 0), (300, 50), (0, 0, 0), -1)
        frame = cv2.putText(frame, 'press q to exit', (30, 30), cv2.FONT_HERSHEY_SIMPLEX,
                            1, (255, 255, 255), 1, cv2.LINE_AA)

        # region of interest i.e rectangle which we drawn earlier
        roi = frame[100:300, 300:500]
        roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
        roi = cv2.GaussianBlur(roi, (5, 5), 0)


        # applying edge detection on roi
        roi_edges = cv2.Canny(roi, 100, 200)
        # cv2.imshow('Edges', roi_edges)


        # to make roid_edges of shape (200,200,1) , specifying color channel which is required for model
        img = np.expand_dims(roi_edges, axis=2)
        cv2.imshow('input for model', img)

        frame = cv2.putText(frame, predict(img), (300, 400), cv2.FONT_HERSHEY_SIMPLEX,
                            1, (255, 255, 255), 1, cv2.LINE_AA)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        elif cv2.waitKey(1) & 0xFF == ord('s'):
            sen += predict(img)
            print(sen)

        # printing whole sentence i.e. sen
        frame = cv2.putText(frame, sen , (300, 500),
                            cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1, cv2.LINE_AA)

        cv2.imshow('Smile', frame)

    cv2.destroyAllWindows()
    cap.release()


capture()

那么这里可能是什么问题呢?

标签: pythonopencv

解决方案


cv2.waitKey(1)问题是您多次调用该方法,在这种情况下您应该使用变量 forcv2.waitKey(1)因为等待是两个函数调用都读取键盘缓冲区,因此只有当软件在第一个评估后立即收到 s 键时才执行第二个分支分支(q)。这是示例代码:

keys = cv2.waitKey(1) & 0xFF
if keys == ord('q'):
    break
elif keys == ord('s'):
    print('s is pressed')

推荐阅读