OpenCV Python: How to detect if a window is closed?

I tested on C++ using the getWindowProperty('image', WND_PROP_VISIBLE), but it does not work. So I used the WND_PROP_AUTOSIZE and it works.

I did like this:

cv::namedWindow("myTitle", WINDOW_AUTOSIZE);

while(1)
{
    cv::imshow("myTitle", myImage);


    if (cv::getWindowProperty("myTitle", WND_PROP_AUTOSIZE) == -1)
        break;
}

        if cv2.getWindowProperty('windowname',1) == -1 :
            break
        cv2.imshow('windowname', image)

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.


As of version 2.2 there is a simple solution (this is modified from the loop in hist.py):

    cv2.imshow('image',im)
    while True:
        k = cv2.waitKey(100) # change the value from the original 0 (wait forever) to something appropriate
...
        elif k == 27:
            print('ESC')
            cv2.destroyAllWindows()
            break        
        if cv2.getWindowProperty('image',cv2.WND_PROP_VISIBLE) < 1:        
            break        
    cv2.destroyAllWindows()

Tags:

Python

Opencv