Python OpenCV – namedWindow()函数
Python OpenCV namedWindow() 方法用于创建一个具有合适名称和大小的窗口,以在屏幕上显示图像和视频。默认情况下,图像以其原始大小显示,因此我们可能需要调整图像大小以使其适合我们的屏幕。
创建的窗口以其名称引用,也可以用作占位符。如果存在同名的窗口,则该函数不执行任何操作。
Syntax: cv2.namedWindow(window_name, flag)
Parameters:
- window_name: Name of the window that will display image/video
- flag: Represents if window size is automatically set or adjustable.
Some of the flag values are:
- WINDOW_NORMAL – Allows to manually change window size
- WINDOW_AUTOSIZE(Default) – Automatically sets the window size
- WINDOW_FULLSCREEN – Changes the window size to fullscreen
Return Value: It doesn’t return anything
用于以下所有示例的图像:
示例 1:自动使用 namedWindow() 方法 设置窗口大小
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", cv.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()
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", cv.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()
输出:
说明:
- 在这段代码中,为了使用namedWindow函数,引入了OpenCV的Python库。
- 然后通过使用 cv2.imread,来自特定位置(路径)的文件在默认模式下加载到 'image' 变量中。
- 现在创建一个带有“显示”名称的窗口,并且使用了命名窗口的图像自动大小。
- 通过使用 cv2.imshow,自定义窗口显示在屏幕上。等待 0 毫秒后,用户可以通过按键盘上的任意键来销毁所有窗口。
示例2:手动更改窗口大小
蟒蛇3
# 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", cv.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()
输出:
注意:当用户随机改变尺寸时,窗口尺寸改变后图像的尺寸保持不变。