将图像统一转换成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像素,并且在必要时使用灰度边缘填充。