Raspberry Pi AI Camera 使用 12.3 兆像素 Sony IMX500 成像传感器,为任何相机应用提供低延迟、高性能的 AI 能力。
与Raspberry Pi 相机软件栈紧密集成,使用户能够以最小的工作量部署自己的神经网络模型。
本节演示如何在相机上运行预打包或自定义神经网络模型。此外,本节还包括解释在 IMX500 上运行的神经网络所生成的推理数据所需的步骤,具体在rpicam-apps和Picamera2.
用户指南
入门指南
以下说明描述如何在 Raspberry Pi AI Camera 上运行预打包的 MobileNet SSD 和 PoseNet 神经网络模型。
硬件设置
按照以下位置的说明将相机连接到 Raspberry Pi 板:安装 Raspberry Pi 相机.
先决条件
这些说明假设你使用的是连接到 Raspberry Pi 4 Model B 或 Raspberry Pi 5 板的 AI Camera,并且运行的是最新.
的 Raspberry Pi OS。稍作修改后,你可以在任何其他带相机连接器的 Raspberry Pi 型号上遵循这些说明,包括 Raspberry Pi Zero 型号。
该命令:
AI摄像头必须在启动时将运行时固件下载到IMX500传感器上。要将这些固件文件安装到你的树莓派上,请运行以下命令:
$ sudo apt install imx500-all
将若干神经网络模型固件文件放置于
-
将IMX500后处理软件阶段安装至
/lib/firmware/imx500_loader.fpkand/lib/firmware/imx500_firmware.fpkfirmware files required to operate the IMX500 sensor. -
将索尼网络模型打包工具安装到位
/usr/share/imx500-models/. -
IMX500内核驱动程序会在相机启动时加载所有固件文件,如果神经网络模型固件此前未被缓存,这一过程可能需要数分钟时间。我们在此使用的示例演示会在控制台显示进度条,以实时提示固件加载的进展情况。
rpicam-apps. -
安装 Sony 网络模型打包工具。
| IMX500 内核设备驱动程序会在相机启动时加载所有固件文件。如果神经网络模型固件之前未被缓存,这可能需要几分钟。以下演示会在控制台上显示进度条,以指示固件加载进度。 |
重启
现在您已经完成了先决条件的安装,接下来请重启您的树莓派:
$ sudo reboot
运行示例应用程序
在所有系统包更新且固件文件安装完成后,我们可以开始运行一些示例应用程序。Raspberry Pi AI Camera 与libcamera, rpicam-apps, and Picamera2.
rpicam-apps
该rpicam-apps camera applications其中包括 IMX500 物体检测和姿态估计模块,这些模块可在后处理管道中运行。有关后处理管道的更多信息,请参阅……后处理文档.
本页中的示例使用位于……的后处理 JSON 文件。/usr/share/rpi-camera-assets/.
物体检测
MobileNet SSD 神经网络执行基本对象检测,为找到的每个对象提供边界框和置信度值。文件imx500_mobilenet_ssd.json contains the configuration parameters for the IMX500 object detection post-processing stage using the MobileNet SSD neural network.
imx500_mobilenet_ssd.json declares a post-processing pipeline that contains two stages:
-
imx500_object_detection, which picks out bounding boxes and confidence values generated by the neural network in the output tensor. -
object_detect_draw_cv, which draws bounding boxes and labels on the image.
MobileNet SSD 张量在树莓派上无需进行大量后处理即可生成最终的边界框输出。所有物体检测均直接在 AI 摄像头上完成。
以下命令运行rpicam-hello with object detection post-processing:
$ rpicam-hello -t 0s --post-process-file /usr/share/rpi-camera-assets/imx500_mobilenet_ssd.json --viewfinder-width 1920 --viewfinder-height 1080 --framerate 30
运行命令后,你会看到一个取景器,它会在神经网络识别出的对象上叠加边界框:
要录制带有物体检测叠加效果的视频,请使用……rpicam-vid instead:
$ rpicam-vid -t 10s -o output.264 --post-process-file /usr/share/rpi-camera-assets/imx500_mobilenet_ssd.json --width 1920 --height 1080 --framerate 30
您可以对……进行配置。imx500_object_detection stage in many ways.
例如,max_detections defines the maximum number of objects that the pipeline detects at any given time. threshold defines the minimum confidence value required for the pipeline to consider any input as an object.
该网络的原始推理输出数据可能相当嘈杂,因此这一阶段还会进行一定的时序滤波并应用迟滞机制。若要禁用此滤波功能,请移除……temporal_filter config block.
姿态估计
PoseNet 神经网络可执行姿态估计,为身体上与关节和肢体相关的关键点标注位置。imx500_posenet.json contains the configuration parameters for the IMX500 pose estimation post-processing stage using the PoseNet neural network.
imx500_posenet.json declares a post-processing pipeline that contains two stages:
-
imx500_posenet, which fetches the raw output tensor from the PoseNet neural network. -
plot_pose_cv, which draws line overlays on the image.
AI 摄像头可执行基础检测,但其输出张量仍需在主机树莓派上进行额外的后处理,以生成最终结果。
以下命令运行rpicam-hello with pose estimation post-processing:
$ rpicam-hello -t 0s --post-process-file /usr/share/rpi-camera-assets/imx500_posenet.json --viewfinder-width 1920 --viewfinder-height 1080 --framerate 30
您可以对……进行配置。imx500_posenet stage in many ways.
例如,max_detections defines the maximum number of bodies that the pipeline detects at any given time. threshold defines the minimum confidence value required for the pipeline to consider input as a body.
Picamera2
Picamera2是用于 Raspberry Pi 相机的 Python 库。它提供了一个 IMX500 辅助类,允许你访问 IMX500 相机模块的输入和输出张量。
有关使用 Picamera2 进行图像分类、对象检测、分割和姿态估计的示例,请参阅picamera2-examples GitHub repository.
大多数示例使用 OpenCV 进行一些额外处理。
要安装 OpenCV 和示例所需的其他依赖项:
-
从命令行运行以下命令:
$ sudo apt install python3-opencv python3-munkres
+
. 克隆picamera2-examples repository到你的 Raspberry Pi
. 切换到 IMX500 示例目录:
+
$ git clone https://github.com/raspberrypi/picamera2-examples.git
$ cd picamera2-examples/examples/imx500
+ . 从本目录运行以下脚本以运行 MobileNet SSD 目标检测演示:
+
$ python imx500_object_detection_demo.py --model /usr/share/imx500-models/imx500_network_ssd_mobilenetv2_fpnlite_320x320_pp.rpk
要在 Picamera2 中尝试姿态估计:
| 此演示使用 HigherHRNet 神经网络而不是 PoseNet: |
-
在命令行中,从同一目录运行以下脚本。
$ python imx500_pose_estimation_higherhrnet_demo.py=== 模型部署
要将新的神经网络模型部署到 Raspberry Pi AI Camera:
-
提供一个浮点神经网络模型(PyTorch 或 TensorFlow)。
-
通过 Edge-MDT(Edge AI Model Development Toolkit)运行该模型。
-
量化并压缩模型,使其能够使用 IMX500 摄像头模块上可用的资源运行。
-
转换将压缩后的模型转换为 IMX500 格式。
-
-
将模型打包成可在运行时加载到摄像头上的固件文件。
前两个步骤通常在性能更强的计算机(如台式机或服务器)上执行。您必须在 Raspberry Pi 上运行最后的打包步骤。
模型创建
神经网络模型的创建超出了本指南的范围,但您可以复用现有模型,或使用免费或付费工具训练自己的模型。
免费工具
量化、转换和打包用于 AI Camera 的训练模型所需的所有工具均可免费使用。诸如TensorFlow或PyTorch等框架提供广泛的预训练模型。
模型压缩与转换
Edge-MDT 安装
Edge-MDT(Model Development Toolkit)软件包会安装将模型量化、压缩并转换为可在你的 IMX500 设备上运行所需的全部工具。
Edge-MDT 软件包接受一个参数,用于选择安装 PyTorch 版还是 TensorFlow 版工具。
- PyTorch
-
$ pip install edge-mdt[pt] - TensorFlow
-
$ pip install edge-mdt[tf]始终使用与压缩模型时所用版本相同的 TensorFlow。
如果你需要安装这两个软件包,请使用两个独立的 Python 虚拟环境。这可以防止 TensorFlow 和 PyTorch 相互冲突。
模型优化
模型使用 Sony 的 Model Compression Toolkit (MCT) 进行量化和压缩。该工具会在 Edge-MDT 安装步骤中自动安装。有关更多信息,请参阅Sony 模型优化 GitHub 仓库.
Model Compression Toolkit 会生成以下格式的量化模型:
-
Keras (TensorFlow)
-
ONNX (PyTorch)
转换
转换器是一个命令行应用程序,用于编译量化模型(采用.onnx or .keras formats) into a binary file that can be packaged and loaded onto the AI Camera. This tool is automatically installed as part of the Edge-MDT installation step.
要转换模型:
- PyTorch
-
$ imxconv-pt -i <compressed ONNX model> -o <output folder> - TensorFlow
-
$ imxconv-tf -i <compressed Keras model> -o <output folder>
为了最佳利用 IMX500 传感器上加速器可用的内存,请添加--no-input-persistency to the previous commands. However, this disables input tensor generation that can be used for debugging purposes.
|
两个命令都会创建一个输出文件夹,其中包含内存使用报告和一个packerOut.zip file.
有关模型转换过程的更多信息,请参阅官方Sony IMX500 Converter 文档.
打包
| 你必须在运行 Raspberry Pi OS 的 Raspberry Pi 上执行此步骤。 |
最后一步会将模型打包为 RPK 文件。运行神经网络模型时,我们会将此文件上传到 AI Camera。继续之前,请运行以下命令以安装必要工具:
$ sudo apt install imx500-tools
要将模型打包为 RPK 文件,请运行以下命令:
$ imx500-package -i <path to packerOut.zip> -o <output folder>
此命令会创建一个名为network.rpk in the output folder. Pass the name of this file to your IMX500 camera applications.
有关更全面的说明以及所用工具的更多细节,请参阅Sony IMX500 Packager 文档.
编写你自己的应用程序
对于大多数用户,使用 Picamera2 在 Python 中创建应用程序要容易得多。如果你已经熟悉 Picamera2,并且了解诸如 之类的相邻 Python 包,这会有所帮助OpenCV and numpy.
如果你对 C++ 应用程序有特定需求,并且熟悉这种语言,rpicam-apps provides a helpful example to get you started, and shows how you might want to integrate further custom post-processing to the application. You can copy and reuse the rpicam-apps code, or create your own more custom solutions.
创建一个rpicam-apps post-processing stage
rpicam-apps provides an IMX500 post-processing stage base class that implements helpers for IMX500 post-processing stages: IMX500PostProcessingStage。使用此基类为在 IMX500 上运行的任何神经网络模型派生新的后处理阶段。有关示例,请参见imx500_object_detection.cpp:
class ObjectDetection : public IMX500PostProcessingStage
{
public:
ObjectDetection(RPiCamApp *app) : IMX500PostProcessingStage(app) {}
char const *Name() const override;
void Read(boost::property_tree::ptree const ¶ms) override;
void Configure() override;
bool Process(CompletedRequestPtr &completed_request) override;
};
对于应用程序接收到的每一帧,Process() function is called. In this function, you can extract the output tensor for further processing or analysis:
auto output = completed_request->metadata.get(controls::rpi::CnnOutputTensor);
if (!output)
{
LOG_ERROR("No output tensor found in metadata!");
return false;
}
std::vector<float> output_tensor(output->data(), output->data() + output->size());
完成后,最终结果既可以进行可视化,也可以保存在元数据中,并由另一个下游阶段或顶层应用程序本身使用。在对象推理场景中:
if (objects.size())
completed_request->post_process_metadata.Set("object_detect.results", objects);
该object_detect_draw_cv post-processing stage running downstream fetches these results from the metadata and draws the bounding boxes onto the image in the ObjectDetectDrawCvStage::Process() function:
std::vector<Detection> detections;
completed_request->post_process_metadata.Get("object_detect.results", detections);
有关辅助函数的完整列表,这些函数IMX500PostProcessingStage provides, see IMX500PostProcessingStage helpers.
将 AI Camera 与 Picamera2 配合使用
有关与 的逐函数比较rpicam-apps, see 比较rpicam-apps and Picamera2 helpers.
加载神经网络模型
将 IMX500 辅助类导入你的 Python 脚本,然后创建一个IMX500 object for your neural network model file:
from picamera2.devices.imx500 import IMX500
imx500 = IMX500(model_file)
创建IMX500 object before you create the Picamera2 object.
|
有关查询传感器和已加载神经网络的辅助函数,请参见模型和传感器信息.
读取输出张量
Picamera2 会在每个请求的元数据中返回输出张量。使用imx500.get_outputs() to retrieve them from the metadata, then apply additional processing in your Python script.
例如,在如下所示的对象推理用例中:imx500_object_detection_demo.py, parse_detections() extracts the object bounding boxes and confidence values, and draw_detections() draws the boxes on the image.
以下代码是摘录。它依赖于picam2, args, threshold, and get_labels(), which are defined elsewhere in the script.
class Detection:
def __init__(self, coords, category, conf, metadata):
"""Create a Detection object, recording the bounding box, category and confidence."""
self.category = category
self.conf = conf
obj_scaled = imx500.convert_inference_coords(coords, metadata, picam2)
self.box = (obj_scaled.x, obj_scaled.y, obj_scaled.width, obj_scaled.height)
def draw_detections(request, detections, stream="main"):
"""Draw the detections for this request onto the ISP output."""
labels = get_labels()
with MappedArray(request, stream) as m:
for detection in detections:
x, y, w, h = detection.box
label = f"{labels[int(detection.category)]} ({detection.conf:.2f})"
cv2.putText(m.array, label, (x + 5, y + 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
cv2.rectangle(m.array, (x, y), (x + w, y + h), (0, 0, 255, 0))
if args.preserve_aspect_ratio:
b = imx500.get_roi_scaled(request)
cv2.putText(m.array, "ROI", (b.x + 5, b.y + 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1)
cv2.rectangle(m.array, (b.x, b.y), (b.x + b.width, b.y + b.height), (255, 0, 0, 0))
def parse_detections(request, stream='main'):
"""Parse the output tensor into a number of detected objects, scaled to the ISP output."""
metadata = request.get_metadata()
outputs = imx500.get_outputs(metadata)
boxes, scores, classes = outputs[0][0], outputs[1][0], outputs[2][0]
detections = [ Detection(box, category, score, metadata)
for box, score, category in zip(boxes, scores, classes) if score > threshold]
draw_detections(request, detections, stream)
与 不同rpicam-apps example, this example applies no additional hysteresis or temporal filtering.
有关输出张量辅助函数,请参见输出张量.
设置 region of interest
有关 region of interest 辅助函数,请参见感兴趣区域.
转换坐标
有关坐标转换辅助函数,请参见坐标转换.
AI Camera 的工作原理
概述
Raspberry Pi AI Camera 的工作方式与传统基于 AI 的摄像头图像处理系统不同,如下图所示:
左侧展示了传统 AI 摄像头系统的架构。在此类系统中,摄像头将图像传送给 Raspberry Pi。Raspberry Pi 处理图像,然后执行 AI inferencing。传统系统可以使用外部 AI accelerator(如图所示),也可以完全依赖 CPU。
右侧展示了使用 IMX500 的系统的架构。摄像头模块包含一个小型 Image Signal Processor (ISP),它将原始摄像头图像数据转换为一个输入张量。摄像头模块将该 tensor 直接发送到摄像头内的 AI accelerator 中,后者产生输出张量,其中包含推理结果。AI accelerator 将这些 tensor 发送给 Raspberry Pi。无需外部 accelerator,也无需 Raspberry Pi 在 CPU 上运行 neural network software。
要完全理解该系统,请熟悉以下概念:
- 输入张量
-
传感器图像中传递给 AI engine 以进行推理的部分。由小型 on-board ISP 生成,该 ISP 还会裁剪并缩放摄像头图像,使其达到已加载的 neural network 所期望的尺寸。input tensor 通常不会提供给应用程序,不过可以为调试目的访问它。
- 感兴趣区域 (ROI)
-
精确指定在将传感器图像重新缩放到 neural network 所要求的大小之前,裁剪出传感器图像的哪一部分。可由应用程序查询和设置。使用的单位始终是全分辨率传感器输出中的像素。默认 ROI 设置使用从传感器接收的完整图像,不裁剪任何数据。
- 输出张量
-
由 neural network 执行的推理结果。输出的确切数量和形状取决于 neural network。应用程序代码必须了解如何处理这些 tensor。
系统架构
下图展示了在 Raspberry Pi AI Camera 模块硬件(红色)的成像和推理用例中使用的各种摄像头软件组件(绿色):
启动时,IMX500 传感器模块加载 firmware 以运行特定的 neural network model。在流式传输期间,IMX500 生成两者一个 image stream 和一个 inference stream。该 inference stream 包含 neural network model 的输入和输出,也称为 input 和 output张量.
设备驱动程序
在最底层,IMX500 传感器内核驱动通过 I2C 总线配置摄像头模块。CSI2 驱动(CFE on Raspberry Pi 5, Unicam on all other Raspberry Pi platforms) sets up the receiver to write the image data stream into a frame buffer, together with the embedded data and inference data streams into another buffer in memory.
固件文件也通过 I2C 总线导线传输。在大多数设备上,这使用标准 I2C 协议,但 Raspberry Pi 5 使用自定义高速协议。内核中的 RP2040 SPI 驱动负责固件文件传输,因为该传输使用 RP2040 微控制器。该微控制器通过 SPI 总线将来自内核的 I2C 传输桥接到 IMX500。此外,RP2040 将固件文件缓存在板载存储中。这避免了需要通过 I2C 总线传输整个固件 blob,从而显著加快你已使用过的固件的加载速度。
libcamera
在libcamera dequeues the image and inference data buffers from the kernel, the IMX500-specific cam-helper library (part of the Raspberry Pi image processing algorithms within libcamera) parses the inference buffer to access the input and output tensors. These tensors are packaged as Raspberry Pi vendor-specific libcamera controls。对于以下控件libcamera returns, see libcamera controls.
rpicam-apps
要编写自己的阶段,请参见创建一个rpicam-apps post-processing stage.
Picamera2
Picamera2 中的 IMX500 集成与以下内容中可用的非常相似rpicam-apps. Picamera2 has an IMX500 helper class that provides the same functionality as the rpicam-apps IMX500PostProcessingStage base class.
要在自己的脚本中使用它,请参见将 AI Camera 与 Picamera2 配合使用.
参考
libcamera controls
libcamera returns the following IMX500 controls:
| 控制 | 说明 |
|---|---|
|
存储输出张量的浮点数组。 |
|
存储输入张量的浮点数组。 |
|
描述输出张量结构的网络特定参数:
|
|
描述输入张量结构的网络特定参数:
|
IMX500PostProcessingStage helpers
下表包含由以下内容提供的辅助函数的完整列表:IMX500PostProcessingStage:
| 函数 | 说明 |
|---|---|
|
通常从以下位置调用: 此函数还会读取神经网络模型文件字符串( |
|
通常从以下位置调用: |
|
在传感器图像上设置绝对感兴趣区域(ROI)裁剪矩形,以用于在 IMX500 上进行推理。 |
|
自动计算传感器图像上的感兴趣区域(ROI)裁剪矩形,以针对给定神经网络保持输入张量的宽高比。 |
|
在控制台上显示进度条,显示神经网络固件上传到 IMX500 的进度。 |
|
从输入张量坐标空间转换到最终 ISP 输出图像空间。 从原始传感器图像到完全处理的 ISP 输出图像,会发生一系列缩放、裁剪和平移操作。此函数将输出张量提供的坐标转换为执行这些操作后的等效坐标。 |
Picamera2 IMX500 辅助函数
Picamera2 中的 IMX500 类提供以下辅助函数:
模型和传感器信息
| 函数或属性 | 说明 |
|---|---|
|
返回神经网络配置的字典。 |
|
返回 IMX500 的完整传感器分辨率。 |
|
根据所使用的神经网络模型返回输入 tensor 大小。 |
|
返回 ISP 输出图像大小。 |
输出张量
| 函数 | 说明 |
|---|---|
|
从 Picamera2 图像 metadata 中返回输出 tensor。 |
|
根据所使用的神经网络模型,从 Picamera2 图像 metadata 中返回输出 tensor 的形状。 |
感兴趣区域
| 函数 | 说明 |
|---|---|
|
设置感兴趣区域(ROI)裁剪矩形,该矩形决定传感器图像的哪一部分被转换为用于在 IMX500 上进行推理的输入 tensor。以完整传感器分辨率下的像素为单位指定感兴趣区域,形式为 |
|
自动计算传感器图像上的感兴趣区域(ROI)裁剪矩形,以保留给定纵横比。要使 ROI 纵横比与该网络的输入 tensor 完全匹配,请使用 |
|
返回 ISP 输出图像坐标空间中的感兴趣区域(ROI)。 |
坐标转换
| 函数 | 说明 |
|---|---|
|
转换坐标坐标从输入 tensor 坐标空间到最终 ISP 输出图像空间。必须传入该图像的 Picamera2 图像 metadata,以及 Picamera2 对象。 从原始传感器图像到完全处理的 ISP 输出图像,会发生一系列缩放、裁剪和平移操作。此函数将输出张量提供的坐标转换为执行这些操作后的等效坐标。 |
诊断
| 函数 | 说明 |
|---|---|
|
在控制台上显示进度条,显示神经网络固件上传到 IMX500 的进度。 |
|
返回 IMX500 为给定图像 metadata 记录的帧级性能指标。 |
比较rpicam-apps and Picamera2 helpers
下表映射了rpicam-apps IMX500PostProcessingStage base class to their equivalents in the Picamera2 IMX500 class:
| 用途 | rpicam-apps (IMX500PostProcessingStage) |
Picamera2(IMX500) |
|---|---|---|
加载神经网络模型 firmware |
|
|
设置绝对 ROI |
|
|
设置保留纵横比的 ROI |
|
|
将输出 tensor 坐标转换为 ISP 输出坐标 |
|
|
显示 firmware 上传进度 |
|
|