Initial public project cleanup
This commit is contained in:
commit
2034b04519
95 files changed
+16583
No files matched your search
@@ -0,0 +1,191 @@
|
||||
"""
|
||||
PYNQ inference script for the DDR-backed HLS-QCNN accelerator.
|
||||
|
||||
Single image:
|
||||
python3 hls_qcnn_inference.py --bitstream hls_qcnn.bit --weights hls_qcnn_weights_flat.npy --image test_images/class_0/10.jpg
|
||||
|
||||
Validation set:
|
||||
python3 hls_qcnn_inference.py --bitstream hls_qcnn.bit --weights hls_qcnn_weights_flat.npy --test_dir test_images
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
# Some PYNQ-Z2 v2.7 images expose pynq through /home/xilinx/pynq and rely on
|
||||
# XILINX_XRT being present in login shells. Keep the script robust when it is
|
||||
# launched by SSH from a subdirectory.
|
||||
os.environ.setdefault("XILINX_XRT", "/usr")
|
||||
if os.path.isdir("/home/xilinx") and "/home/xilinx" not in sys.path:
|
||||
sys.path.insert(0, "/home/xilinx")
|
||||
|
||||
from pynq import Overlay, allocate
|
||||
|
||||
|
||||
IMG_SIZE = 128
|
||||
NUM_CLASSES = 10
|
||||
ACT_SCALE = 1024
|
||||
IMAGE_WORDS = (IMG_SIZE * IMG_SIZE * 3) // 4
|
||||
FEATURE_BUFFER_SIZE = 16 * IMG_SIZE * IMG_SIZE
|
||||
|
||||
|
||||
def preprocess_image(image_path):
|
||||
image = Image.open(image_path).convert("RGB").resize((IMG_SIZE, IMG_SIZE))
|
||||
pixels = np.asarray(image, dtype=np.uint8).reshape(-1).astype(np.uint32)
|
||||
pad = (-pixels.size) % 4
|
||||
if pad:
|
||||
pixels = np.pad(pixels, (0, pad), constant_values=0)
|
||||
words = (
|
||||
pixels[0::4]
|
||||
| (pixels[1::4] << 8)
|
||||
| (pixels[2::4] << 16)
|
||||
| (pixels[3::4] << 24)
|
||||
)
|
||||
return words.astype(np.uint32)
|
||||
|
||||
|
||||
def write_u64(ip, offset, value):
|
||||
value = int(value)
|
||||
ip.write(offset, value & 0xFFFFFFFF)
|
||||
ip.write(offset + 4, (value >> 32) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
class HLSQCNNAccelerator:
|
||||
def __init__(self, bitstream_path, weights_path):
|
||||
self.overlay = Overlay(bitstream_path)
|
||||
self.accel = self.overlay.hls_qcnn_accel_0
|
||||
|
||||
weights_np = np.load(weights_path).astype(np.int16).reshape(-1)
|
||||
self.image_buffer = allocate(shape=(IMAGE_WORDS,), dtype=np.uint32)
|
||||
self.weights_buffer = allocate(shape=(weights_np.size,), dtype=np.int16)
|
||||
self.buf0 = allocate(shape=(FEATURE_BUFFER_SIZE,), dtype=np.int16)
|
||||
self.buf1 = allocate(shape=(FEATURE_BUFFER_SIZE,), dtype=np.int16)
|
||||
self.logits_buffer = allocate(shape=(NUM_CLASSES,), dtype=np.int32)
|
||||
self.weights_buffer[:] = weights_np
|
||||
self.weights_buffer.flush()
|
||||
|
||||
def close(self):
|
||||
for name in ("image_buffer", "weights_buffer", "buf0", "buf1", "logits_buffer"):
|
||||
if hasattr(self, name):
|
||||
getattr(self, name).freebuffer()
|
||||
|
||||
def start(self):
|
||||
# Register offsets generated by Vitis HLS for pointer arguments:
|
||||
# 0x10 image_words, 0x1c weights, 0x28 buf0, 0x34 buf1, 0x40 logits.
|
||||
write_u64(self.accel, 0x10, self.image_buffer.physical_address)
|
||||
write_u64(self.accel, 0x1C, self.weights_buffer.physical_address)
|
||||
write_u64(self.accel, 0x28, self.buf0.physical_address)
|
||||
write_u64(self.accel, 0x34, self.buf1.physical_address)
|
||||
write_u64(self.accel, 0x40, self.logits_buffer.physical_address)
|
||||
self.accel.write(0x00, 0x01)
|
||||
while (self.accel.read(0x00) & 0x2) == 0:
|
||||
pass
|
||||
|
||||
def infer_words(self, image_words):
|
||||
self.image_buffer[:] = image_words
|
||||
self.logits_buffer[:] = 0
|
||||
self.image_buffer.flush()
|
||||
self.logits_buffer.flush()
|
||||
|
||||
start = time.time()
|
||||
self.start()
|
||||
elapsed = time.time() - start
|
||||
|
||||
self.logits_buffer.invalidate()
|
||||
logits = np.asarray(self.logits_buffer, dtype=np.int32).copy()
|
||||
pred = int(np.argmax(logits))
|
||||
return pred, logits, elapsed
|
||||
|
||||
def infer_image(self, image_path):
|
||||
return self.infer_words(preprocess_image(image_path))
|
||||
|
||||
|
||||
def test_single(accel, image_path):
|
||||
pred, logits, elapsed = accel.infer_image(image_path)
|
||||
print(f"image: {image_path}")
|
||||
print(f"predicted class: {pred}")
|
||||
print(f"logits: {logits.tolist()}")
|
||||
print(f"inference time: {elapsed * 1000:.2f} ms")
|
||||
return pred, elapsed
|
||||
|
||||
|
||||
def test_dataset(accel, test_dir):
|
||||
total = 0
|
||||
correct = 0
|
||||
times = []
|
||||
class_total = [0] * NUM_CLASSES
|
||||
class_correct = [0] * NUM_CLASSES
|
||||
|
||||
for class_idx in range(NUM_CLASSES):
|
||||
class_dir = os.path.join(test_dir, f"class_{class_idx}")
|
||||
if not os.path.isdir(class_dir):
|
||||
print(f"missing class directory: {class_dir}")
|
||||
continue
|
||||
for image_name in sorted(os.listdir(class_dir)):
|
||||
if not image_name.lower().endswith((".jpg", ".jpeg", ".png")):
|
||||
continue
|
||||
image_path = os.path.join(class_dir, image_name)
|
||||
pred, _, elapsed = accel.infer_image(image_path)
|
||||
total += 1
|
||||
class_total[class_idx] += 1
|
||||
class_correct[class_idx] += int(pred == class_idx)
|
||||
correct += int(pred == class_idx)
|
||||
times.append(elapsed)
|
||||
print(f"{total:03d} label={class_idx} pred={pred} {image_name}")
|
||||
|
||||
if total == 0:
|
||||
print("no images found")
|
||||
return
|
||||
|
||||
accuracy = 100.0 * correct / total
|
||||
avg_time = float(np.mean(times))
|
||||
fps = 1.0 / avg_time if avg_time > 0 else 0.0
|
||||
print(f"accuracy: {accuracy:.2f}% ({correct}/{total})")
|
||||
print(f"average time: {avg_time * 1000:.2f} ms")
|
||||
print(f"fps: {fps:.2f}")
|
||||
for class_idx in range(NUM_CLASSES):
|
||||
if class_total[class_idx]:
|
||||
class_acc = 100.0 * class_correct[class_idx] / class_total[class_idx]
|
||||
print(f"class_{class_idx}: {class_acc:.2f}% ({class_correct[class_idx]}/{class_total[class_idx]})")
|
||||
|
||||
|
||||
def benchmark(accel, image_path, runs):
|
||||
words = preprocess_image(image_path)
|
||||
for _ in range(2):
|
||||
accel.infer_words(words)
|
||||
times = []
|
||||
for _ in range(runs):
|
||||
_, _, elapsed = accel.infer_words(words)
|
||||
times.append(elapsed)
|
||||
avg_time = float(np.mean(times))
|
||||
print(f"benchmark runs: {runs}")
|
||||
print(f"average time: {avg_time * 1000:.2f} ms")
|
||||
print(f"fps: {1.0 / avg_time:.2f}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="HLS-QCNN PYNQ inference")
|
||||
parser.add_argument("--bitstream", required=True)
|
||||
parser.add_argument("--weights", required=True)
|
||||
parser.add_argument("--image", default=None)
|
||||
parser.add_argument("--test_dir", default=None)
|
||||
parser.add_argument("--runs", type=int, default=10)
|
||||
args = parser.parse_args()
|
||||
|
||||
accel = HLSQCNNAccelerator(args.bitstream, args.weights)
|
||||
try:
|
||||
if args.image:
|
||||
test_single(accel, args.image)
|
||||
benchmark(accel, args.image, args.runs)
|
||||
if args.test_dir:
|
||||
test_dataset(accel, args.test_dir)
|
||||
finally:
|
||||
accel.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,131 @@
|
||||
"""
|
||||
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()
|
||||
@@ -0,0 +1,122 @@
|
||||
"""
|
||||
简化的推理脚本 - 不依赖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()
|
||||
@@ -0,0 +1,147 @@
|
||||
"""
|
||||
PYNQ inference script for the HLS TinyCNN accelerator.
|
||||
|
||||
Single image:
|
||||
python3 tiny_cnn_inference.py --bitstream tiny_cnn.bit --image test_images/class_0/10.jpg
|
||||
|
||||
Validation set:
|
||||
python3 tiny_cnn_inference.py --bitstream tiny_cnn.bit --test_dir test_images --runs 100
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from pynq import Overlay, allocate
|
||||
|
||||
|
||||
IMG_SIZE = 64
|
||||
NUM_CLASSES = 10
|
||||
|
||||
|
||||
def preprocess_image(image_path):
|
||||
image = Image.open(image_path).convert("L")
|
||||
image = image.resize((IMG_SIZE, IMG_SIZE))
|
||||
return np.asarray(image, dtype=np.uint8).reshape(-1)
|
||||
|
||||
|
||||
class TinyCNNAccelerator:
|
||||
def __init__(self, bitstream_path):
|
||||
self.overlay = Overlay(bitstream_path)
|
||||
self.dma = self.overlay.axi_dma_0
|
||||
self.accel = self.overlay.tiny_cnn_accel_0
|
||||
self.input_buffer = allocate(shape=(IMG_SIZE * IMG_SIZE,), dtype=np.uint32)
|
||||
self.output_buffer = allocate(shape=(NUM_CLASSES,), dtype=np.int32)
|
||||
|
||||
def close(self):
|
||||
if hasattr(self, "input_buffer"):
|
||||
self.input_buffer.freebuffer()
|
||||
if hasattr(self, "output_buffer"):
|
||||
self.output_buffer.freebuffer()
|
||||
|
||||
def infer_pixels(self, pixels_u8):
|
||||
self.input_buffer[:] = pixels_u8.astype(np.uint32)
|
||||
self.output_buffer[:] = 0
|
||||
|
||||
start = time.time()
|
||||
self.dma.recvchannel.transfer(self.output_buffer)
|
||||
self.dma.sendchannel.transfer(self.input_buffer)
|
||||
self.accel.write(0x00, 0x01)
|
||||
self.dma.sendchannel.wait()
|
||||
self.dma.recvchannel.wait()
|
||||
elapsed = time.time() - start
|
||||
|
||||
logits = np.asarray(self.output_buffer, dtype=np.int32).copy()
|
||||
pred = int(np.argmax(logits))
|
||||
return pred, logits, elapsed
|
||||
|
||||
def infer_image(self, image_path):
|
||||
pixels = preprocess_image(image_path)
|
||||
return self.infer_pixels(pixels)
|
||||
|
||||
|
||||
def test_single(accel, image_path):
|
||||
pred, logits, elapsed = accel.infer_image(image_path)
|
||||
print(f"image: {image_path}")
|
||||
print(f"predicted class: {pred}")
|
||||
print(f"logits: {logits.tolist()}")
|
||||
print(f"inference time: {elapsed * 1000:.2f} ms")
|
||||
return pred, elapsed
|
||||
|
||||
|
||||
def test_dataset(accel, test_dir):
|
||||
total = 0
|
||||
correct = 0
|
||||
times = []
|
||||
class_total = [0] * NUM_CLASSES
|
||||
class_correct = [0] * NUM_CLASSES
|
||||
|
||||
for class_idx in range(NUM_CLASSES):
|
||||
class_dir = os.path.join(test_dir, f"class_{class_idx}")
|
||||
if not os.path.isdir(class_dir):
|
||||
print(f"missing class directory: {class_dir}")
|
||||
continue
|
||||
for image_name in sorted(os.listdir(class_dir)):
|
||||
if not image_name.lower().endswith((".jpg", ".jpeg", ".png")):
|
||||
continue
|
||||
image_path = os.path.join(class_dir, image_name)
|
||||
pred, _, elapsed = accel.infer_image(image_path)
|
||||
total += 1
|
||||
class_total[class_idx] += 1
|
||||
times.append(elapsed)
|
||||
if pred == class_idx:
|
||||
correct += 1
|
||||
class_correct[class_idx] += 1
|
||||
|
||||
if total == 0:
|
||||
print("no images found")
|
||||
return
|
||||
|
||||
accuracy = 100.0 * correct / total
|
||||
avg_time = float(np.mean(times))
|
||||
fps = 1.0 / avg_time if avg_time > 0 else 0.0
|
||||
print(f"accuracy: {accuracy:.2f}% ({correct}/{total})")
|
||||
print(f"average time: {avg_time * 1000:.2f} ms")
|
||||
print(f"fps: {fps:.2f}")
|
||||
for class_idx in range(NUM_CLASSES):
|
||||
if class_total[class_idx]:
|
||||
class_acc = 100.0 * class_correct[class_idx] / class_total[class_idx]
|
||||
print(f"class_{class_idx}: {class_acc:.2f}% ({class_correct[class_idx]}/{class_total[class_idx]})")
|
||||
|
||||
|
||||
def benchmark(accel, image_path, runs):
|
||||
pixels = preprocess_image(image_path)
|
||||
for _ in range(5):
|
||||
accel.infer_pixels(pixels)
|
||||
times = []
|
||||
for _ in range(runs):
|
||||
_, _, elapsed = accel.infer_pixels(pixels)
|
||||
times.append(elapsed)
|
||||
avg_time = float(np.mean(times))
|
||||
print(f"benchmark runs: {runs}")
|
||||
print(f"average time: {avg_time * 1000:.2f} ms")
|
||||
print(f"fps: {1.0 / avg_time:.2f}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="TinyCNN HLS PYNQ inference")
|
||||
parser.add_argument("--bitstream", required=True)
|
||||
parser.add_argument("--image", default=None)
|
||||
parser.add_argument("--test_dir", default=None)
|
||||
parser.add_argument("--runs", type=int, default=100)
|
||||
args = parser.parse_args()
|
||||
|
||||
accel = TinyCNNAccelerator(args.bitstream)
|
||||
try:
|
||||
if args.image:
|
||||
test_single(accel, args.image)
|
||||
benchmark(accel, args.image, args.runs)
|
||||
if args.test_dir:
|
||||
test_dataset(accel, args.test_dir)
|
||||
finally:
|
||||
accel.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,143 @@
|
||||
"""
|
||||
工具函数
|
||||
"""
|
||||
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}')
|
||||
Reference in new issue
Block a user