在大模型训练中,图像数据预处理的质量直接影响模型性能。本文分享几种实用的预处理优化方法。
1. 数据清洗与去重 使用hash算法快速识别重复图片:
import hashlib
import cv2
from collections import defaultdict
def calculate_hash(image_path):
with open(image_path, 'rb') as f:
return hashlib.md5(f.read()).hexdigest()
# 找出重复项
hash_dict = defaultdict(list)
for img_path in image_paths:
img_hash = calculate_hash(img_path)
hash_dict[img_hash].append(img_path)
2. 图像尺寸标准化 统一输入尺寸提升训练效率:
from PIL import Image
import torch
def resize_and_normalize(image_path, target_size=(224, 224)):
img = Image.open(image_path).convert('RGB')
img = img.resize(target_size, Image.LANCZOS)
return torch.tensor(np.array(img)).permute(2, 0, 1) / 255.0
3. 噪声去除与增强 使用中值滤波处理椒盐噪声:
import cv2
import numpy as np
noisy_img = cv2.imread('noisy.jpg')
filtered_img = cv2.medianBlur(noisy_img, 5)
这些方法可显著提升数据质量,建议在训练前进行完整预处理流程。

讨论