122 lines
3.5 KiB
Python
122 lines
3.5 KiB
Python
"""
|
|
简化的推理脚本 - 不依赖FPGA硬件
|
|
用于在PC端测试模型
|
|
"""
|
|
import torch
|
|
import cv2
|
|
import numpy as np
|
|
from PIL import Image
|
|
import argparse
|
|
import sys
|
|
import os
|
|
|
|
sys.path.append('../pc_training')
|
|
from model import create_model
|
|
|
|
|
|
class SimpleMobileNetInference:
|
|
"""简化的MobileNet推理类(CPU/GPU)"""
|
|
|
|
def __init__(self, model_path, num_classes=10, device='cpu'):
|
|
"""
|
|
初始化推理器
|
|
|
|
Args:
|
|
model_path: 模型权重路径
|
|
num_classes: 类别数
|
|
device: 运行设备
|
|
"""
|
|
self.device = torch.device(device)
|
|
print(f"使用设备: {self.device}")
|
|
|
|
# 加载模型
|
|
print("加载模型...")
|
|
self.model = create_model(num_classes=num_classes, pretrained=False)
|
|
checkpoint = torch.load(model_path, map_location=self.device)
|
|
self.model.load_state_dict(checkpoint['model_state_dict'])
|
|
self.model = self.model.to(self.device)
|
|
self.model.eval()
|
|
|
|
print("模型加载完成!")
|
|
|
|
def preprocess(self, image_path):
|
|
"""图像预处理"""
|
|
from torchvision import transforms
|
|
|
|
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])
|
|
])
|
|
|
|
img = Image.open(image_path).convert('RGB')
|
|
img_tensor = transform(img).unsqueeze(0)
|
|
return img_tensor
|
|
|
|
def inference(self, image_path):
|
|
"""执行推理"""
|
|
import time
|
|
|
|
# 预处理
|
|
img_tensor = self.preprocess(image_path).to(self.device)
|
|
|
|
# 推理
|
|
start_time = time.time()
|
|
with torch.no_grad():
|
|
output = self.model(img_tensor)
|
|
probs = torch.softmax(output, dim=1)
|
|
|
|
inference_time = time.time() - start_time
|
|
|
|
# 获取结果
|
|
class_id = output.argmax(1).item()
|
|
confidence = probs[0, class_id].item()
|
|
|
|
print(f"推理时间: {inference_time * 1000:.2f} ms")
|
|
print(f"预测类别: {class_id}, 置信度: {confidence:.4f}")
|
|
|
|
return class_id, confidence
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description='MobileNet推理(CPU/GPU)')
|
|
parser.add_argument('--model', type=str, required=True,
|
|
help='模型权重路径')
|
|
parser.add_argument('--image', type=str, required=True,
|
|
help='输入图像路径')
|
|
parser.add_argument('--num_classes', type=int, default=10,
|
|
help='类别数')
|
|
parser.add_argument('--device', type=str, default='cpu',
|
|
choices=['cpu', 'cuda'],
|
|
help='运行设备')
|
|
|
|
args = parser.parse_args()
|
|
|
|
# 检查文件是否存在
|
|
if not os.path.exists(args.model):
|
|
print(f"错误: 模型文件不存在: {args.model}")
|
|
return
|
|
|
|
if not os.path.exists(args.image):
|
|
print(f"错误: 图像文件不存在: {args.image}")
|
|
return
|
|
|
|
# 创建推理器
|
|
inferencer = SimpleMobileNetInference(
|
|
args.model,
|
|
num_classes=args.num_classes,
|
|
device=args.device
|
|
)
|
|
|
|
# 执行推理
|
|
class_id, confidence = inferencer.inference(args.image)
|
|
|
|
# 类别名称
|
|
class_names = [f'{i}个光瓣' for i in range(args.num_classes)]
|
|
print(f"\n识别结果: {class_names[class_id]}")
|
|
print(f"置信度: {confidence * 100:.2f}%")
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main() |