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:
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:
However, I cannot find a function in OpenCV that can detect when user closes a window. Can anyone suggest a workaround please?
getWindowProperty() to detect whether a window is closed or open. getWindowProperty() returns -1 if all windows are closed.
Using the waitKey() Function in OpenCV If we press a key from the keyboard while the image window is active, the window will close.
0 – wait indefinitely cv2. destroyAllWindows() simply destroys all the windows we created. To destroy any specific window, use the function cv2. destroyWindow() where you pass the exact window name.
Python OpenCV namedWindow() method is used to create a window with a suitable name and size to display images and videos on the screen. The image by default is displayed in its original size, so we may need to resize the image for it to fit our screen.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With