File size: 5,005 Bytes
b2f66f0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | """
数据预处理脚本
对收集的图片进行预处理和数据增强
"""
import os
from pathlib import Path
from PIL import Image
import numpy as np
from tqdm import tqdm
import cv2
class DataPreprocessor:
"""数据预处理器"""
def __init__(self, input_dir="data/train", output_dir="data/train_processed", img_size=(224, 224)):
"""
初始化预处理器
Args:
input_dir: 输入目录
output_dir: 输出目录
img_size: 目标图片尺寸
"""
self.input_dir = Path(input_dir)
self.output_dir = Path(output_dir)
self.img_size = img_size
self.output_dir.mkdir(parents=True, exist_ok=True)
def resize_image(self, img_path, output_path):
"""
调整图片大小
Args:
img_path: 输入图片路径
output_path: 输出图片路径
"""
try:
img = Image.open(img_path)
img = img.convert('RGB') # 确保RGB格式
img = img.resize(self.img_size, Image.Resampling.LANCZOS)
img.save(output_path, quality=95)
return True
except Exception as e:
print(f"处理图片失败 {img_path}: {e}")
return False
def augment_image(self, img_path, output_dir, category):
"""
数据增强:生成多个变体
Args:
img_path: 输入图片路径
output_dir: 输出目录
category: 图片类别
"""
try:
img = cv2.imread(str(img_path))
if img is None:
return
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
base_name = img_path.stem
# 1. 原始图片(调整大小)
img_resized = cv2.resize(img_rgb, self.img_size)
cv2.imwrite(str(output_dir / f"{base_name}_0.jpg"),
cv2.cvtColor(img_resized, cv2.COLOR_RGB2BGR))
# 2. 水平翻转
img_flipped = cv2.flip(img_resized, 1)
cv2.imwrite(str(output_dir / f"{base_name}_1.jpg"),
cv2.cvtColor(img_flipped, cv2.COLOR_RGB2BGR))
# 3. 亮度调整(变亮)
img_bright = cv2.convertScaleAbs(img_resized, alpha=1.2, beta=20)
cv2.imwrite(str(output_dir / f"{base_name}_2.jpg"),
cv2.cvtColor(img_bright, cv2.COLOR_RGB2BGR))
# 4. 亮度调整(变暗)
img_dark = cv2.convertScaleAbs(img_resized, alpha=0.8, beta=-20)
cv2.imwrite(str(output_dir / f"{base_name}_3.jpg"),
cv2.cvtColor(img_dark, cv2.COLOR_RGB2BGR))
# 5. 轻微旋转(±5度)
angle = 5
center = (self.img_size[0] // 2, self.img_size[1] // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
img_rotated = cv2.warpAffine(img_resized, M, self.img_size)
cv2.imwrite(str(output_dir / f"{base_name}_4.jpg"),
cv2.cvtColor(img_rotated, cv2.COLOR_RGB2BGR))
except Exception as e:
print(f"增强图片失败 {img_path}: {e}")
def process_category(self, category):
"""
处理单个类别
Args:
category: 类别名称
"""
input_category_dir = self.input_dir / category
output_category_dir = self.output_dir / category
output_category_dir.mkdir(exist_ok=True)
if not input_category_dir.exists():
print(f"警告: 输入目录不存在 {input_category_dir}")
return
image_files = list(input_category_dir.glob("*.jpg")) + \
list(input_category_dir.glob("*.png")) + \
list(input_category_dir.glob("*.jpeg"))
if len(image_files) == 0:
print(f"警告: 类别 {category} 中没有找到图片")
return
print(f"\n处理类别: {category} ({len(image_files)} 张图片)")
for img_path in tqdm(image_files, desc=f"处理 {category}"):
# 数据增强
self.augment_image(img_path, output_category_dir, category)
def process_all(self):
"""处理所有类别"""
categories = ['normal', 'elderly', 'wheelchair', 'stroller']
print("=" * 60)
print("开始数据预处理和数据增强")
print("=" * 60)
for category in categories:
self.process_category(category)
print("\n" + "=" * 60)
print("数据预处理完成!")
print(f"处理后的数据保存在: {self.output_dir}")
print("=" * 60)
def main():
"""主函数"""
preprocessor = DataPreprocessor()
preprocessor.process_all()
if __name__ == "__main__":
main()
|