OpenCV close window with mouse issue
Asked Answered
W

3

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...
}
Wordsworth answered 27/3, 2012 at 10:1 Comment(0)
R
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>

Raby answered 27/3, 2012 at 10:18 Comment(2)
@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!Wordsworth
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).Weirdo
D
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".

Desmond answered 27/3, 2012 at 10:32 Comment(0)
W
0
if (!cvGetWindowHandle(windowName.c_str())) {
    destroyAllWindows();
    exit(1);
}
Wangle answered 16/8, 2017 at 6:42 Comment(1)
Add a bit more text so readers can understand what you're trying to achieve.Wightman

© 2022 - 2024 — McMap. All rights reserved.