143 lines
3.8 KiB
Python
143 lines
3.8 KiB
Python
"""
|
|
工具函数
|
|
"""
|
|
import numpy as np
|
|
import cv2
|
|
import matplotlib.pyplot as plt
|
|
|
|
|
|
def visualize_prediction(image_path, class_id, confidence, class_names=None):
|
|
"""
|
|
可视化预测结果
|
|
|
|
Args:
|
|
image_path: 图像路径
|
|
class_id: 预测类别
|
|
confidence: 置信度
|
|
class_names: 类别名称列表
|
|
"""
|
|
if class_names is None:
|
|
class_names = [f'Class {i}' for i in range(10)]
|
|
|
|
img = cv2.imread(image_path)
|
|
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
|
|
|
plt.figure(figsize=(8, 6))
|
|
plt.imshow(img)
|
|
plt.title(f'预测: {class_names[class_id]}\n置信度: {confidence * 100:.2f}%',
|
|
fontsize=14)
|
|
plt.axis('off')
|
|
plt.tight_layout()
|
|
plt.show()
|
|
|
|
|
|
def benchmark(inferencer, image_path, num_runs=100):
|
|
"""
|
|
性能基准测试
|
|
|
|
Args:
|
|
inferencer: 推理器实例
|
|
image_path: 测试图像路径
|
|
num_runs: 运行次数
|
|
|
|
Returns:
|
|
avg_time: 平均推理时间(ms)
|
|
fps: 每秒帧数
|
|
"""
|
|
import time
|
|
|
|
times = []
|
|
for i in range(num_runs):
|
|
start = time.time()
|
|
inferencer.inference(image_path)
|
|
end = time.time()
|
|
times.append((end - start) * 1000)
|
|
|
|
if (i + 1) % 10 == 0:
|
|
print(f'进度: {i + 1}/{num_runs}')
|
|
|
|
avg_time = np.mean(times)
|
|
std_time = np.std(times)
|
|
fps = 1000 / avg_time
|
|
|
|
print(f'\n性能统计:')
|
|
print(f'平均推理时间: {avg_time:.2f} ± {std_time:.2f} ms')
|
|
print(f'FPS: {fps:.2f}')
|
|
print(f'最小时间: {np.min(times):.2f} ms')
|
|
print(f'最大时间: {np.max(times):.2f} ms')
|
|
|
|
return avg_time, fps
|
|
|
|
|
|
def batch_inference(inferencer, image_dir, output_csv='results.csv'):
|
|
"""
|
|
批量推理
|
|
|
|
Args:
|
|
inferencer: 推理器实例
|
|
image_dir: 图像目录
|
|
output_csv: 输出CSV文件路径
|
|
"""
|
|
import os
|
|
import csv
|
|
|
|
results = []
|
|
image_files = [f for f in os.listdir(image_dir)
|
|
if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
|
|
|
|
print(f'找到 {len(image_files)} 张图像')
|
|
|
|
for i, img_file in enumerate(image_files):
|
|
img_path = os.path.join(image_dir, img_file)
|
|
class_id, confidence = inferencer.inference(img_path)
|
|
results.append([img_file, class_id, confidence])
|
|
|
|
if (i + 1) % 10 == 0:
|
|
print(f'进度: {i + 1}/{len(image_files)}')
|
|
|
|
# 保存结果
|
|
with open(output_csv, 'w', newline='') as f:
|
|
writer = csv.writer(f)
|
|
writer.writerow(['Image', 'Class', 'Confidence'])
|
|
writer.writerows(results)
|
|
|
|
print(f'结果已保存到: {output_csv}')
|
|
|
|
|
|
def compare_with_pytorch(pynq_inferencer, pytorch_model, image_path, device='cpu'):
|
|
"""
|
|
对比PYNQ和PyTorch推理结果
|
|
|
|
Args:
|
|
pynq_inferencer: PYNQ推理器
|
|
pytorch_model: PyTorch模型
|
|
image_path: 测试图像
|
|
device: PyTorch设备
|
|
"""
|
|
import torch
|
|
from torchvision import transforms
|
|
|
|
# PYNQ推理
|
|
pynq_class, pynq_conf = pynq_inferencer.inference(image_path)
|
|
|
|
# PyTorch推理
|
|
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])
|
|
])
|
|
|
|
from PIL import Image
|
|
img = Image.open(image_path).convert('RGB')
|
|
img_tensor = transform(img).unsqueeze(0).to(device)
|
|
|
|
pytorch_model.eval()
|
|
with torch.no_grad():
|
|
output = pytorch_model(img_tensor)
|
|
pytorch_class = output.argmax(1).item()
|
|
pytorch_conf = torch.softmax(output, dim=1)[0, pytorch_class].item()
|
|
|
|
print(f'\nPYNQ推理: 类别={pynq_class}, 置信度={pynq_conf:.4f}')
|
|
print(f'PyTorch推理: 类别={pytorch_class}, 置信度={pytorch_conf:.4f}')
|
|
print(f'结果一致: {pynq_class == pytorch_class}') |