300 lines
9.1 KiB
Python
300 lines
9.1 KiB
Python
"""
|
|
PC端演示脚本 - 适合录屏展示
|
|
|
|
功能:
|
|
1. 加载训练好的模型
|
|
2. 逐张显示测试图像
|
|
3. 实时显示预测结果(类别、置信度、推理时间)
|
|
4. 适合录屏演示给老师
|
|
"""
|
|
import os
|
|
import time
|
|
import torch
|
|
import torch.nn as nn
|
|
from torchvision import transforms
|
|
from PIL import Image
|
|
import matplotlib.pyplot as plt
|
|
import matplotlib
|
|
import numpy as np
|
|
|
|
# 设置中文字体
|
|
matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 黑体
|
|
matplotlib.rcParams['axes.unicode_minus'] = False
|
|
|
|
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_image(model, image_path, transform, device):
|
|
"""对单张图像进行预测"""
|
|
# 加载图像
|
|
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()
|
|
|
|
return image, pred_class, confidence, inference_time, probabilities[0].cpu().numpy()
|
|
|
|
|
|
def display_prediction(image, pred_class, confidence, inference_time,
|
|
true_class, probabilities, class_names):
|
|
"""显示预测结果"""
|
|
fig = plt.figure(figsize=(14, 6))
|
|
|
|
# 左侧:显示图像
|
|
ax1 = plt.subplot(1, 2, 1)
|
|
ax1.imshow(image)
|
|
ax1.axis('off')
|
|
|
|
# 标题显示预测结果
|
|
is_correct = (pred_class == true_class)
|
|
color = 'green' if is_correct else 'red'
|
|
result_text = '正确' if is_correct else '错误'
|
|
|
|
title = f'真实类别: {class_names[true_class]}\n'
|
|
title += f'预测类别: {class_names[pred_class]} ({result_text})\n'
|
|
title += f'置信度: {confidence*100:.2f}%\n'
|
|
title += f'推理时间: {inference_time:.2f} ms'
|
|
|
|
ax1.set_title(title, fontsize=14, color=color, fontweight='bold')
|
|
|
|
# 右侧:显示概率分布
|
|
ax2 = plt.subplot(1, 2, 2)
|
|
bars = ax2.barh(class_names, probabilities * 100)
|
|
|
|
# 高亮预测类别
|
|
bars[pred_class].set_color('red')
|
|
bars[true_class].set_edgecolor('green')
|
|
bars[true_class].set_linewidth(3)
|
|
|
|
ax2.set_xlabel('置信度 (%)', fontsize=12)
|
|
ax2.set_title('各类别预测概率', fontsize=14, fontweight='bold')
|
|
ax2.set_xlim(0, 100)
|
|
|
|
# 添加数值标签
|
|
for i, (bar, prob) in enumerate(zip(bars, probabilities)):
|
|
if prob > 0.01: # 只显示>1%的概率
|
|
ax2.text(prob * 100 + 1, i, f'{prob*100:.1f}%',
|
|
va='center', fontsize=10)
|
|
|
|
plt.tight_layout()
|
|
plt.pause(0.1) # 短暂暂停以更新显示
|
|
|
|
return fig
|
|
|
|
|
|
def demo_single_mode(model, data_dir, transform, device, class_names):
|
|
"""单张演示模式 - 逐张显示"""
|
|
print("\n" + "="*60)
|
|
print("单张演示模式 - 按任意键继续,按 'q' 退出")
|
|
print("="*60 + "\n")
|
|
|
|
# 获取所有测试图像
|
|
image_paths = []
|
|
true_labels = []
|
|
|
|
for class_idx, class_name in enumerate(class_names):
|
|
class_dir = os.path.join(data_dir, class_name)
|
|
if os.path.exists(class_dir):
|
|
for img_name in os.listdir(class_dir):
|
|
if img_name.endswith(('.jpg', '.png', '.jpeg')):
|
|
image_paths.append(os.path.join(class_dir, img_name))
|
|
true_labels.append(class_idx)
|
|
|
|
print(f"找到 {len(image_paths)} 张测试图像\n")
|
|
|
|
correct = 0
|
|
total = 0
|
|
|
|
plt.ion() # 开启交互模式
|
|
|
|
for idx, (img_path, true_label) in enumerate(zip(image_paths, true_labels)):
|
|
print(f"\n[{idx+1}/{len(image_paths)}] 正在处理: {os.path.basename(img_path)}")
|
|
|
|
# 预测
|
|
image, pred_class, confidence, inf_time, probs = predict_image(
|
|
model, img_path, transform, device
|
|
)
|
|
|
|
# 显示结果
|
|
fig = display_prediction(
|
|
image, pred_class, confidence, inf_time,
|
|
true_label, probs, class_names
|
|
)
|
|
|
|
# 统计
|
|
if pred_class == true_label:
|
|
correct += 1
|
|
total += 1
|
|
|
|
# 打印结果
|
|
result = "正确" if pred_class == true_label else "错误"
|
|
print(f" 真实: {class_names[true_label]}")
|
|
print(f" 预测: {class_names[pred_class]} ({result})")
|
|
print(f" 置信度: {confidence*100:.2f}%")
|
|
print(f" 推理时间: {inf_time:.2f} ms")
|
|
print(f" 当前准确率: {correct}/{total} = {correct/total*100:.2f}%")
|
|
|
|
# 等待用户输入
|
|
print("\n按 Enter 继续,输入 'q' 退出...")
|
|
user_input = input()
|
|
|
|
plt.close(fig)
|
|
|
|
if user_input.lower() == 'q':
|
|
break
|
|
|
|
plt.ioff()
|
|
|
|
# 最终统计
|
|
print("\n" + "="*60)
|
|
print("演示完成!")
|
|
print(f"总体准确率: {correct}/{total} = {correct/total*100:.2f}%")
|
|
print("="*60)
|
|
|
|
|
|
def demo_auto_mode(model, data_dir, transform, device, class_names, delay=2.0):
|
|
"""自动演示模式 - 自动播放,适合录屏"""
|
|
print("\n" + "="*60)
|
|
print(f"自动演示模式 - 每张图像停留 {delay} 秒")
|
|
print("="*60 + "\n")
|
|
|
|
# 获取所有测试图像
|
|
image_paths = []
|
|
true_labels = []
|
|
|
|
for class_idx, class_name in enumerate(class_names):
|
|
class_dir = os.path.join(data_dir, class_name)
|
|
if os.path.exists(class_dir):
|
|
for img_name in sorted(os.listdir(class_dir)):
|
|
if img_name.endswith(('.jpg', '.png', '.jpeg')):
|
|
image_paths.append(os.path.join(class_dir, img_name))
|
|
true_labels.append(class_idx)
|
|
|
|
print(f"找到 {len(image_paths)} 张测试图像\n")
|
|
print("开始演示...\n")
|
|
|
|
correct = 0
|
|
total = 0
|
|
total_time = 0
|
|
|
|
plt.ion() # 开启交互模式
|
|
|
|
for idx, (img_path, true_label) in enumerate(zip(image_paths, true_labels)):
|
|
print(f"[{idx+1}/{len(image_paths)}] {os.path.basename(img_path)}", end=" ")
|
|
|
|
# 预测
|
|
image, pred_class, confidence, inf_time, probs = predict_image(
|
|
model, img_path, transform, device
|
|
)
|
|
|
|
# 显示结果
|
|
fig = display_prediction(
|
|
image, pred_class, confidence, inf_time,
|
|
true_label, probs, class_names
|
|
)
|
|
|
|
# 统计
|
|
if pred_class == true_label:
|
|
correct += 1
|
|
print("[正确]", end=" ")
|
|
else:
|
|
print("[错误]", end=" ")
|
|
|
|
total += 1
|
|
total_time += inf_time
|
|
|
|
print(f"准确率: {correct/total*100:.1f}%")
|
|
|
|
# 等待
|
|
plt.pause(delay)
|
|
plt.close(fig)
|
|
|
|
plt.ioff()
|
|
|
|
# 最终统计
|
|
print("\n" + "="*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("="*60)
|
|
|
|
|
|
def main():
|
|
import argparse
|
|
|
|
parser = argparse.ArgumentParser(description='PC端演示脚本')
|
|
parser.add_argument('--model_path', type=str,
|
|
default='data/models/best_model.pth',
|
|
help='模型路径')
|
|
parser.add_argument('--data_dir', type=str,
|
|
default='data/processed/val',
|
|
help='测试数据目录')
|
|
parser.add_argument('--mode', type=str, default='auto',
|
|
choices=['single', 'auto'],
|
|
help='演示模式: single(单张) 或 auto(自动)')
|
|
parser.add_argument('--delay', type=float, default=2.0,
|
|
help='自动模式下每张图像停留时间(秒)')
|
|
parser.add_argument('--device', type=str, default='cpu',
|
|
help='设备 (cpu/cuda)')
|
|
args = parser.parse_args()
|
|
|
|
# 设置设备
|
|
device = torch.device(args.device if torch.cuda.is_available() else '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}")
|
|
print(f"模式: {args.mode}")
|
|
|
|
# 加载模型
|
|
model = load_model(args.model_path, num_classes=10, device=device)
|
|
|
|
# 运行演示
|
|
if args.mode == 'single':
|
|
demo_single_mode(model, args.data_dir, transform, device, class_names)
|
|
else:
|
|
demo_auto_mode(model, args.data_dir, transform, device, class_names, args.delay)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|