OpenCV Python: How to detect if a window is closed?
OpenCV in Python provides a method cv2.getWindowProperty() to detect whether a window is closed or open. getWindowProperty() returns -1 if all windows are closed. This is one of the main problems we face while using the OpenCV package, sometimes it’s hard to detect whether the window is open or closed. when a user closes the window the method detects it.
Syntax: cv2.getWindowProperty(window_name, window_property)
- window_name : is the name of the window.
- window_property : it’s the window property to retrieve. we use flags.
flags which we can use:
- cv.2WND_PROP_VISIBLE : checks whether the window is visible and open.
- We read an image and then display it, window name is also specified in the cv2.imshow() method.
- Then we use a while loop to wait till the user presses ESC (exit key) to destroy all windows. After the window is destroyed the loop is broken.
- We make one final check to see whether the window is closed using getWindowProperty(), which takes the name of the window and the flag as parameters.
- If the window is closed the method returns -1.
In the below code as the window is closed it returns -1. even though the window is closed sometimes python doesn’t respond, using waitkey(1) closes the window instantly.
'esc is pressed closing all windows'
, cv2.WND_PROP_VISIBLE) <
"ALL WINDOWS ARE CLOSED"
esc is pressed closing all windows
ALL WINDOWS ARE CLOSED
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!