Thursday, December 26, 2024
Google search engine
HomeLanguagesOpenCV Python: How to detect if a window is closed?

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)

parameters:

  • 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.
  • cv2.WND_PROP_TOPMOST
  • cv2.WND_PROP_OPENGL
  • cv2.WND_PROP_ASPECT_RATIO
  • cv2.WND_PROP_AUTOSIZE
  • cv.WND_PROP_FULLSCREEN

Approach

  • 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.

Python3




# importing packages
import cv2
  
# reading image
img = cv2.imread('sunset.jpeg')
cv2.imshow('sunset', img)
while True:
    
    # it waits till we press a key
    key = cv2.waitKey(0)
  
    # if we press esc
    if key == 27:
        print('esc is pressed closing all windows')
        cv2.destroyAllWindows()
        break
  
if cv2.getWindowProperty('sunset', cv2.WND_PROP_VISIBLE) < 1:
    print("ALL WINDOWS ARE CLOSED")
cv2.waitKey(1)


Output:

esc is pressed closing all windows
ALL WINDOWS ARE CLOSED
-1
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments