Answer a question

I have the following code:

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

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 total_frame 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?

Answers

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 as the window is closed.


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.


Note: This might only work for certain GUI backends. Notably, it will not work with the GTK backend used in Debian/Ubuntu packages. To use the Qt backend instead, you have to install opencv-python via pip.

Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐