""" PYNQ Z2 推理脚本 在PYNQ板卡上运行MobileNetV2模型进行图像识别 """ import numpy as np import cv2 from pynq import Overlay, allocate import time from PIL import Image class MobileNetInference: """MobileNet推理类""" def __init__(self, bitstream_path, model_path=None): """ 初始化推理器 Args: bitstream_path: FPGA bitstream文件路径 model_path: 量化模型路径(可选) """ print("加载FPGA overlay...") self.overlay = Overlay(bitstream_path) # 获取DMA和加速器 self.dma = self.overlay.axi_dma_0 self.accelerator = self.overlay.mobilenet_accel_0 # 输入输出缓冲区 self.input_buffer = allocate(shape=(224, 224, 3), dtype=np.uint8) self.output_buffer = allocate(shape=(10,), dtype=np.float32) print("初始化完成!") def preprocess(self, image_path): """ 图像预处理 Args: image_path: 图像路径 Returns: preprocessed_image: 预处理后的图像 """ # 读取图像 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 inference(self, image_path): """ 执行推理 Args: image_path: 输入图像路径 Returns: class_id: 预测的类别ID confidence: 置信度 """ # 预处理 img = self.preprocess(image_path) # 复制到输入缓冲区 np.copyto(self.input_buffer, img) # 启动DMA传输 start_time = time.time() self.dma.sendchannel.transfer(self.input_buffer) self.dma.recvchannel.transfer(self.output_buffer) self.dma.sendchannel.wait() self.dma.recvchannel.wait() inference_time = time.time() - start_time # 获取结果 output = np.array(self.output_buffer) class_id = np.argmax(output) confidence = output[class_id] print(f"推理时间: {inference_time * 1000:.2f} ms") print(f"预测类别: {class_id}, 置信度: {confidence:.4f}") return class_id, confidence def __del__(self): """清理资源""" if hasattr(self, 'input_buffer'): self.input_buffer.freebuffer() if hasattr(self, 'output_buffer'): self.output_buffer.freebuffer() def main(): """主函数""" import argparse parser = argparse.ArgumentParser(description='PYNQ Z2 MobileNet推理') parser.add_argument('--bitstream', type=str, required=True, help='Bitstream文件路径') parser.add_argument('--image', type=str, required=True, help='输入图像路径') parser.add_argument('--model', type=str, default=None, help='模型文件路径') args = parser.parse_args() # 创建推理器 inferencer = MobileNetInference(args.bitstream, args.model) # 执行推理 class_id, confidence = inferencer.inference(args.image) # 类别名称映射 class_names = [f'{i}个光瓣' for i in range(10)] print(f"\n识别结果: {class_names[class_id]}") print(f"置信度: {confidence * 100:.2f}%") if __name__ == '__main__': main()