OpenCV 关闭特定键上的 window?

OpenCV to close the window on a specific key?

看起来很简单,但我无法让它工作,也找不到关于这个特定问题的任何问题(如果有,请在评论中指出)。

我正在显示图像并希望 window 在特定键上关闭,但奇怪的是,任何键都会导致它关闭

这是我的简单测试代码:

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()

(根据所说here

无论我按什么键,都会显示键码(ESC 为 27,SPACE 为 32,...)并且 window 关闭。

主要问题: 从未到达 if 子句(我通过将 print(k) 放入其中进行检查,但没有打印任何内容)。按下按键后,程序只是停止 运行 并且不会检查键码。

(我在 macOS Catalina 上,Python 3.8)

那么,我怎样才能真正让它等待特定的键呢?

试试这个,它会等待 'q' 键被按下。

import cv2

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

嗨。

只需这样做:

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()

我只是从中删除了 & 0xFF。这对我有用,但我不知道为什么这会造成问题,因为它只是用 FF.

应用和操作

从我的角度来看,您的程序刚刚终止,因此所有 windows 都隐式关闭,无论您按哪个键。

一个想法可能是在读取和检查按下的键的周围放置一个 while True 循环:

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

运行 这个,按一些键,最后 ESC,我得到以下输出:

103
100
102
27

另外,windows全部关闭,程序终止。

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

如果你想使用特定的密钥,你可以使用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