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

342 lines
8.4 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# PYNQ Z2 MobileNetV2 部署示例\n",
"本notebook演示如何在PYNQ Z2板卡上部署和运行MobileNetV2模型"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. 环境准备"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"sys.path.append('../fpga_deployment')\n",
"\n",
"import numpy as np\n",
"import cv2\n",
"import matplotlib.pyplot as plt\n",
"from PIL import Image\n",
"from pynq import Overlay, allocate\n",
"import time\n",
"\n",
"print('环境准备完成!')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. 加载FPGA Overlay"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 指定bitstream路径\n",
"BITSTREAM_PATH = 'mobilenet.bit'\n",
"\n",
"# 加载overlay\n",
"print('加载FPGA overlay...')\n",
"overlay = Overlay(BITSTREAM_PATH)\n",
"print('Overlay加载成功!')\n",
"\n",
"# 查看overlay信息\n",
"print('\\nOverlay IP核:')\n",
"print(overlay.ip_dict.keys())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. 初始化DMA和加速器"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 获取DMA\n",
"dma = overlay.axi_dma_0\n",
"print('DMA初始化完成')\n",
"\n",
"# 获取加速器\n",
"accelerator = overlay.mobilenet_accel_0\n",
"print('加速器初始化完成')\n",
"\n",
"# 分配输入输出缓冲区\n",
"input_buffer = allocate(shape=(224, 224, 3), dtype=np.float32)\n",
"output_buffer = allocate(shape=(10,), dtype=np.float32)\n",
"print('缓冲区分配完成')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. 图像预处理函数"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def preprocess_image(image_path):\n",
" \"\"\"预处理图像\"\"\"\n",
" # 读取图像\n",
" img = cv2.imread(image_path)\n",
" img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n",
" \n",
" # 调整大小\n",
" img = cv2.resize(img, (224, 224))\n",
" \n",
" # 归一化\n",
" img = img.astype(np.float32) / 255.0\n",
" mean = np.array([0.485, 0.456, 0.406])\n",
" std = np.array([0.229, 0.224, 0.225])\n",
" img = (img - mean) / std\n",
" \n",
" return img\n",
"\n",
"def show_image(image_path):\n",
" \"\"\"显示图像\"\"\"\n",
" img = cv2.imread(image_path)\n",
" img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n",
" plt.figure(figsize=(6, 6))\n",
" plt.imshow(img)\n",
" plt.axis('off')\n",
" plt.show()\n",
"\n",
"print('预处理函数定义完成')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5. 单张图像推理"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 指定测试图像\n",
"TEST_IMAGE = 'test.jpg'\n",
"\n",
"# 显示图像\n",
"print('测试图像:')\n",
"show_image(TEST_IMAGE)\n",
"\n",
"# 预处理\n",
"img = preprocess_image(TEST_IMAGE)\n",
"np.copyto(input_buffer, img)\n",
"\n",
"# 推理\n",
"print('\\n开始推理...')\n",
"start_time = time.time()\n",
"\n",
"dma.sendchannel.transfer(input_buffer)\n",
"dma.recvchannel.transfer(output_buffer)\n",
"dma.sendchannel.wait()\n",
"dma.recvchannel.wait()\n",
"\n",
"inference_time = time.time() - start_time\n",
"\n",
"# 获取结果\n",
"output = np.array(output_buffer)\n",
"class_id = np.argmax(output)\n",
"confidence = output[class_id]\n",
"\n",
"# 类别名称\n",
"class_names = [f'{i}个光瓣' for i in range(10)]\n",
"\n",
"print(f'推理时间: {inference_time * 1000:.2f} ms')\n",
"print(f'预测类别: {class_names[class_id]}')\n",
"print(f'置信度: {confidence * 100:.2f}%')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 6. 性能测试"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 多次推理测试性能\n",
"num_runs = 100\n",
"times = []\n",
"\n",
"print(f'运行 {num_runs} 次推理...')\n",
"for i in range(num_runs):\n",
" start = time.time()\n",
" \n",
" dma.sendchannel.transfer(input_buffer)\n",
" dma.recvchannel.transfer(output_buffer)\n",
" dma.sendchannel.wait()\n",
" dma.recvchannel.wait()\n",
" \n",
" end = time.time()\n",
" times.append((end - start) * 1000)\n",
" \n",
" if (i + 1) % 10 == 0:\n",
" print(f'进度: {i + 1}/{num_runs}')\n",
"\n",
"# 统计结果\n",
"avg_time = np.mean(times)\n",
"std_time = np.std(times)\n",
"min_time = np.min(times)\n",
"max_time = np.max(times)\n",
"fps = 1000 / avg_time\n",
"\n",
"print(f'\\n性能统计:')\n",
"print(f'平均推理时间: {avg_time:.2f} ± {std_time:.2f} ms')\n",
"print(f'最小时间: {min_time:.2f} ms')\n",
"print(f'最大时间: {max_time:.2f} ms')\n",
"print(f'FPS: {fps:.2f}')\n",
"\n",
"# 绘制时间分布\n",
"plt.figure(figsize=(10, 4))\n",
"plt.hist(times, bins=30, edgecolor='black')\n",
"plt.xlabel('推理时间 (ms)')\n",
"plt.ylabel('频次')\n",
"plt.title('推理时间分布')\n",
"plt.axvline(avg_time, color='r', linestyle='--', label=f'平均: {avg_time:.2f} ms')\n",
"plt.legend()\n",
"plt.grid(True, alpha=0.3)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 7. 批量推理"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import pandas as pd\n",
"\n",
"# 测试图像目录\n",
"TEST_DIR = 'test_images/'\n",
"\n",
"# 获取所有图像\n",
"image_files = [f for f in os.listdir(TEST_DIR) \n",
" if f.lower().endswith(('.png', '.jpg', '.jpeg'))]\n",
"\n",
"print(f'找到 {len(image_files)} 张测试图像')\n",
"\n",
"# 批量推理\n",
"results = []\n",
"for img_file in image_files:\n",
" img_path = os.path.join(TEST_DIR, img_file)\n",
" \n",
" # 预处理\n",
" img = preprocess_image(img_path)\n",
" np.copyto(input_buffer, img)\n",
" \n",
" # 推理\n",
" dma.sendchannel.transfer(input_buffer)\n",
" dma.recvchannel.transfer(output_buffer)\n",
" dma.sendchannel.wait()\n",
" dma.recvchannel.wait()\n",
" \n",
" # 结果\n",
" output = np.array(output_buffer)\n",
" class_id = np.argmax(output)\n",
" confidence = output[class_id]\n",
" \n",
" results.append({\n",
" 'image': img_file,\n",
" 'class': class_id,\n",
" 'class_name': class_names[class_id],\n",
" 'confidence': confidence\n",
" })\n",
"\n",
"# 显示结果\n",
"df = pd.DataFrame(results)\n",
"print('\\n推理结果:')\n",
"print(df)\n",
"\n",
"# 保存结果\n",
"df.to_csv('batch_results.csv', index=False)\n",
"print('\\n结果已保存到 batch_results.csv')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 8. 清理资源"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 释放缓冲区\n",
"input_buffer.freebuffer()\n",
"output_buffer.freebuffer()\n",
"\n",
"print('资源清理完成')"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.0"
}
},
"nbformat": 4,
"nbformat_minor": 4
}