OpenCV to close the window on a specific key?

Viewed 8201

It seems really simple, but I can't get it to work and the couldn't find any questions regarding this particular issue (if there are, please point out in the comments).

I am showing an image and want the window to close on a specific key, but strangely, any key causes it to close.

This is my simple code for testing:

img = cv2.imread("MyImage.png")
cv2.imshow('My Image', img)
k = cv2.waitKey(0) & 0xFF
print(k)
if k == 27:  # close on ESC key
    cv2.destroyAllWindows()

(based on what is said here)

No matter what key I press, the key code is shown (27 for ESC, 32 for SPACE, ...) and the window closes.

The main problem: the if clause is never reached (I checked by putting the print(k) inside it, and nothing is printed). After the key press, the program simply stops running and it doesn't get to checking the key code.

(I am on macOS Catalina, with Python 3.8)

So, how do I actually make it wait for a specific key?

4 Answers

From my point of view, your program just terminates, and thus all windows are implicitly closed, regardless of which key you press.

One idea might be to put a while True loop around the reading and checking of the pressed key:

import cv2

img = cv2.imread('path/to/your/image.png')
cv2.imshow('My Image', img)
while True:
    k = cv2.waitKey(0) & 0xFF
    print(k)
    if k == 27:
        cv2.destroyAllWindows()
        break

Running this, pressing some keys, and finally ESC, I get the following output:

103
100
102
27

Also, all windows are closed, and the program is terminated.

----------------------------------------
System information
----------------------------------------
Platform:     Windows-10-10.0.16299-SP0
Python:       3.8.5
OpenCV:       4.4.0
----------------------------------------

Try this, it will wait for key 'q' to be pressed.

import cv2

img = cv2.imread("MyImage.png")
cv2.imshow('My Image', img)
if cv2.waitKey(0) & 0xFF == ord('q'):
    cv2.destroyAllWindows()

HIH.

Simply do this:

img = cv2.imread("MyImage.png")
cv2.imshow('My Image', img)
k = cv2.waitKey(0)
print(k)
if k == 27:  # close on ESC key
    cv2.destroyAllWindows()

I have simply removed & 0xFF from it. This works for me but I don't why this would pose a problem as it is simply applying and operation with FF.

If you want to use specific key, you can use ord():

img = cv2.imread('path/to/your/image.png')
cv2.imshow('My Image', img)

while True:
    k = cv2.waitKey(0) & 0xFF
    print(k)
    if k == ord('c'): # you can put any key here
        cv2.destroyAllWindows()
        break
Related