Use the cv2.resize() function in Python to customize the scaled image size in batches

Commonly used interpolation scaling methods

cv2.resize()The parameters in the function interpolationspecify the interpolation method used when scaling the image. The following are commonly used interpolation methods:

cv2.INTER_NEAREST: Nearest neighbor interpolation. This method interpolates by selecting the original pixel closest to the target pixel. It is the fastest interpolation method, but may cause jagged edge effects.

cv2.INTER_LINEAR: Bilinear interpolation. This method calculates the value of the target pixel by using a linear combination of the original pixels. It provides smoother results than nearest neighbor interpolation, but may lose detail when shrinking the image.

cv2.INTER_CUBIC: Bicubic interpolation. This method uses more neighboring pixels based on bilinear interpolation to obtain higher quality scaling results. It is more computationally intensive than bilinear interpolation, but provides better results.

cv2.INTER_LANCZOS4: Lanczos interpolation. This method uses the Lanczos algorithm to calculate the value of the target pixel. It provides better fidelity when scaling images, but is more computationally intensive.

cv2.INTER_AREa: Suitable for shrinking images without distortion. For details, please refer to the blog post: What exactly is INTER_AREA in OpenCV doing?

Zoom example

Insert image description here

code


import os
import cv2

# 获取文件路径
folder_path = "E:/SR_Images/DIV2K_theml/DIV2K_train_HR"
output_path = "E:/SR_Images/DIV2K_theml/DIV2K_train_LR_bicubic/X2"

# 获取文件夹中所有的文件
file_list = os.listdir(folder_path)

# 遍历文件列表
for file_name in file_list:
    # 拼接文件路径
    file_path = os.path.join(folder_path,file_name)

    # 仅处理图像文件
    if os.path.isfile(file_path) and file_name.lower().endswith(('.png',',jpg','.jpeg','.bmp')):
        # 读取图像路径
        image = cv2.imread(file_path)

        # 获取图像原尺寸
        height,width = image.shape[:2]

        # 计算缩放后的尺寸
        new_heiht = int(height / 2)
        new_width = int(width / 2)

        # 缩放图像
        resized_image = cv2.resize(image,(new_width,new_heiht),interpolation=cv2.INTER_CUBIC)  # 例子中使用了双三次插值

        # 保存缩放后的图像
        output_file = file_name[:-4] + "x2.png"
        cv2.imwrite(os.path.join(output_path,output_file),resized_image)

Summarize

The above is how to use the cv2.resize() function to batch customize the zoom image size. Scholars use the corresponding scaling parameters according to their own scaling needs. Thank you for your support!

Guess you like

Origin blog.csdn.net/qq_40280673/article/details/134018946