-1

I start the script from the terminal with Python 3.8.10 python3 myprog.py. I have two problems:

  1. When I run it as is, it does prints -1 indefinitely, but when I press s it never gets inside the if.
  2. If I comment out print(key) after the waitKey(1) the program just waits for an input. It allows me to enter many characters and I have to press Enter. But, after pressing Enter it just adds a new line and waits for input again.

What am I doing wrong? Why do I get this behaviour in those two cases?

import cv2
def main():
    while True:
        key = cv2.waitKey(1)
        print(key)
        if 's' == chr(key & 255):
            print("--------------INSIDE IF --------------")

if __name__ == '__main__':
    main()
theateist
  • 13,879
  • 17
  • 69
  • 109
  • 1
    From the docs: _The function only works if there is at least one HighGUI window created and the window is active._ In your example, there's no window so the event isn't processed. Check: https://docs.opencv.org/4.x/d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7 – stateMachine Jun 09 '23 at 23:59
  • the "entering characters" and the "newline" is behavior from your terminal program. this behavior is usual on linux but not on windows (for example). OpenCV, here, doesn't notice your inputs at all, because they aren't inputs to any OpenCV ***GUI***. – Christoph Rackwitz Jun 10 '23 at 09:32

1 Answers1

1

cv.waitKey() does not work on terminal input.

It requires OpenCV GUI (cv.imshow(), cv.namedWindow(), ...). You do not appear to use any OpenCV GUI. Since you appear to want terminal input, you can't use cv.waitKey().

You need to use something else like Python's built-in input(). input() prompts the user for a line of input. It is not suitable for detecting whether a key was pressed.

To detect whether a key was pressed in your terminal, there are various solutions. One such question, with answers, is Python cross-platform listening for keypresses?

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36