OpenCV: Create window, display and save images

Table of contents

cv2.waitKey()

Window creation: cv2.namedWindow()

Window resizing: cv2.resizeWindow()

Window display: cv2.imshow()

Close the window: cv2.destroyAllWindows()

Image reading: cv2.imread()

Image saving: cv2.imwrite()

code example


cv2.waitKey()

int waitKey(int delay=0)

The basic logic of waitKey(): it will wait to receive a value from the keyboard within a certain period of time;The return value is the ASCII of the keyboard key Value; delay represents the waiting time (ms).

If delay<=0, it means that the program will wait for the user's key event indefinitely.

If there is no key input during the waiting period, -1 is returned.

常见:cv2.waitKey(1000) & 0xFF == ord(‘q’) 

Explanation:ord('q') : Returns the ascii code of q. The range of waitKey return value is (0-255). The value can be limited to  cv2.waitKey(1) & 0xFF  (0-255) Avoid strange bugs in the program.

Common cases:

key = cv2.waitKey(0)
if key & 0xFF == ord('q'):
    exit()

Window creation: cv2.namedWindow()

void nameWindow(const string& winname,int flags = WINDOW_AUTOSIZE)

winname: window name; flags: window identifier, the default is WINDOW_AUTOSIZE.

flags

effect
WINDOW_NORMAL After displaying the image, allow the user to resize the window at will
WINDOW_AUTOSIZE Show window based on image size, do not allow user to resize
WINDOW_FREERATIO Window size adaptive proportion
WINDOW_KEEPRATIO Maintain image proportions

Window resizing: cv2.resizeWindow()

用法:cv2.resizeWindow(window_name, width, height)

Does not return any value;

  • window_name: The name of the window in which the image/video will be displayed
  • width:                New window width (integer type)
  • height:               New window height (integer type)

Window display: cv2.imshow()

cv2.imshow(winname, img)

winname: A string representing the name of the window in which the image is to be displayed.
img: It is the image to be displayed.

It returns no value. When displayed, the image value range is mapped to [0, 255].


Close the window: cv2.destroyAllWindows()

        You can call destroyWindow() or destroyAllWindows() to close the window and de-allocate any associated memory usage. For a simple program, you do not really have to call these functions because all the resources and windows of the application are closed automatically by the operating system upon exit.
        

        You can call destroyWindow() or destroyAllWindows() to close the window and deallocate any associated memory usage. For a simple program, it is not actually necessary to call these functions because the operating system automatically closes all the application's resources and windows when exiting

void destroyWindow(const string& winname);

winname: The name of the window that needs to be closed


Image reading: cv2.imread()

imread(const string& filename, int flags = IMREAD_COLOR)

Return value: mat format, returns the read image.

Parameter 1 filename: The name of the image file to be read. You can use a relative path or an absolute path, but it must have a complete file extension. (Picture format suffix).

Parameter 2 flags: A read flag used to select the way to read pictures. The default value is IMREAD_COLOR, and the setting of the flag value It depends on what color format is used to read the image.

flags illustrate
IMREAD_UNCHANGED If set, returns the loaded image as-is (with alpha channel, otherwise it will be cropped)
IMREAD_GRAYSCALE If set, always converts the image to a single-channel grayscale image (codec-internal conversion).
IMREAD_COLOR If set, always convert the image to a 3-channel BGR color image.
IMREAD_ANYDEPTH If set, returns a 16-bit/32-bit image when the input has the corresponding depth, otherwise converts it to 8-bit.
IMREAD_ANYCOLOR If set, reads the image in any possible color format.
IMREAD_LOAD_GDAL If set, use the gdal driver to load the image
IMREAD_REDUCED_GRAYSCALE_2 If set, always converts the image to a single-channel grayscale image, reducing the image size by 1/2.
IMREAD_REDUCED_COLOR_2 If set, the image is always converted to a 3-channel BGR color image with the image size reduced by 1/2.
IMREAD_REDUCED_GRAYSCALE_4 If set, always converts the image to a single channel grayscale image, reducing the image size by 1/4
IMREAD_REDUCED_COLOR_4 If set, always converts the image to a 3-channel BGR color image, reducing the image size by 1/4
IMREAD_REDUCED_GRAYSCALE_8 If set, always converts the image to a single-channel grayscale image, reducing the image size by 1/8.
IMREAD_REDUCED_COLOR_8 If set, the image is always converted to a 3-channel BGR color image, reducing the image size by 1/8.
IMRED_IGNORE_ORIENTATION If set, do not rotate the image based on EXIF's orientation flags.

Image saving: cv2.imwrite()

cv2.imwrite(filename,img,params)

filename: The address where the image is saved, including the image file name and suffix.

img: Array of images to be saved.

The imwrite function selects the format of the image based on the file extension. Generally, only 8-bit single-channel or 3-channel (with BGR channel order) images can be saved using this function, with the following exceptions:

▶For PNG, JPEG2000 and TIFF formats, 16-bit unsigned (CV_16U) images can be saved.


▶32-bit floating point (CV_32F) images can be saved in PFM, TIFF, OpenEXR and Radiance HDR formats; 3-channel (CV_32FC3) TIFF images are saved using LogLuv high dynamic range encoding (4 bytes per pixel).


▶You can save PNG images with Alpha channel using this feature. To do this, create an 8-bit (or 16-bit) 4-channel image BGRA, with the alpha channel last. Fully transparent pixels should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535.

If the format, depth or channel order is different, use Mat::convertTo and cv::cvtColor to convert before saving. Alternatively, use the generic FileStorage I/O functions to save the image to XML or YAML format.

params: Save the image in a specific format.

cv2.CV_IMWRITE_JPEG_QUALITY: Set the image quality in .jpeg/.jpg format, the value is 0-100 (default value 95), the larger the value, the higher the image quality;


cv2.CV_IMWRITE_WEBP_QUALITY: Set the image quality in .webp format, the value is 0-100;


cv2.CV_IMWRITE_PNG_COMPRESSION: Set the compression ratio of .png format images, the value is 0-9 (default value 3), the larger the value, the greater the compression ratio.

Return value: Returns True if the save is successful, otherwise returns False.


code example

import cv2
# 读取图片 211*400
img = cv2.imread('D:\Tom.jpg', flags = cv2.IMREAD_COLOR)
# 创建窗口,命名为Demo
cv2.namedWindow('Demo', cv2.WINDOW_NORMAL)
# 调整窗口大小w
cv2.resizeWindow('Demo', 422, 800)
while 1:
    # 在窗口内显示图片
    cv2.imshow('Demo', img)
    # 等待按键结束窗口
    key = cv2.waitKey(0)
    # 按 q 退出程序
    if key & 0xFF == ord('q'):
        break
    # 按 s 保存图片
    elif key & 0xFF == ord('s'):
        cv2.imwrite('D:\Demo.jpg', img)
#关闭所有窗口,释放资源
cv2.destroyAllWindows()


reference:

cv2.waitKey()_Changqing’s Blog-CSDN Blog

Entry-level understanding of cv2.waitKey_There is a strong blog on the mountain-CSDN blog

python cv2.waitKey() function_Mantian and Feixue's blog-CSDN blog

3-2 How to create a display window through OpenCV_bilibili_bilibili

Summary of usage of namedWindow() function in opencv (02) tu_Locke Family Blog-CSDN Blog

Use of namedWindow() function in OpenCV_opencv銝needamedwindow_Zheng Deshuai's blog-CSDN blog

[300 OpenCV routines] 03. Image display (cv2.imshow)_youcans_'s blog-CSDN blog

The role of destroyallWindows in OpenCV_hanjie-chen's blog-CSDN blog

Python OpenCV resizeWindow() usage and code examples - Pure Sky

https://www.cnblogs.com/mangoroom/archive/2019/06/10/10999151.html

cv.imread() function_Kindergarten leader~’s blog-CSDN blog

[300 OpenCV routines] 02. Image saving (cv2.imwrite)_youcans_'s blog-CSDN blog

The second issue of python-opencv: Detailed explanation of imwrite function_cv2.imwrite_Kamen Black's blog-CSDN blog

Guess you like

Origin blog.csdn.net/adsdasdasdahj/article/details/129963385