178 lines
5.4 KiB
Python
178 lines
5.4 KiB
Python
"""
|
|
PC端简单演示脚本 - 命令行版本(无GUI,适合快速测试)
|
|
|
|
功能:
|
|
1. 加载模型并进行推理
|
|
2. 在命令行显示结果
|
|
3. 保存预测结果图像
|
|
"""
|
|
import os
|
|
import time
|
|
import torch
|
|
from torchvision import transforms
|
|
from PIL import Image, ImageDraw, ImageFont
|
|
import argparse
|
|
|
|
from model import create_model
|
|
|
|
|
|
def load_model(model_path, num_classes=10, device='cpu'):
|
|
"""加载训练好的模型"""
|
|
print(f"正在加载模型: {model_path}")
|
|
model = create_model(num_classes=num_classes, pretrained=False)
|
|
|
|
checkpoint = torch.load(model_path, map_location=device)
|
|
if 'model_state_dict' in checkpoint:
|
|
model.load_state_dict(checkpoint['model_state_dict'])
|
|
else:
|
|
model.load_state_dict(checkpoint)
|
|
|
|
model = model.to(device)
|
|
model.eval()
|
|
print("模型加载完成\n")
|
|
return model
|
|
|
|
|
|
def predict_and_save(model, image_path, transform, device, output_path, class_names):
|
|
"""预测并保存结果图像"""
|
|
# 加载图像
|
|
image = Image.open(image_path).convert('RGB')
|
|
image_tensor = transform(image).unsqueeze(0).to(device)
|
|
|
|
# 推理
|
|
with torch.no_grad():
|
|
start_time = time.time()
|
|
output = model(image_tensor)
|
|
inference_time = (time.time() - start_time) * 1000 # ms
|
|
|
|
probabilities = torch.softmax(output, dim=1)
|
|
pred_class = torch.argmax(probabilities, dim=1).item()
|
|
confidence = probabilities[0][pred_class].item()
|
|
|
|
# 在图像上添加预测结果
|
|
result_image = image.copy()
|
|
result_image = result_image.resize((800, 800))
|
|
draw = ImageDraw.Draw(result_image)
|
|
|
|
# 添加文字
|
|
text = f"Predicted: {class_names[pred_class]}\n"
|
|
text += f"Confidence: {confidence*100:.2f}%\n"
|
|
text += f"Time: {inference_time:.2f}ms"
|
|
|
|
# 使用默认字体
|
|
try:
|
|
font = ImageFont.truetype("arial.ttf", 40)
|
|
except:
|
|
font = ImageFont.load_default()
|
|
|
|
# 绘制文字背景
|
|
draw.rectangle([(10, 10), (600, 150)], fill='white', outline='black', width=3)
|
|
draw.text((20, 20), text, fill='black', font=font)
|
|
|
|
# 保存结果
|
|
result_image.save(output_path)
|
|
|
|
return pred_class, confidence, inference_time
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description='PC端简单演示')
|
|
parser.add_argument('--model_path', type=str,
|
|
default='data/models/best_model.pth')
|
|
parser.add_argument('--data_dir', type=str,
|
|
default='data/processed/val')
|
|
parser.add_argument('--output_dir', type=str,
|
|
default='demo_results')
|
|
parser.add_argument('--num_samples', type=int, default=20,
|
|
help='演示图像数量')
|
|
args = parser.parse_args()
|
|
|
|
# 创建输出目录
|
|
os.makedirs(args.output_dir, exist_ok=True)
|
|
|
|
# 设置设备
|
|
device = torch.device('cpu')
|
|
|
|
# 数据预处理
|
|
transform = transforms.Compose([
|
|
transforms.Resize((224, 224)),
|
|
transforms.ToTensor(),
|
|
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
|
std=[0.229, 0.224, 0.225])
|
|
])
|
|
|
|
# 类别名称
|
|
class_names = [f'class_{i}' for i in range(10)]
|
|
|
|
print("="*60)
|
|
print("PC端光图像识别演示系统")
|
|
print("="*60)
|
|
print(f"模型: MobileNetV2")
|
|
print(f"设备: {device}\n")
|
|
|
|
# 加载模型
|
|
model = load_model(args.model_path, num_classes=10, device=device)
|
|
|
|
# 获取测试图像
|
|
image_paths = []
|
|
true_labels = []
|
|
|
|
for class_idx, class_name in enumerate(class_names):
|
|
class_dir = os.path.join(args.data_dir, class_name)
|
|
if os.path.exists(class_dir):
|
|
for img_name in sorted(os.listdir(class_dir))[:2]: # 每类取2张
|
|
if img_name.endswith(('.jpg', '.png', '.jpeg')):
|
|
image_paths.append(os.path.join(class_dir, img_name))
|
|
true_labels.append(class_idx)
|
|
|
|
# 限制数量
|
|
image_paths = image_paths[:args.num_samples]
|
|
true_labels = true_labels[:args.num_samples]
|
|
|
|
print(f"找到 {len(image_paths)} 张测试图像\n")
|
|
print("开始推理...\n")
|
|
|
|
correct = 0
|
|
total = 0
|
|
total_time = 0
|
|
|
|
for idx, (img_path, true_label) in enumerate(zip(image_paths, true_labels)):
|
|
# 输出文件名
|
|
output_name = f"result_{idx+1:03d}.jpg"
|
|
output_path = os.path.join(args.output_dir, output_name)
|
|
|
|
# 预测
|
|
pred_class, confidence, inf_time = predict_and_save(
|
|
model, img_path, transform, device, output_path, class_names
|
|
)
|
|
|
|
# 统计
|
|
is_correct = (pred_class == true_label)
|
|
if is_correct:
|
|
correct += 1
|
|
total += 1
|
|
total_time += inf_time
|
|
|
|
# 打印结果
|
|
status = "[正确]" if is_correct else "[错误]"
|
|
print(f"[{idx+1}/{len(image_paths)}] {os.path.basename(img_path)}")
|
|
print(f" 真实: {class_names[true_label]}")
|
|
print(f" 预测: {class_names[pred_class]} {status}")
|
|
print(f" 置信度: {confidence*100:.2f}%")
|
|
print(f" 推理时间: {inf_time:.2f} ms")
|
|
print(f" 已保存: {output_name}")
|
|
print()
|
|
|
|
# 最终统计
|
|
print("="*60)
|
|
print("演示完成!")
|
|
print(f"总体准确率: {correct}/{total} = {correct/total*100:.2f}%")
|
|
print(f"平均推理时间: {total_time/total:.2f} ms")
|
|
print(f"吞吐量: {1000/(total_time/total):.2f} FPS")
|
|
print(f"结果已保存到: {args.output_dir}/")
|
|
print("="*60)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|