pythonopencv

OpenCV cv2.waitKey() cannot detect the Delete key, what should I do?


I am using cv2.waitKey(1) & 0xFF to capture key events, but I found that it cannot correctly detect the Delete key. My current code is as follows:

import cv2

while True:
    key = cv2.waitKey(1)
    if key != -1: # -1 : timeout/no key event
        print(f"Key pressed: {key}")

    if key == 127: 
        print("Delete key detected!")
        break

cv2.destroyAllWindows()

However, when I run this code and press the Delete key, it is not detected.

Environment: Windows 10, Python 3.9, OpenCV 4.5.5

Issue: key == 127 does not work

Expected Behavior: When I press Delete, it should print Delete key detected.

Questions:


Solution

  • Use waitKeyEx().

    It'll give you every bit of information the operating system has to give. waitKey does not, it only gives you the lowest eight bits.

    On Windows, Del will cause waitKey to return 0, but waitKeyEx() will return 0x2e0000. waitKeyEx() will return other values on other systems.


    Never ever use that & 0xFF pattern. Never ever. Not with waitKeyEx, not with waitKey. That operation is utterly redundant. waitKey does that internally already, and with waitKeyEx the point is to get those bits, not discard them.

    This operation also mangles the return value indicating "no key event", which is properly -1, and makes it 255.