OpenCV Python: How to detect if a window is closed? (original) (raw)

Last Updated : 03 Jan, 2023

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:

flags which we can use:

Approach

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

import cv2

img = cv2.imread( 'sunset.jpeg' )

cv2.imshow( 'sunset' , img)

while True :

`` key = cv2.waitKey( 0 )

`` 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

Similar Reads

Getting Started






Working with Images - Getting Started








Working with Images - Image Processing
































Working with Images - Feature Detection and Description









Working with Images - Drawing Functions









Working with Videos










Applications and Projects


















OpenCV Projects