Raspberry Pi 4 上的实时推理 (30 fps!)¶
创建于:2022 年 2 月 8 日 | 最后更新:2024 年 1 月 16 日 | 最后验证:2024 年 11 月 05 日
作者: Tristan Rice
PyTorch 提供了对 Raspberry Pi 4 的开箱即用支持。本教程将指导您如何在 Raspberry Pi 4 上设置 PyTorch,并在 CPU 上实时运行 MobileNet v2 分类模型(30 fps 以上)。
所有测试均使用 Raspberry Pi 4 Model B 4GB 进行,但也应适用于 2GB 版本以及性能降低的 3B。

先决条件¶
要学习本教程,您需要 Raspberry Pi 4、摄像头以及所有其他标准配件。
散热片和风扇(可选但推荐)
5V 3A USB-C 电源
SD 卡(至少 8gb)
SD 卡读卡器/写卡器
Raspberry Pi 4 设置¶
PyTorch 仅为 Arm 64 位 (aarch64) 提供 pip 包,因此您需要在 Raspberry Pi 上安装 64 位版本的操作系统
您可以从 https://downloads.raspberrypi.org/raspios_arm64/images/ 下载最新的 arm64 Raspberry Pi OS,并通过 rpi-imager 安装它。
32 位 Raspberry Pi OS 将无法工作。

安装将至少需要几分钟,具体取决于您的互联网速度和 sdcard 速度。完成后,它应该看起来像

现在可以将您的 sdcard 放入 Raspberry Pi,连接摄像头并启动它。

启动并完成初始设置后,您需要编辑 /boot/config.txt
文件以启用摄像头。
# This enables the extended features such as the camera.
start_x=1
# This needs to be at least 128M for the camera processing, if it's bigger you can just leave it as is.
gpu_mem=128
# You need to commment/remove the existing camera_auto_detect line since this causes issues with OpenCV/V4L2 capture.
#camera_auto_detect=1
然后重启。重启后,video4linux2 设备 /dev/video0
应该存在。
安装 PyTorch 和 OpenCV¶
PyTorch 和我们需要的其他所有库都具有 ARM 64 位/aarch64 变体,因此您只需通过 pip 安装它们,就可以像其他任何 Linux 系统一样工作。
$ pip install torch torchvision torchaudio
$ pip install opencv-python
$ pip install numpy --upgrade

我们现在可以检查一切是否安装正确
$ python -c "import torch; print(torch.__version__)"

视频捕获¶
对于视频捕获,我们将使用 OpenCV 来流式传输视频帧,而不是更常见的 picamera
。picamera 在 64 位 Raspberry Pi OS 上不可用,并且比 OpenCV 慢得多。OpenCV 直接访问 /dev/video0
设备以抓取帧。
我们使用的模型 (MobileNetV2) 接受 224x224
的图像尺寸,因此我们可以直接从 OpenCV 以 36fps 的速度请求。我们的模型目标是 30fps,但我们请求的帧速率略高于此值,以便始终有足够的帧。
import cv2
from PIL import Image
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 224)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 224)
cap.set(cv2.CAP_PROP_FPS, 36)
OpenCV 返回 BGR 中的 numpy
数组,因此我们需要读取并进行一些混洗以将其转换为预期的 RGB 格式。
ret, image = cap.read()
# convert opencv output from BGR to RGB
image = image[:, :, [2, 1, 0]]
此数据读取和处理大约需要 3.5 毫秒
。
图像预处理¶
我们需要获取帧并将它们转换为模型期望的格式。这与您在任何机器上使用标准 torchvision 变换所做的处理相同。
from torchvision import transforms
preprocess = transforms.Compose([
# convert the frame to a CHW torch tensor for training
transforms.ToTensor(),
# normalize the colors to the range that mobilenet_v2/3 expect
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
input_tensor = preprocess(image)
# The model can handle multiple images simultaneously so we need to add an
# empty dimension for the batch.
# [3, 224, 224] -> [1, 3, 224, 224]
input_batch = input_tensor.unsqueeze(0)
模型选择¶
您可以选择许多模型来使用,它们具有不同的性能特征。并非所有模型都提供 qnnpack
预训练变体,因此出于测试目的,您应该选择一个提供该变体的模型,但如果您训练和量化自己的模型,则可以使用任何模型。
在本教程中,我们使用 mobilenet_v2
,因为它具有良好的性能和准确性。
Raspberry Pi 4 基准测试结果
模型 |
FPS |
总时间(毫秒/帧) |
模型时间(毫秒/帧) |
qnnpack 预训练 |
---|---|---|---|---|
mobilenet_v2 |
33.7 |
29.7 |
26.4 |
真 |
mobilenet_v3_large |
29.3 |
34.1 |
30.7 |
真 |
resnet18 |
9.2 |
109.0 |
100.3 |
假 |
resnet50 |
4.3 |
233.9 |
225.2 |
假 |
resnext101_32x8d |
1.1 |
892.5 |
885.3 |
假 |
inception_v3 |
4.9 |
204.1 |
195.5 |
假 |
googlenet |
7.4 |
135.3 |
132.0 |
假 |
shufflenet_v2_x0_5 |
46.7 |
21.4 |
18.2 |
假 |
shufflenet_v2_x1_0 |
24.4 |
41.0 |
37.7 |
假 |
shufflenet_v2_x1_5 |
16.8 |
59.6 |
56.3 |
假 |
shufflenet_v2_x2_0 |
11.6 |
86.3 |
82.7 |
假 |
MobileNetV2:量化和 JIT¶
为了获得最佳性能,我们希望模型是量化和融合的。量化意味着它使用 int8 进行计算,这比标准 float32 数学运算效率更高。融合意味着连续操作已融合在一起,成为性能更高的版本(如果可能)。通常,像激活函数 (ReLU
) 这样的东西可以在推理期间合并到之前的层 (Conv2d
) 中。
pytorch 的 aarch64 版本需要使用 qnnpack
引擎。
import torch
torch.backends.quantized.engine = 'qnnpack'
对于此示例,我们将使用 torchvision 开箱即用的 MobileNetV2 的预量化和融合版本。
from torchvision import models
net = models.quantization.mobilenet_v2(pretrained=True, quantize=True)
然后我们希望 jit 模型以减少 Python 开销并融合任何操作。Jit 使我们获得约 30fps,而不是没有它时的约 20fps。
net = torch.jit.script(net)
整合在一起¶
我们现在可以将所有部分整合在一起并运行它
import time
import torch
import numpy as np
from torchvision import models, transforms
import cv2
from PIL import Image
torch.backends.quantized.engine = 'qnnpack'
cap = cv2.VideoCapture(0, cv2.CAP_V4L2)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 224)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 224)
cap.set(cv2.CAP_PROP_FPS, 36)
preprocess = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
net = models.quantization.mobilenet_v2(pretrained=True, quantize=True)
# jit model to take it from ~20fps to ~30fps
net = torch.jit.script(net)
started = time.time()
last_logged = time.time()
frame_count = 0
with torch.no_grad():
while True:
# read frame
ret, image = cap.read()
if not ret:
raise RuntimeError("failed to read frame")
# convert opencv output from BGR to RGB
image = image[:, :, [2, 1, 0]]
permuted = image
# preprocess
input_tensor = preprocess(image)
# create a mini-batch as expected by the model
input_batch = input_tensor.unsqueeze(0)
# run model
output = net(input_batch)
# do something with output ...
# log model performance
frame_count += 1
now = time.time()
if now - last_logged > 1:
print(f"{frame_count / (now-last_logged)} fps")
last_logged = now
frame_count = 0
运行它表明我们徘徊在约 30 fps。

这是使用 Raspberry Pi OS 中的所有默认设置。如果您禁用了 UI 和默认启用的所有其他后台服务,则性能更高且更稳定。
如果我们检查 htop
,我们会看到我们几乎有 100% 的利用率。

为了验证它是否端到端工作,我们可以计算类的概率,并使用 ImageNet 类标签来打印检测结果。
top = list(enumerate(output[0].softmax(dim=0)))
top.sort(key=lambda x: x[1], reverse=True)
for idx, val in top[:10]:
print(f"{val.item()*100:.2f}% {classes[idx]}")
mobilenet_v3_large
实时运行

检测到一个橙子

检测到一个马克杯

故障排除:性能¶
PyTorch 默认将使用所有可用的内核。如果您的 Raspberry Pi 上有任何后台运行程序,则可能会导致模型推理发生争用,从而导致延迟峰值。为了缓解这种情况,您可以减少线程数,这将以较小的性能损失来降低峰值延迟。
torch.set_num_threads(2)
对于 shufflenet_v2_x1_5
,使用 2 个线程
而不是 4 个线程
会将最佳情况延迟从 60 毫秒
增加到 72 毫秒
,但消除了 128 毫秒
的延迟峰值。
下一步¶
您可以创建自己的模型或微调现有模型。如果您在 torchvision.models.quantized 中的模型之一上进行微调,则大部分融合和量化工作已经为您完成,因此您可以直接部署并在 Raspberry Pi 上获得良好的性能。
查看更多