python工具——图像预处理(resize224*224并进行灰度填充)

将图像统一转换成224*224大小的分类数据图像,并且根据长宽进行灰度(114,114,114)边缘填充,以防止原图发生变形。
为了实现这个功能,我们可以使用Python的PIL库(Pillow),它提供了丰富的图像处理功能。下面是一个示例脚本,该脚本会遍历指定目录下的所有图像,将它们统一缩放到224x224像素,同时保持原始图像的比例不变,并在必要时使用灰度(114, 114, 114)边缘填充来避免图像变形。首先,确保你已经安装了Pillow库。如果没有安装,可以通过pip来安装:

pip install pillow

脚本代码:

from PIL import Image
import os
import glob

def resize_and_pad_image(input_path, output_path, target_size=224, pad_color=(114, 114, 114)):
    """
    Resize and pad an image to the target size with a specified padding color.
    
    :param input_path: Path to the input image file.
    :param output_path: Path to save the output image file.
    :param target_size: Target size (width, height) of the output image.
    :param pad_color: Color to use for padding (R, G, B).
    """
    # 打开图像
    with Image.open(input_path) as img:
        # 计算原始图像与目标尺寸的比例
        original_width, original_height = img.size
        ratio = min(target_size / original_width, target_size / original_height)
        
        # 缩放图像
        new_size = (int(original_width * ratio), int(original_height * ratio))
        resized_img = img.resize(new_size, Image.ANTIALIAS)
        
        # 计算填充区域
        padded_img = Image.new('RGB', (target_size, target_size), pad_color)
        x_offset = (target_size - new_size[0]) // 2
        y_offset = (target_size - new_size[1]) // 2
        
        # 将缩放后的图像粘贴到填充后的画布上
        padded_img.paste(resized_img, (x_offset, y_offset))
        
        # 保存处理后的图像
        padded_img.save(output_path, format='JPEG')

def process_images_in_directory(directory, output_directory, target_size=224):
    """
    Process all images in a directory to be resized and padded.
    
    :param directory: Directory containing the images to process.
    :param output_directory: Directory to save the processed images.
    :param target_size: Target size (width, height) of the output images.
    """
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)
    
    # 获取目录下所有的图像文件
    image_files = glob.glob(os.path.join(directory, '*.jpg')) + glob.glob(os.path.join(directory, '*.png'))
    
    for image_file in image_files:
        # 创建输出文件路径
        base_name = os.path.basename(image_file)
        output_file = os.path.join(output_directory, base_name)
        
        # 处理单个图像
        resize_and_pad_image(image_file, output_file, target_size=target_size)

# 使用示例
input_dir = 'path/to/input/directory'  # 替换为包含待处理图像的目录
output_dir = 'path/to/output/directory'  # 替换为要保存处理后图像的目录
process_images_in_directory(input_dir, output_dir)

说明

•resize_and_pad_image 函数负责读取单个图像,将其缩放到合适的大小,然后填充到224x224的目标尺寸。
•process_images_in_directory 函数遍历指定目录中的所有图像文件,并调用 resize_and_pad_image 对它们进行处理。
•pad_color 参数定义了用于填充的灰度颜色,在这里设为(114, 114, 114)。
•请确保替换 input_dir 和 output_dir 变量为实际的输入和输出目录路径。
运行此脚本后,指定目录中的所有图像都会被处理并保存到输出目录,每个图像都将被调整为224x224像素,并且在必要时使用灰度边缘填充。

参考资源链接:[Python深度学习实现遥感图片分类与识别](https://wenku.youkuaiyun.com/doc/p6sfyv984y?utm_source=wenku_answer2doc_content) 在深度学习领域,数据预处理是至关重要的一步,特别是在处理遥感图像时。Python和PyTorch提供了强大的工具集来处理这类数据。首先,你需要确保已经安装了Python和PyTorch,且理解了CNN模型的基本构成,包括卷积层、池化层和全连接层。接下来,根据遥感图像的特点,我们通常需要对图像进行以下几个预处理步骤: 1. 图像尺寸调整:由于CNN要求输入的图像尺寸一致,因此需要将所有遥感图像统一尺寸。常用的方法是将图像转换为正方形,对缺失的部分填充灰度值或零值以保持一致性。 2. 数据增强:通过对图像进行旋转、缩放、翻转等操作,可以增加数据集的多样性,提高模型的泛化能力。 3. 归一化:将图像像素值归一化到0-1范围内,有助于加快模型的收敛速度和提高训练效率。 4. 标准化:对图像数据进行标准化处理,使得数据具有0均值和单位方差,有助于稳定训练过程提升模型性能。 在PyTorch中,可以使用`transforms`模块来实现上述预处理步骤,例如: ```python from torchvision import transforms transform = ***pose([ transforms.Resize((128, 128)), # 调整图像大小为128x128 transforms.Grayscale(num_output_channels=1), # 转换为灰度图,如果需要的话 transforms.RandomHorizontalFlip(), # 随机水平翻转 transforms.RandomRotation(10), # 随机旋转 transforms.ToTensor(), # 转换为Tensor transforms.Normalize(mean=[0.5], std=[0.5]) # 归一化处理 ]) ``` 在定义好预处理流程后,你可以将这个`transform`应用到数据集上,如使用`torchvision.datasets.ImageFolder`加载数据集,传递预处理流程给它。 通过这样的预处理步骤,你可以确保你的数据集适合于CNN模型的输入,且可以更好地训练模型以进行遥感图像的分类任务。如果需要更详细的实践操作,我推荐你查阅《Python深度学习实现遥感图片分类与识别》一书,它将为你提供详细的代码示例和操作步骤,帮助你更全面地掌握这些技能。 参考资源链接:[Python深度学习实现遥感图片分类与识别](https://wenku.youkuaiyun.com/doc/p6sfyv984y?utm_source=wenku_answer2doc_content)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值