PIL:图片预处理(批量改变图片尺寸)

from PIL import Image
import os.path

def convertSize(files_dir,width=1024,height=299):  #图片的大小
    file_dir = os.listdir(files_dir)
    for file in file_dir:
        file_path = os.path.join(files_dir,file)
        img = Image.open(file_path)
        img = img.resize((1024, 299))
        img = img.save(file_path)
convertSize('D:\毕设\ACE中文手写字识别\HWDB2.2Train_images')

file_dir = os.listdir('D:\毕设\ACE中文手写字识别\HWDB2.2Train_images')
for file in file_dir:
    file_path = os.path.join('D:\毕设\ACE中文手写字识别\HWDB2.2Train_images',file)
    img = Image.open(file_path)
    print(img)

### YOLOv8 图像预处理方法 对于YOLOv8模型,在执行预测之前,输入图像需经过一系列预处理步骤以确保其格式和尺寸符合网络的要求。这些预处理操作通常包括调整大小、归一化以及可能的数据增强等。 #### 预处理流程概述 - **加载并解析图像**:从指定路径读取图片文件,并将其转换为适合神经网络输入的形式。 - **缩放与裁剪**:将原始图像按比例缩小到目标分辨率(通常是640x640),保持宽高比不变;如果必要的话还会应用中心裁剪来匹配最终期望的输入尺寸[^2]。 - **颜色空间变换**:某些情况下需要改变色彩模式,比如由BGR转RGB,因为OpenCV默认保存的是BGR格式而大多数深度学习框架更倾向于使用RGB顺序。 - **像素值标准化**:为了加速训练过程收敛速度,一般会把各通道上的数值范围映射至[-1, 1]或者[0, 1]之间。这一步骤可以通过减去均值再除以标准差完成。 - **维度排列调整**:由于PyTorch和其他一些库采用NCHW布局(批量×通道数×高度×宽度),所以当源图像是HWC形式时就需要做相应的轴交换。 ```python import torch from PIL import Image import numpy as np def preprocess_image(image_path): """Preprocesses the input image for inference with YOLOv8.""" # Load and resize image to expected size (e.g., 640x640) img = Image.open(image_path).convert('RGB') new_size = (640, 640) # Target resolution img_resized = img.resize(new_size) # Convert to NumPy array and normalize pixel values between [0, 1] img_np = np.array(img_resized) / 255.0 # Transpose dimensions from HWC to CHW format required by PyTorch models img_transposed = img_np.transpose((2, 0, 1)) # Add batch dimension at front since most deep learning frameworks expect batches of inputs img_batched = np.expand_dims(img_transposed, axis=0) # Cast to float tensor compatible with GPU computations if available img_tensor = torch.tensor(img_batched, dtype=torch.float32) return img_tensor.cuda() if torch.cuda.is_available() else img_tensor ``` 上述代码展示了如何准备一张静态照片供YOLOv8检测器分析前所需经历的主要环节。值得注意的是这里假设所有准备工作都在CPU上完成之后才转移到GPU上去运行实际推断任务——这对于Jetson Nano这样的嵌入式平台来说尤为重要,因为它拥有有限计算资源却具备不错的图形处理器性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值