Files
light-petal-recognition/notebooks/03_pynq_deployment.ipynb
T

8.4 KiB

PYNQ Z2 MobileNetV2 部署示例

本notebook演示如何在PYNQ Z2板卡上部署和运行MobileNetV2模型

1. 环境准备

In [ ]:
import sys
sys.path.append('../fpga_deployment')

import numpy as np
import cv2
import matplotlib.pyplot as plt
from PIL import Image
from pynq import Overlay, allocate
import time

print('环境准备完成!')

2. 加载FPGA Overlay

In [ ]:
# 指定bitstream路径
BITSTREAM_PATH = 'mobilenet.bit'

# 加载overlay
print('加载FPGA overlay...')
overlay = Overlay(BITSTREAM_PATH)
print('Overlay加载成功!')

# 查看overlay信息
print('\nOverlay IP核:')
print(overlay.ip_dict.keys())

3. 初始化DMA和加速器

In [ ]:
# 获取DMA
dma = overlay.axi_dma_0
print('DMA初始化完成')

# 获取加速器
accelerator = overlay.mobilenet_accel_0
print('加速器初始化完成')

# 分配输入输出缓冲区
input_buffer = allocate(shape=(224, 224, 3), dtype=np.float32)
output_buffer = allocate(shape=(10,), dtype=np.float32)
print('缓冲区分配完成')

4. 图像预处理函数

In [ ]:
def preprocess_image(image_path):
    """预处理图像"""
    # 读取图像
    img = cv2.imread(image_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    
    # 调整大小
    img = cv2.resize(img, (224, 224))
    
    # 归一化
    img = img.astype(np.float32) / 255.0
    mean = np.array([0.485, 0.456, 0.406])
    std = np.array([0.229, 0.224, 0.225])
    img = (img - mean) / std
    
    return img

def show_image(image_path):
    """显示图像"""
    img = cv2.imread(image_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.figure(figsize=(6, 6))
    plt.imshow(img)
    plt.axis('off')
    plt.show()

print('预处理函数定义完成')

5. 单张图像推理

In [ ]:
# 指定测试图像
TEST_IMAGE = 'test.jpg'

# 显示图像
print('测试图像:')
show_image(TEST_IMAGE)

# 预处理
img = preprocess_image(TEST_IMAGE)
np.copyto(input_buffer, img)

# 推理
print('\n开始推理...')
start_time = time.time()

dma.sendchannel.transfer(input_buffer)
dma.recvchannel.transfer(output_buffer)
dma.sendchannel.wait()
dma.recvchannel.wait()

inference_time = time.time() - start_time

# 获取结果
output = np.array(output_buffer)
class_id = np.argmax(output)
confidence = output[class_id]

# 类别名称
class_names = [f'{i}个光瓣' for i in range(10)]

print(f'推理时间: {inference_time * 1000:.2f} ms')
print(f'预测类别: {class_names[class_id]}')
print(f'置信度: {confidence * 100:.2f}%')

6. 性能测试

In [ ]:
# 多次推理测试性能
num_runs = 100
times = []

print(f'运行 {num_runs} 次推理...')
for i in range(num_runs):
    start = time.time()
    
    dma.sendchannel.transfer(input_buffer)
    dma.recvchannel.transfer(output_buffer)
    dma.sendchannel.wait()
    dma.recvchannel.wait()
    
    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)
min_time = np.min(times)
max_time = np.max(times)
fps = 1000 / avg_time

print(f'\n性能统计:')
print(f'平均推理时间: {avg_time:.2f} ± {std_time:.2f} ms')
print(f'最小时间: {min_time:.2f} ms')
print(f'最大时间: {max_time:.2f} ms')
print(f'FPS: {fps:.2f}')

# 绘制时间分布
plt.figure(figsize=(10, 4))
plt.hist(times, bins=30, edgecolor='black')
plt.xlabel('推理时间 (ms)')
plt.ylabel('频次')
plt.title('推理时间分布')
plt.axvline(avg_time, color='r', linestyle='--', label=f'平均: {avg_time:.2f} ms')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

7. 批量推理

In [ ]:
import os
import pandas as pd

# 测试图像目录
TEST_DIR = 'test_images/'

# 获取所有图像
image_files = [f for f in os.listdir(TEST_DIR) 
               if f.lower().endswith(('.png', '.jpg', '.jpeg'))]

print(f'找到 {len(image_files)} 张测试图像')

# 批量推理
results = []
for img_file in image_files:
    img_path = os.path.join(TEST_DIR, img_file)
    
    # 预处理
    img = preprocess_image(img_path)
    np.copyto(input_buffer, img)
    
    # 推理
    dma.sendchannel.transfer(input_buffer)
    dma.recvchannel.transfer(output_buffer)
    dma.sendchannel.wait()
    dma.recvchannel.wait()
    
    # 结果
    output = np.array(output_buffer)
    class_id = np.argmax(output)
    confidence = output[class_id]
    
    results.append({
        'image': img_file,
        'class': class_id,
        'class_name': class_names[class_id],
        'confidence': confidence
    })

# 显示结果
df = pd.DataFrame(results)
print('\n推理结果:')
print(df)

# 保存结果
df.to_csv('batch_results.csv', index=False)
print('\n结果已保存到 batch_results.csv')

8. 清理资源

In [ ]:
# 释放缓冲区
input_buffer.freebuffer()
output_buffer.freebuffer()

print('资源清理完成')