How to check if an opencv window is closed

What you are trying to do can be achieved with cvGetWindowHandle():

The function cvGetWindowHandle returns the native window handle (HWND in case of Win32 and GtkWidget in case of GTK+). [Qt Backend Only] qt-specific details: The function cvGetWindowHandle returns the native window handle inheriting from the Qt class QWidget.

The idea is to get the handle of the window and then use specific platform API functions to check if that handle is still valid.

EDIT:

Or you could use the tradicional cvWaitKey() approach:

char exit_key_press = 0;
while (exit_key_press != 'q') // or key != ESC
{
   // retrieve frame

   // display frame

   exit_key_press = cvWaitKey(10);
}

You can use the cv::getWindowProperty method.

Do like that:

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

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

     // add this IF.
     if (cv::getWindowProperty("main", WND_PROP_AUTOSIZE) == -1)
         break;
}

When the windows be closed the getWindowProperty will return -1.


Suppose you have only one image window open, then clicking the 'x' button at its corner causes the waitkey() function to return a -1 value. Then check if the cvGetWindowHandle("name_of_the_window") function returns 0 or not. If it does return 0, then the window is actually closed. I have tested it in OpenCV3. But I am still not very clear on the reason why the waitkey() return -. I will much appreciate if anyone explains why this happens. [I don't know if my answer to this question will be relevant or not after such a long time. But hopefully if anyone else gets stuck with the same issue (like me), this answer might help them out.] Thanks.


This should do

#include <opencv2/opencv.hpp>

std::string mTitle = "title of my window";

while (cvGetWindowHandle(mTitle.c_str()))
{
   // ...
}

Tags:

C++

C

Opencv