Python OpenCV namedWindow() Function (original) (raw)

Last Updated : 03 Jan, 2023

Python OpenCV namedWindow() method is used to create a window with a suitable name and size to display images and videos on the screen. The image by default is displayed in its original size, so we may need to resize the image for it to fit our screen.

Created windows are referred by their names and can also be used as a placeholder. The function does nothing If a window exists with the same name.

Syntax: cv2.namedWindow(window_name, flag)

Parameters:

Some of the flag values are:

Return Value: It doesn't return anything

Image used for all the below examples:

Example 1: Working of namedWindow() method with automaticallysets the window size

Python3 `

Python program to explain cv2.namedWindow() method

Importing OpenCV

import cv2

Path to image in local directory

path = 'C:/Users/art/OneDrive/Desktop/geeks.png'

Using cv2.imread() to read an image in default mode

image = cv2.imread(path)

Using namedWindow()

A window with 'Display' name is created

with WINDOW_AUTOSIZE, window size is set automatically

cv2.namedWindow("Display", cv2.WINDOW_AUTOSIZE)

using cv2.imshow() to display the image

cv2.imshow('Display', image)

Waiting 0ms for user to press any key

cv2.waitKey(0)

Using cv2.destroyAllWindows() to destroy

all created windows open on screen

cv2.destroyAllWindows()

`

Output:

Explanation:

Example 2: Manually change the window size

Python3 `

Python Program to explain namedWindow() method

Importing OpenCV

import cv2

Path to image in local directory

path = 'C:/Users/art/OneDrive/Desktop/geeks.png'

Using cv2.imread() to read an image in grayscale mode

image = cv2.imread(path, 0)

Using namedWindow()

A window with 'Display_Image' name is created

with WINDOW_NORMAL allowing us to have random size

cv2.namedWindow("Display_Image", cv2.WINDOW_NORMAL)

Using cv2.imshow() to display the image

cv2.imshow('Display_Image', image)

Waiting 0ms for user to press any key

cv2.waitKey(0)

Using cv2.destroyAllWindows() to destroy

all created windows open on screen

cv2.destroyAllWindows()

`

Output:

Note: When a user randomly changes size, the window size is changed dimensions of the image remain unchanged.