Creating a Window

First, we want to show an image on the screen using HighGUI. The function that does this for us is cvNamedWindow(). The function expects a name for the new window and one flag. The name appears at the top of the window, and the name is also used as a handle for the window that can be passed to other HighGUI functions. The flag indicates if the window should autosize itself to fit an image we put into it. Here is the full prototype:

int cvNamedWindow(
    const char* name,
    int         flags = CV_WINDOW_AUTOSIZE
);

Notice the parameter flags. For now, the only valid options available are to set flags to 0 or to use the default setting, CV_WINDOW_AUTOSIZE. If CV_WINDOW_AUTOSIZE is set, then HighGUI resizes the window to fit the image. Thereafter, the window will automatically resize itself if a new image is loaded into the window but cannot be resized by the user. If you don't want autosizing, you can set this argument to 0; then users can resize the window as they wish.

Once we create a window, we usually want to put something into it. But before we do that, let's see how to get rid of the window when it is no longer needed. For this we use cvDestroyWindow(), a function whose argument is a string: the name given to the window when it was created. In OpenCV, windows are referenced by name instead of by some unfriendly (and invariably OS-dependent) "handle". Conversion between handles and names happens under the hood of HighGUI, so you needn't worry about it.

Having said that, some people do worry about it, and that's OK, too. For those people, HighGUI provides the following functions:

void*       cvGetWindowHandle( const char* name );
const char* cvGetWindowName( void* window_handle );

These functions allow us to convert back and forth between the human-readable names preferred by OpenCV and the "handle" style of reference used by different window systems.[40]

To resize a window, call (not surprisingly) cvResizeWindow():

void cvResizeWindow(
    const char* name,
    int         width,
    int         height
);

Here the width and height are in pixels and give the size of the drawable part of the window (which are probably the dimensions you actually care about).



[40] For those who know what this means: the window handle returned is a HWND on Win32 systems, a Carbon WindowRef on Mac OS X, and a Widget* pointer on systems (e.g., GtkWidget) of X Window type.

Get Learning OpenCV now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.