使用OpenCV来实现读取一个目录下的所有图像,然后将它们调整大小为1920x1080像素,并保存

使用OpenCV来实现读取一个目录下的所有图像,然后将它们调整大小为1920x1080像素,并保存的步骤如下:

  1. 安装OpenCV库:如果你还没有安装OpenCV库,可以通过pip安装:

    pip install opencv-python
    
  2. 编写Python脚本

    import os
    import cv2
    
    def resize_images_in_directory(source_dir, target_dir, size=(1920, 1080)):
        """
        Resize images in the specified directory to the given size and save them to the target directory.
    
        :param source_dir: Directory to find original images.
        :param target_dir: Directory to save resized images.
        :param size: Desired image size.
        """
        # 创建目标目录如果它不存在
        if not os.path.exists(target_dir):
            os.makedirs(target_dir)
    
        # 遍历源目录中的所有文件
        for filename in os.listdir(source_dir):
            if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
                # 构建完整的文件路径
                original_path = os.path.join(source_dir, filename)
                resized_path = os.path.join(target_dir, filename)
    
                # 读取图像
                img = cv2.imread(original_path)
    
                # 调整图像大小
                resized_img = cv2.resize(img, size, interpolation=cv2.INTER_AREA)
    
                # 保存调整大小后的图像
                cv2.imwrite(resized_path, resized_img)
                print(f'Resized and saved {filename} to {resized_path}')
    
    # 使用示例
    source_directory = 'path/to/your/source/directory'
    target_directory = 'path/to/your/target/directory'
    resize_images_in_directory(source_directory, target_directory)
    

    这个脚本会读取指定源目录(source_directory)中的所有图像文件,调整它们的大小到1920x1080像素,然后保存到指定的目标目录(target_directory)。请根据你的需求修改source_directorytarget_directory路径。

  3. 运行脚本:确保源目录中有图像文件,然后运行这个脚本。

这个方法使用了OpenCV库来读取和处理图像,效率较高,并且可以处理指定目录下的所有支持的图像格式。

posted @ 2024-04-15 11:37  Zenith_Hugh  阅读(53)  评论(0)    收藏  举报