3

OpenCV version 2.2, C++ interface.

When showing a loaded image in a window with following code snippet

cvStartWindowThread();

Mat image;
image = imread(argv[1], CV_LOAD_IMAGE_COLOR);   // Read the file

if(! image.data )                              // Check for invalid input
{
    cout <<  "Could not open or find the image" << std::endl ;
    return -1;
}

namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image );   

while( 1 ) {
    if( cvWaitKey(100) == 27 ) break;
}

I face a problem when closing image by pressing the close button with the mouse, instead of using escape key.

In this case my program will be blocked in the while and the only way to exit it is to stop execution, which obviously is not desired.

Is there any function that controls if the close button has been pressed? In that way I could add it in the while loop as this:

E.g.

while( 1 ) {
    if( cvWaitKey(100) == 27 ) break;
    if( cvCloseButtonPressed == 1) break; <--- purely invented method I'm looking for...
}
Matteo
  • 7,924
  • 24
  • 84
  • 129

3 Answers3

11

You can use cvGetWindowHandle() function to get handle of your named window. Window handle is an OS specific feature. An example for win32 looks like this:

HWND hwnd = (HWND)cvGetWindowHandle("Display window");
while(IsWindowVisible(hwnd)) {
    if( cvWaitKey(100) == 27 ) break;
}

IsWindowVisible() is a winapi function, so you may want to add #include <windows.h>

yuyoyuppe
  • 1,582
  • 2
  • 20
  • 33
  • @MichalKottman actually it's working also on linux with g++ compiler, with just a little different sintax. This is the function I was looking for, thanks! – Matteo Mar 27 '12 at 15:27
  • Note: It seems not working for Windows + MinGW compiler, due to a bug in opencv's implementation on MinGW?? I don't know when it will be fixed, or perhaps it is already fixed (since I don't regularly update to the most recent version). – Robin Hsu Jan 06 '16 at 09:25
3

Instead of showing the image in a loop, try showing it only once:

imshow("Display window", image);
waitKey(0);

The waitKey(0) means "wait forever".

Michal Kottman
  • 16,375
  • 3
  • 47
  • 62
0
if (!cvGetWindowHandle(windowName.c_str())) {
    destroyAllWindows();
    exit(1);
}
Nathan B
  • 1,625
  • 1
  • 17
  • 15