OpenCV Python:如何检测窗口是否关闭? [英] OpenCV Python: How to detect if a window is closed?
问题描述
我有以下代码:
total_frames = 50
cv2.cv.NamedWindow("Dragonfly Simulation")
cv2.cv.StartWindowThread()
for i in range(total_frames):
# do stuff
img_name = # something
img = cv2.cv.LoadImage(img_name)
cv2.cv.ShowImage("Dragonfly Simulation", img)
cv2.cv.WaitKey(2)
cv2.cv.DestroyWindow("Dragonfly Simulation")
cv2.cv.WaitKey(1)
# rest of code
那它是怎么做的:
- 打开一个窗口
- 循环显示在窗口上的图像
- 完成后,关闭窗口
- 运行其余代码
但是在这种情况下,我之前已经给出了total_frame
.我不要那个.
However in this case I have the total_frame
given before. I don't want that.
相反,我需要执行以下操作的代码:
Instead, I want a code that does the following:
- 打开一个窗口
- 循环显示在窗口上的图像
- 等待用户关闭该窗口
- 当用户关闭该窗口时,退出循环,继续执行其余代码.
但是,我在OpenCV中找不到可以检测用户何时关闭窗口的功能.有人可以建议解决方法吗?
However, I cannot find a function in OpenCV that can detect when user closes a window. Can anyone suggest a workaround please?
推荐答案
除了等待按键,我只是在寻找一种使用窗口的X
按钮检测窗口何时关闭的方法,但是我在任何地方都找不到答案(IsWindowVisible
和cvGetWindowHandle
在Python cv2
模块中不可用).
I was just looking for a way to detect when the window has been closed using the X
button of the window in addition to waiting for a key press, but I couldn't find an answer anywhere (IsWindowVisible
and cvGetWindowHandle
are not available in the Python cv2
module).
所以我玩了,这是它的工作方式:
So I played around and this is how it works:
while cv2.getWindowProperty('window-name', 0) >= 0:
keyCode = cv2.waitKey(50)
# ...
cv2.getWindowProperty()
在关闭窗口后立即返回-1
.
cv2.getWindowProperty()
returns -1
as soon as the window is closed.
有关说明,请参见 0
的标志是全屏属性,但实际上使用哪个标志都没有关系,一旦关闭窗口,它们都将变为-1
.
For explanation, see the documentation for the enumeration of cv::WindowPropertyFlags
: getting the flag with index 0
is the fullscreen property, but actually it doesn't matter which flag to use, they all become -1
as soon as the window is closed.
这篇关于OpenCV Python:如何检测窗口是否关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!