dessskris dessskris - 1 year ago 292
Python Question

OpenCV Python: How to detect if a window is closed?

I have the following code:

total_frames = 50"Dragonfly Simulation")
for i in range(total_frames):
# do stuff
img_name = # something
img ="Dragonfly Simulation", img)"Dragonfly Simulation")
# rest of code

So what does it do:

  1. Opens a window

  2. In a loop, shows an image on the window

  3. Once finished, closes the window

  4. Runs the rest of the code

However in this case I have the
given before. I don't want that.

Instead, I want a code that does the following:

  1. Opens a window

  2. In a loop, shows an image on the window

  3. Waits for the user to close that window

  4. When the user closes that window, exit loop, goes on with the rest of the code.

However, I cannot find a function in OpenCV that can detect when user closes a window. Can anyone suggest a workaround please?

Answer Source

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() returns -1 as soon is the window is closed.

See the documentation for the enumeration of cv::WindowPropertyFlags for how this works: 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download