本文档介绍了如何配合 Raspberry Pi 软件工具使用 Raspberry Pi Camera Modules。

所有 Raspberry Pi 摄像头均可配合我们的软件工具拍摄高分辨率照片和全高清 1080p 视频(或更高分辨率)。

如需了解有关 Raspberry Pi 摄像头硬件的更多信息,请参阅摄像头硬件文档.

首先,安装摄像头模块。然后,按照本节中的指南开始使用您的摄像头模块。

本指南不涉及遗留相机栈,该堆栈适用于Bullseye及更早版本的 Raspberry Pi OS 发行版。legacy camera stack 使用诸如以下应用程序:raspivid, raspistill and the original Picamera (先拔下连接器的一端 Picamera2) Python library, has been deprecated for many years, and is unsupported. If you are using the legacy camera stack, it will only have support for the Camera Module 1, Camera Module 2 and the High Quality Camera, and will never support any newer camera modules. The remainder of this document is not applicable to the legacy camera stack.

安装 Raspberry Pi 相机

安装 Raspberry Pi 相机的流程在相机和板卡的所有组合中大致相同。连接器存在一些差异;这些差异在以下步骤中注明。

步骤 1. 准备

相机对静电敏感。处理 PCB 前请先接地。如果没有接地腕带,可以触摸水槽水龙头或类似物体来接地。

要完成此过程,你需要以下物品:

  • 一块带有相机连接器的 Raspberry Pi 板卡。

  • 一个 Raspberry Pi 相机。

    某些相机可能附带一小片覆盖镜头的半透明蓝色塑料薄膜。此薄膜仅用于在运输过程中保护镜头。要移除它,请轻轻撕下。

  • 用于连接相机和板卡的合适线缆。

    • 所有 Raspberry Pi 相机都使用标准的 15-pin connector。

    • 直至并包括 Raspberry Pi 4 的 Raspberry Pi 旗舰型号使用标准的 15-pin connector。对于这些板卡,请使用相机随附的 Standard-Standard camera cable。

    • Raspberry Pi 5、所有 Raspberry Pi Zero 型号以及 Compute Module IO boards 使用 mini 22-pin connector。对于这些板卡,请使用Standard-Mini 摄像头排线.

    • 某些 Compute Module Development Kits 附带 Compute Module Camera and Display Adaptor (CMCDA) 板,它可将 IO board 上的 mini 22-pin connector 转换为标准的 15-pin connector。

步骤 2. 将线缆连接到你的 Raspberry Pi

如果你打算将 Active Cooler 与 Raspberry Pi 5 一起使用,请考虑在安装 Active Cooler 之前先将电缆连接到 Raspberry Pi 设备的摄像头连接器上。安装 Active Cooler 后,接触摄像头连接器可能会很不方便。
  1. 关闭 Raspberry Pi 并断开电源。

  2. 找到 Raspberry Pi 板上的摄像头连接器。

    以下描述假设你拿着的 Raspberry Pi 板芯片和连接器朝上,且 Raspberry Pi 标志和板名方向正确。对于顶面没有标志的 Raspberry Pi Zero 板,请让 GPIO 排针位于离你最远的边缘。

    • 在 Raspberry Pi Zero 设备上,摄像头连接器位于右侧短边,与 SD 卡槽相对。

    • 在 Raspberry Pi 4 之前的 Raspberry Pi 旗舰型号上,摄像头连接器位于最靠近你的边缘,在 HDMI 连接器和音频插孔之间。它标有 CAMERA。

    • 在 Raspberry Pi 4 上,摄像头连接器位于最靠近你的边缘,在 micro HDMI 连接器和音频插孔之间。它标有 CAMERA。

    • 在 Raspberry Pi 5 上,两个摄像头和显示器连接器位于最靠近你的边缘,在 micro HDMI 连接器和 Ethernet 端口之间。它们标有 CAM/DISP0 和 CAM/DISP1。你可以将其中任意一个连接器用于摄像头。

    • 在 Raspberry Pi Compute Module 1/3/3+ IO board 上,两个摄像头连接器位于左边缘(最靠近 IO board 上标志的边缘)最靠近你的一端。它们标有 CAM0 和 CAM1。你可以将其中任意一个连接器用于摄像头。

    • 在 Raspberry Pi Compute Module 4 IO board 上,两个摄像头连接器位于最左侧角落附近。它们标有 CAM0 和 CAM1。你可以将其中任意一个连接器用于摄像头。

    • 在 Raspberry Pi Compute Module 5 IO board 上,两个摄像头连接器位于最远边缘的左端。它们标有 CAM/DISP0 和 CAM/DISP1。你可以将其中任意一个连接器用于摄像头。

  3. 打开连接器上的翻盖。

    1. 如果有胶片条将连接器翻盖固定关闭,请将其移除。

    2. 轻轻将翻盖从连接器中拉出,直到感觉它停止。此时翻盖已有一定活动空间。

    3. 将翻盖稍微向远离连接器开口的方向倾斜。

  4. 插入摄像头电缆的一端,使金属触点背向翻盖。

    确保摄像头电缆牢牢插入连接器,并平直就位,以正确对齐所有触点。注意不要以锐角弯折柔性电缆。

  5. 将翻盖朝电缆方向倾回,并向下压入连接器,直到感觉它咔哒一声就位,从而关闭连接器翻盖。

    翻盖将电缆固定到位,并确保连接器引脚与电缆金属触点之间良好接触。

你可以通过反向执行这些步骤将电缆从连接器中取出。

步骤 3. 将电缆连接到摄像头

我们的摄像头已附带 Standard-Standard 电缆。如果你已移除该电缆或想改用其他电缆,请完成以下步骤。

摄像头连接器位于摄像头镜头所在板的相对侧。握住摄像头,使镜头朝下或背向你。

  1. 打开连接器上的翻盖。

    1. 轻轻将翻盖从连接器中拉出,直到感觉它停止。此时翻盖已有一定活动空间。

    2. 将翻盖稍微向远离连接器开口的方向倾斜。

  2. 插入摄像头电缆的一端,使金属触点背向翻盖并朝向摄像头板。

    确保摄像头电缆牢牢插入连接器,并平直就位,以正确对齐所有触点。注意不要以锐角弯折柔性电缆。

  3. 将翻盖朝电缆方向倾回,并向下压入连接器,直到感觉它咔哒一声就位,从而关闭连接器翻盖。

    翻盖将电缆固定到位,并确保连接器引脚与电缆金属触点之间良好接触。

你可以通过反向执行这些步骤将电缆从连接器中取出。

步骤 4. 准备软件

  1. 将你的 Raspberry Pi 设备重新连接到电源并开机。

  2. 按照以下说明确保你的 kernel 和应用程序均为最新版本:使你的操作系统保持最新.

  3. 按照以下设置说明操作:rpicam-apps.

  4. (可选)如果你想使用 picamera2 Python library,请按照以下设置说明操作:picamera2 Python 库.

rpicam-apps

从 Raspberry Pi OS书虫开始,相机捕获应用程序命名为rpicam-*.

Raspberry Pi 提供了一小组示例rpicam-apps. These CLI applications, built on top of libcamera, capture images and video from a camera.

这些应用程序包括:

  • rpicam-hello: A "hello world"-equivalent for cameras, which starts a camera preview stream and displays it on the screen.

  • rpicam-jpeg: Runs a preview window, then captures high-resolution still images.

  • rpicam-still: Emulates many of the features of the original raspistill application.

  • rpicam-vid: Captures video.

  • rpicam-raw: Captures raw (unprocessed Bayer) frames directly from the sensor.

  • rpicam-detect: Not built by default, but users can build it if they have TensorFlow Lite installed on their Raspberry Pi. Captures JPEG images when certain objects are detected.

Raspberry Pi OS 包含五个基本rpicam-apps, so you can record images and videos using a camera even on a fresh Raspberry Pi OS installation.

你可以创建自己的rpicam-based applications with custom functionality to suit your own requirements. The rpicam-apps source code在 BSD-2-Clause licence 下可免费获取。

libcamera

libcamera is an open-source software library aimed at supporting camera systems directly from the Linux operating system on Arm processors. Proprietary code running on the Broadcom GPU is minimised. For more information about libcamera see the libcamera website.

libcamera provides a C++ API that configures the camera, then allows applications to request image frames. These image buffers reside in system memory and can be passed directly to still image encoders (such as JPEG) or to video encoders (such as H.264). libcamera doesn’t encode or display images itself: that that functionality, use rpicam-apps.

你可以在官方 libcamera repository中找到源代码。Raspberry Pi OS 发行版使用一个叉取来控制更新。

在以下内容之下:libcamera core, we provide a custom pipeline handler. libcamera uses this layer to drive the sensor and image signal processor (ISP) on the Raspberry Pi. libcamera contains a collection of image-processing algorithms (IPAs) including auto exposure/gain control (AEC/AGC), auto white balance (AWB), and auto lens-shading correction (ALSC).

Raspberry Pi 对以下内容的实现:libcamera supports the following cameras:

  • 官方相机:

    • OV5647(V1)

    • IMX219(制造时间早于 2026 年 11 月的 V2 设备)

    • IMX355(制造时间晚于 2026 年 10 月的 V2 设备)

    • IMX708(V3)

    • IMX477(HQ)

    • IMX500(AI)

    • IMX296(GS)

  • 第三方传感器:

    • IMX290

    • IMX327

    • IMX378

    • IMX519

    • OV9281

    • VD55G1

    • VD55G4

    • VD56G3

    • VD65G4

    • VD66GY

要扩展对新传感器的支持,贡献到libcamera.

rpicam-hello

rpicam-hello briefly displays a preview window containing the video feed from a connected camera. To use rpicam-hello to display a preview window for five seconds, run the following command in a terminal:

$ rpicam-hello

你可以传入可选的持续时间(以毫秒为单位),使用该timeout选项。值为0 runs the preview indefinitely:

$ rpicam-hello --timeout 0

使用Ctrl+C in the terminal or the close button on the preview window to stop rpicam-hello.

显示图像传感器预览

大多数rpicam-apps display a preview image in a window. If there is no active desktop environment, the preview draws directly to the display using the Linux Direct Rendering Manager (DRM). Otherwise, rpicam-apps attempt to use the desktop environment. Both paths use zero-copy GPU buffer sharing: as a result, X forwarding is 先拔下连接器的一端都受支持。

如果你运行 X window server 并希望使用 X forwarding,请传递qt-preview标志,以在以下窗口中渲染预览窗口:Qt窗口。Qt 预览窗口比替代方案占用更多资源。

使用 Gtk2 的较旧系统在与 OpenCV 链接时,可能会产生Glib-GObject errors and fail to show the Qt preview window. In this case edit the file /etc/xdg/qt5ct/qt5ct.conf as root and replace the line containing style=gtk2 with style=gtk3.

要完全抑制预览窗口,请传入nopreviewflag:

$ rpicam-hello -n

该info-text选项在窗口标题栏上显示图像信息,使用% directives. For example, the following command displays the current red and blue gain values:

$ rpicam-hello --info-text "red gain %rg, blue gain %bg"

有关指令的完整列表,请参阅info-text reference.

rpicam-jpeg

rpicam-jpeg helps you capture images on Raspberry Pi devices.

要捕获全分辨率 JPEG 图像并将其保存到名为test.jpg, run the following command:

$ rpicam-jpeg --output test.jpg

你应该会看到预览窗口五秒钟。然后,rpicam-jpeg captures a full resolution JPEG image and saves it.

使用timeout选项可更改预览窗口的显示时间。width and height选项会更改保存图像的分辨率。例如,以下命令显示预览窗口 2 秒,然后捕获并保存分辨率为 640×480 像素的图像:

$ rpicam-jpeg --output test.jpg --timeout 2000 --width 640 --height 480

rpicam-still

rpicam-still, like rpicam-jpeg, helps you capture images on Raspberry Pi devices. Unlike rpicam-jpeg, rpicam-still supports many options provided in the legacy raspistill application.

要捕获全分辨率 JPEG 图像并将其保存到名为test.jpg, run the following command:

$ rpicam-still --output test.jpg

编码器

rpicam-still can save images in multiple formats, including png, bmp, and both RGB and YUV binary pixel dumps. To read these binary dumps, any application reading the files must understand the pixel arrangement.

使用encoding选项用于指定输出格式。传递给output对输出文件类型没有影响。

要捕获全分辨率 PNG 图像并将其保存到名为test.png, run the following command:

$ rpicam-still --encoding png --output test.png

有关指定图像格式的更多信息,请参阅encoding option reference.

捕获原始图像

原始图像是由图像传感器直接生成的图像,在 Image Signal Processor (ISP) 或 CPU 对其应用任何处理之前。彩色图像传感器通常使用 Bayer 格式。使用raw选项来捕获原始图像。

要捕获图像,请将其保存到名为test.jpg, and also save a raw version of the image to a file named test.dng, run the following command:

$ rpicam-still --raw --output test.jpg

rpicam-still saves raw images in the DNG (Adobe Digital Negative) format. To determine the filename of the raw images, rpicam-still uses the same name as the output file, with the extension changed to .dng. To work with DNG images, use an application like Dcraw或RawTherapee.

DNG 文件包含有关图像捕获的元数据,包括黑电平、白平衡信息以及 ISP 用于生成 JPEG 的色彩矩阵。使用ExifTool查看 DNG 元数据。以下输出显示了 Raspberry Pi 使用 HQ camera 捕获的原始图像中存储的典型元数据:

File Name                       : test.dng
Directory                       : .
File Size                       : 24 MB
File Modification Date/Time     : 2021:08:17 16:36:18+01:00
File Access Date/Time           : 2021:08:17 16:36:18+01:00
File Inode Change Date/Time     : 2021:08:17 16:36:18+01:00
File Permissions                : rw-r--r--
File Type                       : DNG
File Type Extension             : dng
MIME Type                       : image/x-adobe-dng
Exif Byte Order                 : Little-endian (Intel, II)
Make                            : Raspberry Pi
Camera Model Name               : /base/soc/i2c0mux/i2c@1/imx477@1a
Orientation                     : Horizontal (normal)
Software                        : rpicam-still
Subfile Type                    : Full-resolution Image
Image Width                     : 4056
Image Height                    : 3040
Bits Per Sample                 : 16
Compression                     : Uncompressed
Photometric Interpretation      : Color Filter Array
Samples Per Pixel               : 1
Planar Configuration            : Chunky
CFA Repeat Pattern Dim          : 2 2
CFA Pattern 2                   : 2 1 1 0
Black Level Repeat Dim          : 2 2
Black Level                     : 256 256 256 256
White Level                     : 4095
DNG Version                     : 1.1.0.0
DNG Backward Version            : 1.0.0.0
Unique Camera Model             : /base/soc/i2c0mux/i2c@1/imx477@1a
Color Matrix 1                  : 0.8545269369 -0.2382823821 -0.09044229197 -0.1890484985 1.063961506 0.1062747385 -0.01334283455 0.1440163847 0.2593136724
As Shot Neutral                 : 0.4754476844 1 0.413686484
Calibration Illuminant 1        : D65
Strip Offsets                   : 0
Strip Byte Counts               : 0
Exposure Time                   : 1/20
ISO                             : 400
CFA Pattern                     : [Blue,Green][Green,Red]
Image Size                      : 4056x3040
Megapixels                      : 12.3
Shutter Speed                   : 1/20

要计算模拟增益,请将 ISO 数值除以 100。 Auto White Balance (AWB) 算法确定一个校准光源,该光源始终标记为D65.

拍摄长曝光

要拍摄极长曝光图像,请禁用自动曝光/增益控制 (AEC/AGC) 和自动白平衡 (AWB)。否则,这些算法会迫使用户等待若干帧,直到它们收敛。

要禁用这些算法,请为增益和 AWB 提供显式值。由于长曝光已经需要大量时间,因此完全跳过预览阶段通常是合理的,使用immediate选项。

要执行 100 秒曝光拍摄,请运行以下命令:

$ rpicam-still -o long_exposure.jpg --shutter 100000000 --gain 1 --awbgains 1,1 --immediate

要查找官方 Raspberry Pi 相机的最大曝光时间,请参阅相机硬件规格.

创建延时视频

要创建延时视频,请以固定间隔拍摄静态图像(例如每分钟一次),然后使用应用程序将这些图片拼接成视频。

rpicam-still time lapse mode

要使用内置延时模式,请使用rpicam-still, use the timelapse选项。此选项接受一个值,表示你希望 Raspberry Pi 在两次拍摄之间等待的时间,单位为毫秒。

首先,创建一个用于存储延时照片的目录:

$ mkdir timelapse

运行以下命令创建一段 30 秒的延时摄影,每两秒记录一张照片,并将输出保存到image0000.jpg through image0013.jpg:

$ rpicam-still --timeout 30000 --timelapse 2000 -o timelapse/image%04d.jpg
cron

你还可以使用cron. First, create the script, named timelapse.sh containing the following commands. Replace the <username> placeholder with the name of your user account on your Raspberry Pi:

#!/bin/bash
DATE=$(date +"%Y-%m-%d_%H%M")
rpicam-still -o /home/<username>/timelapse/$DATE.jpg

然后,使脚本可执行:

$ chmod +x timelapse.sh

创建timelapse directory into which you’ll save time lapse pictures:

$ mkdir timelapse

打开你的 crontab 进行编辑:

$ crontab -e

在编辑器中打开该文件后,添加以下行以安排每分钟拍摄一张图像,替换<username> placeholder with the username of your primary user account:

* * * * * /home/<username>/timelapse.sh 2>&1

保存并退出,你应该会看到以下消息:

crontab: installing new crontab

要停止为延时摄影录制图像,请运行crontab -e again and remove the above line from your crontab.

将图像拼接在一起

当你有一系列延时照片时,你可能想把它们合并成一个视频。使用ffmpeg to do this on a Raspberry Pi.

首先,安装ffmpeg:

$ sudo apt install ffmpeg

在包含该内容的目录中运行以下命令:timelapse directory to convert your JPEG files into an mp4 video:

$ ffmpeg -r 10 -f image2 -pattern_type glob -i 'timelapse/*.jpg' -s 1280x720 -vcodec libx264 timelapse.mp4

上述命令使用以下参数:

  • -r 10: sets the frame rate (Hz value) to ten frames per second in the output video

  • -f image2: sets ffmpeg to read from a list of image files specified by a pattern

  • -pattern_type glob: use wildcard patterns (globbing) to interpret filename input with -i

  • -i 'timelapse/*.jpg': specifies input files to match JPG files in the timelapse directory

  • -s 1280x720: scales to 720p

  • -vcodec libx264 use the software x264 encoder.

  • timelapse.mp4 The name of the output video file.

有关以下内容的更多信息:ffmpeg options, run ffmpeg --help in a terminal.

rpicam-vid

rpicam-vid helps you capture video on Raspberry Pi devices. rpicam-vid displays a preview window and writes an encoded bitstream to the specified output. This produces an unpackaged video bitstream that is not wrapped in any kind of container (such as an mp4 file) format.

在可用时,rpicam-vid uses hardware H.264 encoding.

例如,以下命令会将一个十秒钟的视频写入名为test.h264:

$ rpicam-vid -t 10s -o test.h264

你可以使用 ffplay 和其他视频播放器播放生成的文件:

$ ffplay test.h264

旧版本的 VLC 能够正确播放 H.264 文件,但近期版本不能——只显示少数帧,或者可能是乱码帧。要么使用其他媒体播放器,要么将文件保存为更广泛支持的容器格式——例如 MP4(见下文)。

在 Raspberry Pi 5 上,你可以通过指定以下内容直接输出为 MP4 容器格式:mp4 file extension for your output file:

$ rpicam-vid  -t 10s -o test.mp4

在 Raspberry Pi 4 或更早设备上,你可以使用以下方式保存 MP4 文件:

$ rpicam-vid -t 10s --codec libav -o test.mp4

编码器

rpicam-vid supports motion JPEG as well as both uncompressed and unformatted YUV420:

$ rpicam-vid -t 10000 --codec mjpeg -o test.mjpeg
$ rpicam-vid -t 10000 --codec yuv420 -o test.data

该codec选项决定输出格式,而不是输出文件的扩展名。

该segment选项会将输出文件分割成段大小的块(以毫秒为单位)。通过指定非常短(1 毫秒)的段,这对将 motion JPEG 流拆分成单独的 JPEG 文件很方便。例如,以下命令将 1 毫秒的段与输出文件名中的计数器结合,为每个段生成新的文件名:

$ rpicam-vid -t 10000 --codec mjpeg --segment 1 -o test%05d.jpeg

捕获高帧率视频

为了尽量减少高帧率(> 60fps)视频的掉帧,请尝试以下配置调整:

  • 设置H.264 目标级别为 4.2,使用--level 4.2.

  • 通过设置以下内容来禁用软件色彩降噪处理:denoise选项设置为cdn_off.

  • 使用以下内容禁用显示窗口:nopreview以释放一些额外的 CPU 周期。

  • 将force_turbo=1 in /boot/firmware/config.txt以确保在视频捕获期间 CPU 时钟不会降频。更多信息,请参见即force_turbo documentation.

  • 使用以下内容调整 ISP 输出分辨率:--width 1280 --height 720 or something even lower to achieve your framerate target.

  • 在 Raspberry Pi 4 上,你可以通过添加以下内容对 GPU 进行超频以提高性能:gpu_freq=550 or higher in /boot/firmware/config.txt. See 超频文档以获取更多详细信息。

以下命令演示了如何实现 1280×720 120fps 视频:

$ rpicam-vid --level 4.2 --framerate 120 --width 1280 --height 720 --save-pts timestamp.pts -o video.264 -t 10000 --denoise cdn_off -n

libav integration with rpicam-vid

rpicam-vid can use the ffmpeg/libav codec backend to encode audio and video streams. You can either save these streams to a file or stream them over the network. libav uses hardware H.264 video encoding when present.

要启用libav backend, pass libav to the codec选项:

$ rpicam-vid --codec libav --libav-format avi --libav-audio --output example.avi

使用 Raspberry Pi 5 的低延迟视频

Raspberry Pi 5 使用软件视频编码器。这些编码器输出的帧通常比旧硬件编码器具有更长的延迟,这有时会是实时流媒体应用的问题。

在这种情况下,添加选项--low-latency to the rpicam-vid command. This will alter certain encoder options to output the encoded frame more quickly.

缺点是编码效率(略微)较差,并且处理器的多个核心可能(略微)无法高效利用。可编码的最大帧率可能会略有降低(尽管仍能轻松达到 1080p30)。

rpicam-raw

rpicam-raw records video as raw Bayer frames directly from the sensor. It does not show a preview window. To record a two second raw clip to a file named test.raw, run the following command:

$ rpicam-raw -t 2000 -o test.raw

rpicam-raw outputs raw frames with no formatting information at all, one directly after another. The application prints the pixel format and image dimensions to the terminal window to help the user interpret the pixel data.

默认情况下,rpicam-raw outputs raw frames in a single, potentially very large, file. Use the segment选项将每个原始帧定向到单独文件,使用%05d 指令使每个帧文件名唯一:

$ rpicam-raw -t 2000 --segment 1 -o test%05d.raw

使用快速存储设备时,rpicam-raw can write 18 MB 12-megapixel HQ camera frames to disk at 10fps. rpicam-raw has no capability to format output frames as DNG files; for that functionality, use rpicam-still。使用framerate选项设置在低于 10 的级别以避免丢帧:

$ rpicam-raw -t 5000 --width 4056 --height 3040 -o test.raw --framerate 8

有关原始格式的更多信息,请参阅mode documentation.

rpicam-detect

Raspberry Pi OS 不包含rpicam-detect. However, you can build rpicam-detect if you have 已安装的 TensorFlow Lite。有关更多信息,请参阅rpicam-apps build instructions。不要忘记传递-Denable_tflite=enabled when you run meson.

rpicam-detect displays a preview window and monitors the contents using a Google MobileNet v1 SSD (Single Shot Detector) neural network trained to identify about 80 classes of objects using the Coco dataset. rpicam-detect recognises people, cars, cats and many other objects.

每当rpicam-detect detects a target object, it captures a full-resolution JPEG. Then it returns to monitoring preview mode.

请查看TensorFlow Lite 对象检测器部分以获取有关模型使用的一般信息。例如,你可以在外出时偷偷监视你的猫:

$ rpicam-detect -t 0 -o cat%04d.jpg --lores-width 400 --lores-height 300 --post-process-file object_detect_tf.json --object cat

配置

大多数用例会自动工作,无需更改摄像头配置。但是,一些常见用例确实需要调整配置,包括:

  • 第三方摄像头(有关任何必要的配置更改,请参阅制造商的说明。)

  • 使用非标准驱动程序或 overlay 与官方 Raspberry Pi 摄像头

Raspberry Pi OS 在以下项中识别以下 overlay/boot/firmware/config.txt.

摄像头模块 在/boot/firmware/config.txt

V1 摄像头(OV5647)

dtoverlay=ov5647

V2 摄像头(IMX219 或 IMX355)

dtoverlay=imx219

HQ 摄像头(IMX477)

dtoverlay=imx477

GS 摄像头(IMX296)

dtoverlay=imx296

Camera Module 3(IMX708)

dtoverlay=imx708

IMX290 和 IMX327

dtoverlay=imx290,clock-frequency=74250000 or dtoverlay=imx290,clock-frequency=37125000 (both modules share the imx290 kernel driver; refer to instructions from the module vendor for the correct frequency)

IMX378

dtoverlay=imx378

OV9281

dtoverlay=ov9281

要使用这些 overlay 之一,必须先禁用自动相机检测。要禁用自动检测,请设置camera_auto_detect=0 in /boot/firmware/config.txt. If config.txt already contains a line assigning an camera_auto_detect value, change the value to 0. Reboot your Raspberry Pi with sudo reboot to load your changes.

如果你的 Raspberry Pi 有两个相机连接器(例如 Raspberry Pi 5 或某个 Compute Module),则可以通过添加 来指定使用相机连接器 0,cam0 to the dtoverlay that you used from the table above. If you do not add this, it will default to checking camera connector 1. Note that for official Raspberry Pi camera modules connected to SBCs (not Compute Modules), auto-detection will correctly identify all the cameras connected to your device.

使用 tuning 文件调整相机行为

Raspberry Pilibcamera implementation includes a tuning 文件用于每个相机。此文件控制算法和硬件以产生最佳图像质量。libcamera can only determine the sensor in use, not the module. As a result, some modules require a tuning file override. Use the tuning-file选项来指定覆盖。你还可以复制并修改现有的 tuning 文件来自定义相机行为。

例如,传感器的无红外滤镜(NoIR)版本使用与标准版本不同的自动白平衡(AWB)设置。在 Raspberry Pi 5 或更高版本上,你可以使用以下命令为 IMX219 传感器指定 NoIR tuning 文件:

$ rpicam-hello --tuning-file /usr/share/libcamera/ipa/rpi/pisp/imx219_noir.json
Raspberry Pi 5 之前的 Raspberry Pi 型号使用不同的 tuning 文件。在这些设备上,请使用存储在/usr/share/libcamera/ipa/rpi/vc4/ instead.

libcamera maintains tuning files for a number of cameras, including third-party models. For instance, you can find the tuning file for the Soho Enterprises SE327M12 in se327m12.json.

使用多个相机

rpicam-apps has basic support for multiple cameras. You can attach multiple cameras to a Raspberry Pi in the following ways:

  • 对于 Raspberry Pi Compute Modules,你可以将两个相机直接连接到 Raspberry Pi Compute Module I/O 板。请参阅Compute Module 文档以获取更多详细信息。使用此方法,你可以同时使用两个相机.

  • 对于 Raspberry Pi 5,你可以使用双 MIPI 连接器将两个相机直接连接到板子。

  • 对于其他带有相机端口的 Raspberry Pi 设备,你可以使用 Video Mux 板连接两个或更多相机,例如这个第三方产品。由于两个相机都连接到单个 Unicam 端口,一次只能使用一个相机.

要列出你的平台上所有可用的相机,请使用list-cameras选项。要选择使用哪个相机,请将相机索引传递给camera选项。

libcamera does not yet provide stereoscopic camera support. When running two cameras simultaneously, they must be run in separate processes, meaning there is no way to synchronise 3A operation between them. As a workaround, you could synchronise the cameras through an external sync signal for the HQ (IMX477) camera or use the software camera synchronisation support that is described below, switching the 3A to manual mode if necessary.

软件相机同步

Raspberry Pilibcamera实现能够仅使用软件来同步不同摄像头的帧。这会使一台摄像头调整其帧时序,以便尽可能紧密地与另一台摄像头的帧重合。无需焊接或硬件连接,并且可适用于所有 Raspberry Pi 摄像头模块,甚至第三方模块,只要其驱动程序正确实现了帧持续时间控制。

工作原理

该方案的工作方式是,将一台摄像头指定为服务器。服务器将按固定间隔(例如每秒一次)向网络广播定时消息。与此同时,其他摄像头,称为客户端,可以监听这些消息,随后略微延长或缩短帧时间,从而将它们与服务器拉入同步。这个过程是持续进行的,不过在进行第一次调整后,后续调整通常很小。

客户端摄像头可以连接到与服务器相同的 Raspberry Pi 设备,也可以连接到同一网络上的不同 Raspberry Pi 设备。客户端上的摄像头型号可以与服务器相同,也可以不同。

客户端和服务器需要以相同的标称帧率运行(例如 30fps)。请注意,不存在从客户端返回服务器的反向通道。客户端完全有责任及时启动并运行以匹配服务器,而服务器完全不知道客户端是否已成功同步,甚至不知道是否存在任何客户端。

在正常操作中,在同一 Raspberry Pi 上运行同一品牌的摄像头时,我们预计摄像头图像的帧起始时间会匹配在“数十微秒”以内。当摄像头型号不同时,这个值可能会大得多,因为摄像头可能无法精确匹配帧率,因此会持续漂移(并在每条定时消息到来时被重新拉回一起)。

当摄像头位于不同设备上时,应使用 NTP 同步系统时钟(Raspberry Pi OS 默认通常如此),或者如果这不够精确,可以使用 PTP 之类的另一种协议。系统时钟之间的任何差异都会直接转化为帧起始时间中的额外误差——即使帧上公布的时间戳不会告诉你这一点。

服务器

如前所述,服务器向网络广播定时消息,默认每秒一次。服务器将运行固定数量的帧,默认 100 帧,之后它会通知设备上的摄像头应用程序已到达“同步点”。此时,应用程序将开始使用这些帧,因此在……的情况下rpicam-vid, they will start being encoded and recorded. Recall that the behaviour and even existence of clients has no bearing on this.

如果需要,同一网络上可以有多个服务器,只要它们向不同的网络地址广播定时消息。当然,客户端必须配置为监听正确的地址。

客户端

客户端监听服务器定时消息,当收到一条消息时,会将摄像头帧持续时间缩短或延长所需量,以便后续帧尽可能在服务器的帧开始的同一时刻开始。

客户端从服务器的消息中学习正确的“同步点”,并且就像服务器一样,会在其应开始使用帧的同一时刻向摄像头应用程序发出信号。因此在……的情况下rpicam-vid, this is once again the moment at which frames will start being recorded.

通常合理的做法是先启动客户端之前再启动服务器,因为客户端只会等待(尚未到达“同步点”),直到看到服务器向网络广播。这显然避免了服务器甚至在所有客户端启动之前就到达其“同步点”的时序问题!

在……中的用法rpicam-vid

我们可以将软件摄像头同步与rpicam-vid to record videos that are synchronised frame-by-frame. We’re going to assume we have two cameras attached, and we’re going to use camera 0 as the server, and camera 1 as the client. rpicam-vid defaults to a fixed 30 frames per second, which will be fine for us.

首先我们应该启动客户端:

$ rpicam-vid -n -t 20s --camera 1 --codec libav -o client.mp4 --sync client

注意--sync client parameter. This will record for 20 seconds but 仅在到达同步点之后。如果需要,它将无限期等待第一条服务器消息。

要启动服务器:

$ rpicam-vid -n -t 20s --camera 0 --codec libav -o server.mp4 --sync server

这也会从到达同步点且录制开始时算起运行 20 秒。使用默认同步设置(30fps 下 100 帧)时,这意味着客户端将有略多于 3 秒的时间来完成同步。

服务器的广播地址和端口、定时消息的频率以及等待客户端同步的帧数,都可以在摄像头调优文件中更改。客户端在这里只关注广播地址,该地址应与服务器的匹配;其他信息将被忽略。更多信息,请参阅Raspberry Pi Camera 调优指南.

在实际操作中,还有几个最后需要注意的要点:

  • fixed framerate 需要低于 camera 能够运行的最大 framerate(在所使用的 camera 模式下)。这是因为 synchronisation algorithm 可能需要缩短camera frames,以便 clients 能够赶上 server,而如果它已经以最快速度运行,这将会失败。

  • 虽然 camera frames 应正确同步,但在较高 framerates 下或取决于系统负载,clients 或 server 上的 frames 有可能被丢弃。在这些情况下,frame timestamps 将帮助应用程序弄清楚发生了什么,不过通常更简单的是尝试避免 frame drops——也许通过降低 framerate、增加分配给 camera queues 的 buffers 数量(见--buffer-count option),或减少系统负载。

有线同步

该高品质相机(High Quality Camera)树莓派5全局快门摄像头(Global Shutter Camera)也可以通过摄像头之间的线缆进行同步。按照各自页面所述连接并配置摄像头后,配置 libcamera 并按如下方式启动摄像头。

libcamera 配置

如果摄像头未能在 1 秒内全部启动,则rpicam applications can time out. To prevent this, edit a configuration file on any Raspberry Pi with sink cameras.

在 Raspberry Pi 5 或 Compute Module 5 上:

$ cp /usr/share/libcamera/pipeline/rpi/pisp/example.yaml timeout.yaml

在其他 Raspberry Pi 型号上:

$ cp /usr/share/libcamera/pipeline/rpi/vc4/rpi_apps.yaml timeout.yaml

现在编辑该副本。在两种情况下,删除# (comment) from the "camera_timeout_value_ms": line, and change the number to 60000 (60 seconds).

启动摄像头

运行以下命令以启动 sink:

$ export LIBCAMERA_RPI_CONFIG_FILE=timeout.yaml
$ rpicam-vid --frames 300 --qt-preview -o sink.h264

等待几秒钟,然后运行以下命令以启动 source:

$ rpicam-vid --frames 300 --qt-preview -o source.h264

Frames 必须同步。使用--frames to ensure the same number of frames are captured, and that the recordings are exactly the same length. Running the sink first ensures that no frames are missed.

安装libcamera and rpicam-apps

Raspberry Pi 提供两个rpicam-apps packages:

  • rpicam-apps contains full applications with support for previews using a desktop environment. This package is pre-installed in Raspberry Pi OS.

  • rpicam-apps-lite omits desktop environment support, and only makes the DRM preview available. This package is pre-installed in Raspberry Pi OS Lite.

依赖项

rpicam-apps depends on library packages named library-name<n>, where <n> is the ABI version. Your package manager should install these automatically.

Dev 软件包

你可以重新构建rpicam-apps without building libcamera and libepoxy from scratch. For more information, see 构建rpicam-apps without rebuilding libcamera.

通过网络流式传输视频,使用rpicam-apps

本节介绍如何通过网络流式传输视频,使用rpicam-vid. Whilst it’s possible to stream very simple formats without using libav, for most applications we recommend using the libav backend.

UDP

要使用 Raspberry Pi 作为服务器通过 UDP 流式传输视频,请使用以下命令,并替换其中的<ip-addr> placeholder with the IP address of the client or multicast address and replacing the <port> placeholder with the port you would like to use for streaming:

$ rpicam-vid -t 0 -n --inline -o udp://<ip-addr>:<port>

要使用 Raspberry Pi 作为客户端查看通过 UDP 流式传输的视频,请使用以下命令,并替换其中的<port> placeholder with the port you would like to stream from:

$ ffplay udp://@:<port> -fflags nobuffer -flags low_delay -framedrop

如前所述,vlc no longer handles unencapsulated H.264 streams.

事实上,对未封装 H.264 的支持通常可能相当差,因此通常最好改为发送 MPEG-2 Transport Stream。利用libav, this can be accomplished with:

$ rpicam-vid -t 0 -n --codec libav --libav-format mpegts -o udp://<ip-addr>:<port>

在这种情况下,我们也可以使用以下工具成功播放该流:vlc:

$ vlc udp://@:<port>

TCP

你也可以通过 TCP 流式传输视频。和之前一样,我们可以通过网络发送未封装的 H.264 流。要使用 Raspberry Pi 作为服务器:

$ rpicam-vid -t 0 -n --inline --listen -o tcp://0.0.0.0:<port>

要使用 Raspberry Pi 作为客户端查看通过 TCP 流式传输的视频,假设服务器以每秒 30 帧运行,请使用以下命令:

$ ffplay tcp://<ip-addr-of-server>:<port> -vf "setpts=N/30" -fflags nobuffer -flags low_delay -framedrop

但与 UDP 示例一样,通常更可取的是发送 MPEG-2 Transport Stream,因为它的支持通常更好。为此,请使用:

$ rpicam-vid -t 0 -n --codec libav --libav-format mpegts -o tcp://0.0.0.0:<port>?listen=1

现在我们可以使用多种媒体播放器回放它,包括vlc:

$ vlc tcp://<ip-addr-of-server>:<port>

RTSP

我们可以将 VLC 用作 RTSP 服务器,但是,我们必须向它发送 MPEG-2 Transport Stream,因为它不再理解未封装的 H.264:

$ rpicam-vid -t 0 -n --codec libav --libav-format mpegts -o - | cvlc stream:///dev/stdin --sout '#rtp{sdp=rtsp://:8554/stream1}'

要使用 Raspberry Pi 作为客户端查看通过 RTSP 流式传输的视频,请使用以下命令:

$ ffplay rtsp://<ip-addr-of-server>:8554/stream1 -fflags nobuffer -flags low_delay -framedrop

或者,在客户端上使用以下命令通过 VLC 进行流式传输:

$ vlc rtsp://<ip-addr-of-server>:8554/stream1

如果你想在服务器上看到预览窗口,只需去掉-n option (see nopreview)。

libav and Audio

我们一直在使用libav as the backend for network streaming. libav allows us to add an audio stream, so long as we’re using a format – like the MPEG-2 Transport Stream – that permits audio data.

我们可以采用之前的某个命令,比如通过 TCP 流式传输 MPEG-2 Transport Stream 的命令,然后只需添加--libav-audio option:

$ rpicam-vid -t 0 --codec libav --libav-format mpegts --libav-audio -o "tcp://<ip-addr>:<port>?listen=1"

你可以使用类似命令通过 UDP 进行流式传输:

$ rpicam-vid -t 0 --codec libav --libav-format mpegts --libav-audio  -o "udp://<ip-addr>:<port>"

GStreamer

GStreamer是一个用于读取、处理和播放多媒体文件的 Linux 框架。我们也可以将其与rpicam-vid for network streaming.

此设置使用rpicam-vid to output an H.264 bitstream to stdout, though as we’ve done previously, we’re going to encapsulate it in an MPEG-2 Transport Stream for better downstream compatibility.

然后,我们使用 GStreamerfdsrc element to receive the bitstream, and extra GStreamer elements to send it over the network. On the server, run the following command to start the stream, replacing the <ip-addr> placeholder with the IP address of the client or multicast address and replacing the <port> placeholder with the port you would like to use for streaming:

$ rpicam-vid -t 0 -n --codec libav --libav-format mpegts -o - | gst-launch-1.0 fdsrc fd=0 ! udpsink host=<ip-addr> port=<port>

你可以使用任何东西(例如 VLC)作为客户端;用于播放的最佳 GStreamer 客户端超出了本文档的范围。但是,以下 pipeline(进行明显替换后)可在 Raspberry Pi 4B 或更早设备上工作:

$ gst-launch-1.0 udpsrc address=<ip-addr> port=<port> ! tsparse ! tsdemux ! h264parse ! queue ! v4l2h264dec ! autovideosink

对于 Raspberry Pi 5 设备,请替换v4l2h264dec by avdec_h264.

要测试此配置,请在同一设备的单独终端中运行服务器和客户端命令,并使用localhost as the address.

libcamerasrc GStreamer element

libcamera provides a libcamerasrc GStreamer element which can be used directly instead of rpicam-vid. To use this element, run the following command on the server, replacing the <ip-addr> placeholder with the IP address of the client or multicast address and replacing the <port> placeholder with the port you would like to use for streaming. On a Raspberry Pi 4B or earlier device, use:

$ gst-launch-1.0 libcamerasrc ! capsfilter caps=video/x-raw,width=640,height=360,format=NV12,interlace-mode=progressive ! v4l2h264enc extra-controls="controls,repeat_sequence_header=1" ! 'video/x-h264,level=(string)4' ! h264parse ! mpegtsmux ! udpsink host=<ip-addr> port=<port>

在 Raspberry Pi 5 设备上,替换v4l2h264enc extra-controls="controls,repeat_sequence_header=1" by x264enc speed-preset=1 threads=1.

在客户端,我们可以使用与上面相同的播放管道,或其他流媒体播放器。

第三方流媒体服务器

有许多可用的第三方流媒体服务器,虽然 Raspberry Pi 并不特别推荐任何一个,但我们提供一些关于使用若干流行服务器的入门指南。

所有这些流媒体服务器都可以摄取由以下内容创建的 Raspberry Pi 摄像头流rpicam-vid, and re-stream them to RTSP clients, or to web browsers using WebRTC, or using many other formats. MediaMTX supports Raspberry Pi cameras as a native option through libcamera, by-passing the need for external executables (like rpicam-vid).

上面的列表并不详尽;但是,我们已确认这些应用程序可与 Raspberry Pi 摄像头系统正确配合工作。

使用 MediaMTX 进行流式传输

MediaMTX接受来自 Raspberry Pi 设备摄像头系统的输入流(例如,由rpicam-vid), and re-streams it to other clients. Additionally, it supports Raspberry Pi cameras as a built-in source.

安装与配置

要安装 MediaMTX:

  1. 从以下位置下载最新版本:发布页面。

    • 如果你使用的是 Raspberry Pi OS 64-bit,请选择linux_arm64 compressed tar file (ending .tar.gz).

    • 如果你使用的是 Raspberry Pi OS 32-bit,请选择armv7 compressed tar file.

  2. 通过运行以下命令解压压缩的 tar 文件tar -xvzf <filename.tar.gz>. The file contains a mediamtx executable and a configuration file called mediamtx.yml.

  3. 备份原始的mediamtx.yml file (recommended). For example, you can run cp mediamtx.yml mediamtx.yml.original. We recommend this because the original file documents many Raspberry Pi camera options that you might want to explore later, so keeping a copy can be useful for reference.

添加摄像头流

要流式传输摄像头,请替换以下内容:mediamtx.yml with the following:

paths:
  cam:
    source: rpiCamera

参数source: rpiCamera tells MediaMTX to start and control the Raspberry Pi camera system for itself.

启动mediamtx executable by typing its name at a command prompt, qualifying the full path if necessary.

如果你希望 MediaMTX 仅在请求流时才获取摄像头,请将以下行添加到更新后的mediamtx.yml:

    sourceOnDemand: yes

查阅原始的mediamtx.yml for additional configuration parameters that let you select the image size, the camera mode, the bitrate, and so on. Find the relevant settings, by searching the file for rpi.

或者,你可以运行rpicam-vid externally to MediaMTX by setting up mediamtx.yml as follows:

paths:
  cam:
    source: udp://127.0.0.1:1234

你可以运行任何外部程序,将 MPEG-TS 流输出到此地址。对于rpicam-vid, it might look like:

$ rpicam-vid -t 0 -n --codec libav --low-latency --libav-format mpegts -o udp://127.0.0.1:1234?pkt_size=1316
这提供了以某种方式更改图像的机会,或许使用rpicam-apps post-processing features, or the Picamera2 Python module. The --low-latency option suppresses B-frames (on a Raspberry Pi 5 or later; earlier Raspberry Pi devices don’t generate any B-frames), which is often advisable because some streaming formats that clients request don’t support them.
使用客户端观看

您可以在媒体播放器或网页浏览器中观看流。以下示例假设流名称为 'cam':

故障排除

视频流中偶尔出现的暂停可能是由 Raspberry Pi 上 UDP 接收缓冲区空间不足引起的。如果缓冲区太小,数据可能会被丢弃,从而导致可见的暂停。要永久增加这些缓冲区,请创建一个名为/etc/sysctl.d/99-network-tuning.conf` containing the following lines:

net.core.rmem_default=1000000
net.core.rmem_max=1000000

重启或运行sudo sysctl -p /etc/sysctl.d/99-network-tuning.conf.

在 Raspberry Pi OS Bookworm 上,您必须改为将这些行添加到/etc/sysctl.conf (and then either reboot or run sudo sysctl -p).

有关 MediaMTX 及其功能的更多信息,请参阅MediaMTX 文档.

使用 MistServer 进行流传输

MistServer是一个流行的免费媒体服务器,您可以将其与 Raspberry Pi 摄像头系统配合使用。与 MediaMTX 不同,它没有内置的摄像头支持;但是,您可以配置 MistServer 从rpicam-vid and serve it to clients in a variety of formats.

安装与配置

您可以按照 MistServer 文档中的说明,在 Raspberry Pi 上安装 MistServer:

  • 对于 64 位操作系统,请按照以下说明操作:Armv8 64位 Linux.

  • 对于 32 位操作系统,请按照以下说明操作:Armv7 Linux.

确保以 root 身份运行这些命令。此过程会设置一个自动运行的系统 MistServer 服务。

要配置 MistServer,请访问您 Raspberry Pi 上的 Management Interface (MI) 网页,网址为http://localhost:4242/; you can also visit the page from another computer if you substitute the IP address of your Raspberry Pi. The first time you use the Management Interface, it asks you to create an admin account. In the steps that follow, you can accept the defaults.

您也可以在另一台计算机上运行 MistServer,而不是在带有摄像头的 Raspberry Pi 上运行。
添加摄像头流

要添加摄像头流,请转到管理界面网页并完成以下步骤:

  1. 在左侧窗格中,选择流.

  2. 在右侧窗格中,选择创建流.

  3. 填写所需信息:

    • 流名称,例如 'cam'。客户端通过它识别此流。

    • 一个源。要将 MistServer 配置为启动rpicam-vid automatically, enter the following command:

      $ ts-exec: rpicam-vid -n -t 0 --width 1920 --height 1080 --codec libav --libav-format mpegts -o -

      此命令中的参数配置以下内容:

      • ts-exec configures the command to output an MPEG-TS stream to stdout. This prefix requires MistServer to be running on the Raspberry Pi with the camera.

      • rpicam-vid is the video command.

      • -n configures no preview.

      • -t configures the command to run indefinitely.

      • --width and --height specify your chosen dimensions.

或者,如果你运行rpicam-vid externally, outputting to a UDP socket, use tsudp in place of ts-exec and follow it with the incoming stream’s IP address.

使用客户端观看

您可以在媒体播放器或网页浏览器中观看流。以下示例假设流名称为 'cam':

  • 要使用采用 RTSP 协议的媒体播放器应用观看此流,请使用地址:rtsp://<ip-address-of-MistServer-server>:8554/cam.

  • 要在网页中观看此流,请使用 MistServer 内置的媒体播放器页面。在浏览器中输入:http://<MistServer服务器的IP地址>:8080/cam.html.

有关 MistServer 用例和选项的更多信息,请参阅MistServer 文档.

使用 go2rtc 进行流传输

go2rtc是一个媒体服务器平台,虽然不像 MediaMTX 那样提供直接集成,但可以像 MistServer 一样进行互操作。

安装与配置

要安装 go2rtc:

  1. 从以下位置下载二进制文件:发布页面:

    • 如果你运行的是 64 位操作系统,请选择go2rtc_linux_arm64 binary.

    • 如果你运行的是 32 位操作系统,请选择go2rtc_linux_arm binary.

    • 如果你的设备是 Raspberry Pi 1 或 Zero,请选择go2rtc_linux_armv6 binary.

  2. 更改文件权限,使下载的二进制文件可执行。

  3. 运行该二进制文件。

你可以使用默认配置运行此应用。当 go2rtc 运行时,管理页面位于http://localhost:1984/.

与 MediaMTX 一样,你可以在不同于带摄像头的 Raspberry Pi 的系统上运行 go2rtc。
添加摄像头流

你可以通过创建一个文件来添加摄像头流go2rtc.yaml in the same folder where you run the executable. When go2rtc starts, it outputs a message to the console indicating where it expects to find its configuration file.

将以下文本添加到该文件,替换为你所需的宽度和高度:

streams:
  cam:
    - exec:rpicam-vid -n -t 0 --width 1280 --height 720 --codec libav --libav-format mpegts --low-latency -o -

此配置会启动rpicam-vid when any client requests the 'cam' stream. The parameter --low-latency suppresses B-frames on Raspberry Pi 5 or later models. In this case, go2rtc must be running on the Raspberry Pi with the camera.

或者,你可以运行rpicam-vid externally and have it output an MPEG-TS stream to the address, for example, udp://127.0.0.1:1234. To configure this, ensure that the go2rtc.yaml file contains the following text:

  cam:
    - ffmpeg:udp://127.0.0.1:1234

如果 go2rtc 在与摄像头不同的计算机上运行,请调整 IP 地址。

使用客户端观看

要使用采用 RTSP 协议的媒体播放器应用查看该流,并假设流名称为 'cam',请使用以下地址:rtsp://<ip-address-of-go2rtc-server>:8554/cam.

要在网页中查看该流,请使用 go2rtc 的内置页面。输入http://<go2rtc服务器的IP地址>:1984/stream.html?src=cam.

有关 go2rtc 使用场景和选项的更多信息,请参见go2rtc README 文档.

rpicam-apps options reference

常用选项

以下选项适用于所有rpicam-apps with similar or identical semantics, unless otherwise noted.

要将以下选项之一传递给应用程序,请在选项名称前加上--. If the option requires a value, pass the value immediately after the option name, separated by a single space. If the value contains a space, surround the value in quotes.

某些选项有简写别名,例如-h instead of --help. Use these shorthand aliases instead of the full option name to save space and time at the expense of readability.

help

别名:-h

打印完整的一组选项,并附上每个选项的简要说明。不接受取值。

version

打印以下项的版本字符串libcamera and rpicam-apps. Does not accept a value.

示例输出:

rpicam-apps build: ca559f46a97a 27-09-2021 (14:10:24)
libcamera build: v0.0.0+3058-c29143f7

list-cameras

列出检测到的连接到你的 Raspberry Pi 的摄像头及其可用的传感器模式。不接受取值。

传感器模式标识符采用以下形式:S<Bayer order><Bit-depth>_<Optional packing> : <Resolution list>

裁剪以原生传感器像素(即使在像素合并模式下)指定为(<x>, <y>)/<Width>×<Height>. (x, y) specifies the location of the crop window of size width × height in the sensor array.

例如,以下输出显示有关一个IMX219 sensor at index 0 and an IMX477 sensor at index 1:

Available cameras
-----------------
0 : imx219 [3280x2464] (/base/soc/i2c0mux/i2c@1/imx219@10)
    Modes: 'SRGGB10_CSI2P' : 640x480 [206.65 fps - (1000, 752)/1280x960 crop]
                             1640x1232 [41.85 fps - (0, 0)/3280x2464 crop]
                             1920x1080 [47.57 fps - (680, 692)/1920x1080 crop]
                             3280x2464 [21.19 fps - (0, 0)/3280x2464 crop]
           'SRGGB8' : 640x480 [206.65 fps - (1000, 752)/1280x960 crop]
                      1640x1232 [41.85 fps - (0, 0)/3280x2464 crop]
                      1920x1080 [47.57 fps - (680, 692)/1920x1080 crop]
                      3280x2464 [21.19 fps - (0, 0)/3280x2464 crop]
1 : imx477 [4056x3040] (/base/soc/i2c0mux/i2c@1/imx477@1a)
    Modes: 'SRGGB10_CSI2P' : 1332x990 [120.05 fps - (696, 528)/2664x1980 crop]
           'SRGGB12_CSI2P' : 2028x1080 [50.03 fps - (0, 440)/4056x2160 crop]
                             2028x1520 [40.01 fps - (0, 0)/4056x3040 crop]
                             4056x3040 [10.00 fps - (0, 0)/4056x3040 crop]

对于上述示例中的 IMX219 传感器:

  • 所有模式都有一个RGGB Bayer ordering

  • 所有模式都以所列分辨率提供 8 位或 10 位 CSI2 打包读出

camera

选择要使用的摄像头。从可用摄像头列表中指定一个索引。.

config

别名:-c

指定包含 CLI 选项和值的文件。考虑一个名为example_configuration.txt that contains the following text, specifying options and values as key-value pairs, one option per line, long (non-alias) option names only:

timeout=99000
verbose=
省略开头的-- that you normally pass on the command line. For flags that lack a value, such as verbose in the above example, you must include a trailing =.

然后可以运行以下命令,指定 99000 毫秒的超时时间和详细输出:

$ rpicam-hello --config example_configuration.txt

timeout

别名:-t

默认值:5000 毫秒(5 秒)

指定应用程序在关闭前运行多长时间。除非使用可选后缀更改单位,否则该值将解释为毫秒数。后缀可以是以下之一:

  • min – minutes

  • s or sec – seconds

  • ms – milliseconds (the default if no suffix used)

  • us – microseconds

  • ns – nanoseconds.

此时间适用于视频录制和预览窗口。捕获静态图像时,应用程序会显示预览窗口,持续时间由timeout parameter before capturing the output image.

要无限期运行应用程序,请指定值为0. Floating point values are also permitted.

示例:rpicam-hello -t 0.5min would run for 30 seconds.

preview

别名:-p

设置桌面或 DRM 预览窗口的位置(x,y 坐标)和大小(w,h 尺寸)。不影响从摄像头请求的图像的分辨率或宽高比。缩放图像大小,并对图像宽高比进行 pillar 或 letterbox 加边,以适应预览窗口。

按以下逗号分隔形式传入预览窗口尺寸:x,y,w,h

示例:rpicam-hello --preview 100,100,500,500

Letterboxed preview image

fullscreen

别名:-f

强制预览窗口使用整个屏幕,无边框或标题栏。缩放图像大小,并对图像宽高比进行 pillar 或 letterbox 加边,以适应整个屏幕。不接受值。

qt-preview

使用 Qt 预览窗口,它比替代方案消耗更多资源,但支持 X window forwarding。与fullscreenflag 不兼容。不接受值。

preview-backend

强制使用特定的预览后端:wayland-egl, egl, drm or qt. If not specified, the application automatically selects a back end, preferring the native Wayland (wayland-egl) preview on Wayland desktop sessions.

示例:rpicam-hello --preview-backend wayland-egl

nopreview

别名:-n

使应用程序先拔下连接器的一端完全不显示预览窗口。不接受值。

info-text

默认值:"#%frame (%fps fps) exp %exp ag %ag dg %dg"

在桌面环境中运行时,将提供的字符串设置为预览窗口的标题。支持以下图像元数据替换:

指令 替换

%frame

帧的序号。

%fps

瞬时帧率。

%exp

用于捕获图像的快门速度,单位为微秒。

%ag

应用于传感器中图像的模拟增益。

%dg

由 ISP 应用于图像的数字增益。

%rg

应用于每个像素红色分量的增益。

%bg

应用于每个像素蓝色分量的增益。

%focus

图像的对焦指标,值越大表示图像越清晰。

%lp

当前镜头位置,以屈光度为单位(1 / 以米为单位的距离)。

%afstate

自动对焦算法状态(idle, scanning, focused or failed).

Image showing focus measure

width and height

每个都接受一个数字,用于定义捕获图像的尺寸(以像素为单位)。

对于rpicam-still, rpicam-jpeg and rpicam-vid, specifies output resolution.

对于rpicam-raw, specifies raw frame resolution. For cameras with a 2×2 binned readout mode, specifying a resolution equal to or smaller than the binned mode captures 2×2 binned raw frames.

对于rpicam-hello, has no effect.

例如:

  • rpicam-vid -o test.h264 --width 1920 --height 1080 captures 1080p video.

  • rpicam-still -r -o test.jpg --width 2028 --height 1520 captures a 2028×1520 resolution JPEG. If used with the HQ camera, uses 2×2 binned mode, so the raw file (test.dng) contains a 2028×1520 raw Bayer image.

viewfinder-width and viewfinder-height

每个都接受一个数字,用于定义预览窗口中显示图像的尺寸(以像素为单位)。不影响预览窗口尺寸,因为图像会被调整大小以适应窗口。不影响捕获的静态图像或视频。

mode

允许您按以下以冒号分隔的格式指定相机模式:<width>:<height>:<bit-depth>:<packing>. The system selects the closest available option for the sensor if there is not an exact match for a provided value. You can use the packed (P) or unpacked (U) packing formats. Impacts the format of stored videos and stills, but not the format of frames passed to the preview window.

Bit-depth 和 packing 是可选的。Bit-depth 默认为 12。Packing 默认为P (packed).

有关您的传感器可用的 bit-depth、分辨率和 packing 选项的信息,请参见list-cameras.

例如:

  • 4056:3040:12:P – 4056×3040 resolution, 12 bits per pixel, packed.

  • 1632:1224:10 – 1632×1224 resolution, 10 bits per pixel.

  • 2592:1944:10:U – 2592×1944 resolution, 10 bits per pixel, unpacked.

  • 3264:2448 – 3264×2448 resolution.

或者,通过由以下内容显示的模式列表中的索引来指定相机模式:list-cameras,从 0 开始按列出顺序计数,如下所示:<index> or <index>:<packing>. Packing defaults to P (packed).

例如:

  • 1 – the second mode in the list.

  • 0:U – the first mode in the list, unpacked.

打包格式详情

打包格式占用的像素数据存储更少。

在 Raspberry Pi 4 及更早设备上,打包格式使用 MIPI CSI-2 标准打包像素。这意味着:

  • 10-bit 相机模式将 4 个像素打包进 5 个字节。前 4 个字节包含每个像素的 8 个最高有效位(MSBs),最后一个字节包含 4 对最低有效位(LSBs)。

  • 12-bit 相机模式将 2 个像素打包进 3 个字节。前 2 个字节包含每个像素的 8 个最高有效位(MSBs),最后一个字节包含两个像素的 4 个最低有效位(LSBs)。

在 Raspberry Pi 5 及更高版本设备上,打包格式使用视觉无损压缩方案将像素值压缩为每像素 8 位(1 字节)。

未打包格式详情

未打包格式提供的像素值更易于手动操作,但代价是占用更多像素数据存储空间。

在所有设备上,未打包格式使用每像素 2 个字节。

在 Raspberry Pi 4 及更早设备上,应用程序在最高有效端应用零填充。在解包格式中,10-bit 相机模式下的像素不能超过值 1023。

在 Raspberry Pi 5 及更高版本设备上,应用程序在最低有效端,因此图像使用传感器所提供像素深度的完整 16-bit 动态范围。

viewfinder-mode

与以下项相同mode option, but it applies to the data passed to the preview window. For more information, see the mode documentation.

lores-width and lores-height

从相机提供第二个分辨率较低的图像流,缩放至指定尺寸。

每个选项接受一个数字,用于定义低分辨率流的尺寸(以像素为单位)。

可用于预览和视频模式。不适用于静态拍摄。如果指定的纵横比与正常分辨率流不同,则生成非方形像素。

对于rpicam-vid, disables extra colour-denoise processing.

hflip

水平翻转图像。不接受值。

vflip

垂直翻转图像。不接受值。

rotation

旋转从传感器提取的图像。仅接受值 0 或 180。

roi

裁剪从传感器完整视场提取的图像。接受四个十进制值,范围为 0 到 1,格式如下:<x>,<y>,<w>,h>. Each of these values represents a percentage of the available width and heights as a decimal between 0 and 1.

这些值定义以下比例:

  • <x>: X coordinates to skip before extracting an image

  • <y>: Y coordinates to skip before extracting an image

  • <w>: image width to extract

  • <h>: image height to extract

默认为0,0,1,1 (starts at the first X coordinate and the first Y coordinate, uses 100% of the image width, uses 100% of the image height).

例如:

  • rpicam-hello --roi 0.25,0.25,0.5,0.5 selects exactly a half of the total number of pixels cropped from the centre of the image (skips the first 25% of X coordinates, skips the first 25% of Y coordinates, uses 50% of the total image width, uses 50% of the total image height).

  • rpicam-hello --roi 0,0,0.25,0.25 selects exactly a quarter of the total number of pixels cropped from the top left of the image (skips the first 0% of X coordinates, skips the first 0% of Y coordinates, uses 25% of the image width, uses 25% of the image height).

hdr

默认值:off

以 HDR 模式运行相机。如果未传值,则假定auto. Accepts one of the following values:

  • off – Disables HDR.

  • auto – Enables HDR on supported devices. Uses the sensor’s built-in HDR mode if available. If the sensor lacks a built-in HDR mode, uses on-board HDR mode, if available.

  • single-exp – Uses on-board HDR mode, if available, even if the sensor has a built-in HDR mode. If on-board HDR mode is not available, disables HDR.

Raspberry Pi 5 及后续设备具有板载 HDR 模式。

要检查传感器中的内置 HDR 模式,请在其他选项之外额外传递此选项list-cameras.

相机控制选项

以下选项控制影响相机图像质量的图像处理和算法。

sharpness

设置图像锐度。接受沿以下范围的一个数值:

  • 0.0 applies no sharpening

  • 大于...的值0.0, but less than 1.0 apply less than the default amount of sharpening

  • 1.0 applies the default amount of sharpening

  • 大于...的值1.0 apply extra sharpening

contrast

指定图像对比度。接受沿以下范围的数值:

  • 0.0 applies minimum contrast

  • 大于...的值0.0, but less than 1.0 apply less than the default amount of contrast

  • 1.0 applies the default amount of contrast

  • 大于...的值1.0 apply extra contrast

brightness

指定图像亮度,作为偏移量添加到输出图像中的所有像素。接受沿以下范围的数值:

  • -1.0 applies minimum brightness (black)

  • 0.0 applies standard brightness

  • 1.0 applies maximum brightness (white)

对于许多用例,优先使用ev.

saturation

指定图像色彩饱和度。接受沿以下范围的数值:

  • 0.0 applies minimum saturation (gray scale)

  • 大于...的值0.0, but less than 1.0 apply less than the default amount of saturation

  • 1.0 applies the default amount of saturation

  • 大于...的值1.0 apply extra saturation

ev

指定曝光值(EV)以档为单位的图像补偿。接受一个数值,该数值控制传递给自动曝光/增益控制(AEC/AGC)处理算法的目标值,范围如下:

  • -10.0 applies minimum target values

  • 0.0 applies standard target values

  • 10.0 applies maximum target values

shutter

指定曝光时间,使用快门,单位为微秒。使用此选项时,增益仍可能变化。如果相机以非常快的帧率运行,以至于不允许指定的曝光时间(例如,帧率为 1fps、曝光时间为 10000 微秒),传感器将使用该帧率允许的最大曝光时间。

有关官方相机的最小和最大快门时间列表,请参阅摄像头硬件文档。高于最大值的值会导致未定义行为。

gain

别名:--analoggain

设置模拟增益和数字增益的组合。当传感器驱动程序能够提供请求的增益时,仅使用模拟增益。当模拟增益达到最大值时,ISP 会应用数字增益。接受一个数值。

有关官方相机的模拟增益限制列表,请参阅摄像头硬件文档.

有时,即使未超过模拟增益限制,数字增益也可能超过 1.0。这种情况可能发生在以下情形:

  • 任一颜色增益降到 1.0 以下,这会使数字增益稳定到 1.0/min(red_gain,blue_gain)。这会使应用于任何颜色通道的总数字增益保持在 1.0 以上,以避免变色伪影。

  • 自动曝光/增益控制(AEC/AGC)变化期间的轻微波动。

metering

默认值:centre

设置自动曝光/增益控制(AEC/AGC)算法的测光模式。接受以下值:

  • centre – centre weighted metering

  • spot – spot metering

  • average – average or whole frame metering

  • custom – custom metering mode defined in the camera tuning file

有关定义自定义测光模式以及调整现有测光模式中区域权重的更多信息,请参阅Raspberry Pi 相机和 libcamera 的调优指南.

exposure

设置曝光配置文件。更改曝光配置文件不应影响图像曝光。相反,不同模式会调整增益设置以达到相同的最终结果。接受以下值:

  • sport: short exposure, larger gains

  • normal: normal exposure, normal gains

  • long: long exposure, smaller gains

你可以使用调优文件编辑曝光配置文件。有关更多信息,请参阅Raspberry Pi 相机和 libcamera 的调优指南.

awb

设置自动白平衡(AWB)模式。接受以下值:

模式名称 色温范围

auto

2500K 到 8000K

incandescent

2500K 到 3000K

tungsten

3000K 到 3500K

fluorescent

4000K 到 4700K

indoor

3000K 到 5000K

daylight

5500K 到 6500K

cloudy

7000K 到 8500K

custom

在 tuning file 中定义的自定义范围。

这些值仅为近似值:值可能会根据 camera tuning 而变化。

没有模式会完全禁用 AWB。相反,你可以使用以下方式固定色彩增益awbgains.

有关 AWB 模式的更多信息,包括如何定义自定义模式,请参阅Raspberry Pi 相机和 libcamera 的调优指南.

awbgains

设置固定的红色和蓝色增益值,以替代 Auto White Balance (AWB) 算法。设置非零值以禁用 AWB。接受以下格式的逗号分隔数字输入:<red_gain>,<blue_gain>

denoise

默认值:auto

设置降噪模式。接受以下值:

  • auto: Enables standard spatial denoise. Uses extra-fast colour denoise for video, and high-quality colour denoise for images. Enables no extra colour denoise in the preview window.

  • off: Disables spatial and colour denoise.

  • cdn_off: Disables colour denoise.

  • cdn_fast: Uses fast colour denoise.

  • cdn_hq: Uses high-quality colour denoise. Not appropriate for video/viewfinder due to reduced throughput.

即使是快速色彩降噪也可能降低帧率。高质量色彩降噪明显会降低帧率。

tuning-file

指定 camera tuning file。tuning file 允许你控制图像处理的许多方面,包括 Automatic Exposure/Gain Control (AEC/AGC)、Auto White Balance (AWB)、色彩阴影校正、色彩处理、降噪等。接受 tuning file 路径作为输入。

有关 tuning files 的更多信息,请参阅调优文件.

autofocus-mode

默认值:default

指定自动对焦模式。接受以下值:

  • default: puts the camera into continuous autofocus mode unless lens-position或autofocus-on-capture将模式覆盖为手动

  • manual: does not move the lens at all unless manually configured with lens-position

  • auto: only moves the lens for an autofocus sweep when the camera starts or just before capture if autofocus-on-capture也会使用

  • continuous: adjusts the lens position automatically as the scene changes

此选项仅受某些摄像头模块支持。

autofocus-range

默认值:normal

指定自动对焦范围。接受以下值:

  • normal: focuses from reasonably close to infinity

  • macro: focuses only on close objects, including the closest focal distances supported by the camera

  • full: focus on the entire range, from the very closest objects to infinity

此选项仅受某些摄像头模块支持。

autofocus-speed

默认值:normal

指定自动对焦速度。接受以下值:

  • normal: changes the lens position at normal speed

  • fast: changes the lens position quickly

此选项仅受某些摄像头模块支持。

autofocus-window

指定传感器整个视场内的自动对焦窗口。接受四个十进制值,范围为 0 到 1,格式如下:<x>,<y>,<w>,h>. Each of these values represents a percentage of the available width and heights as a decimal between 0 and 1.

这些值定义以下比例:

  • <x>: X coordinates to skip before applying autofocus

  • <y>: Y coordinates to skip before applying autofocus

  • <w>: autofocus area width

  • <h>: autofocus area height

默认值在两个维度上都使用输出图像的中间三分之一(占总图像面积的 1/9)。

例如:

  • rpicam-hello --autofocus-window 0.25,0.25,0.5,0.5 selects exactly half of the total number of pixels cropped from the centre of the image (skips the first 25% of X coordinates, skips the first 25% of Y coordinates, uses 50% of the total image width, uses 50% of the total image height).

  • rpicam-hello --autofocus-window 0,0,0.25,0.25 selects exactly a quarter of the total number of pixels cropped from the top left of the image (skips the first 0% of X coordinates, skips the first 0% of Y coordinates, uses 25% of the image width, uses 25% of the image height).

此选项仅受某些摄像头模块支持。

lens-position

默认值:default

将镜头移动到固定焦距,通常以屈光度为单位(单位为 1 /以米为单位的距离)。接受以下值范围:

  • 0.0: moves the lens to the "infinity" position

  • 任何其他number: moves the lens to the 1 / number position. For example, the value 2.0 would focus at approximately 0.5m

  • default: move the lens to a default position which corresponds to the hyperfocal position of the lens

镜头校准并不完美,因此同一型号的不同摄像头模组可能会有所差异。

verbose

别名:-v

默认值:1

设置详细程度级别。接受以下值:

  • 0: no output

  • 1: normal output

  • 2: verbose output

输出文件选项

output

别名:-o

设置用于记录图像或视频的文件名。除纯文本文件名外,还接受以下特殊值:

  • -: write to stdout.

  • udp:// (prefix): a network address for UDP streaming.

  • tcp:// (prefix): a network address for TCP streaming.

  • 包含%d directive in the file name to replace the directive with a count that increments for each opened file. This directive supports standard C format directive modifiers.

例如:

  • rpicam-vid -t 100000 --segment 10000 -o chunk%04d.h264 records a 100 second file in 10 second segments, where each file includes an incrementing four-digit counter padded with leading zeros: for example, chunk0001.h264, chunk0002.h264, etc.

  • rpicam-vid -t 0 --inline -o udp://192.168.1.13:5000 streams H.264 video to network address 192.168.1.13 using UDP on port 5000.

wrap

设置由该 使用的计数器的最大值output %d directive. The counter resets to zero after reaching this value. Accepts a numeric value.

flush

在一帧完成写入后立即将输出文件刷新到磁盘,而不是等待系统处理。不接受任何值。

post-process-file

指定一个 JSON 文件,用于配置成像管线所应用的后处理。这适用于摄像头图像之前它们到达应用程序时。这与旧版 类似raspicam "image effects". Accepts a file name path as input.

后处理是一个很大的主题,并且允许使用 OpenCV 和 TensorFlowLite 等第三方软件来分析和处理图像。更多信息,请参阅后处理.

buffer-count

为静态图像捕获或视频录制分配的缓冲区数量。默认值零让每个应用程序为其自身用例选择合理的数量(静态图像捕获为 1,视频录制为 6)。增加该数量有时有助于减少丢帧数量,尤其是在更高帧率下。

viewfinder-buffer-count

正如buffer-count option, but applies when running in preview mode (that is rpicam-hello or the preview, not capture, phase of rpicam-still).

metadata

将捕获的图像元数据保存到文件或- for stdout. The fields in the metadata output will depend on the camera model in use.

另请参阅metadata-format.

metadata-format

保存元数据所用的格式。接受以下值:

  • txt for text format

  • json for JSON format

在文本格式中,每一行将采用以下形式

key=value

在 JSON 格式中,输出是一个 JSON 对象。

此选项不起作用,除非--metadata is also specified.

图像选项

本节中指定的命令行选项仅适用于静态图像输出。

要将以下选项之一传递给应用程序,请在选项名称前加上--. If the option requires a value, pass the value immediately after the option name, separated by a single space. If the value contains a space, surround the value in quotes.

某些选项有简写别名,例如-h instead of --help. Use these shorthand aliases instead of the full option name to save space and time at the expense of readability.

quality

别名:-q

默认值:93

设置 JPEG 质量。接受一个介于……之间的值1 and 100.

exif

在 JPEG 输出文件中保存额外的 EXIF 标签。仅适用于 JPEG 输出。由于以下方面的限制:libexif library, many tags are currently (incorrectly) formatted as ASCII and print a warning in the terminal.

此选项是添加与相机设置相关的某些 EXIF 标签所必需的。录制后,可以使用以下项将不相关的标签添加到输出 JPEG:ExifTool.

示例:rpicam-still -o test.jpg --exif IDO0.Artist=Someone

timelapse

按指定间隔记录图像。接受以毫秒为单位的间隔。将此设置与timeout结合使用,以随时间拍摄重复图像。

你可以使用字符串格式化为每个输出文件指定单独的文件名,例如,--output test%d.jpg.

示例:rpicam-still -t 100000 -o test%d.jpg --timelapse 10000 captures an image every 10 seconds for 100 seconds.

framestart

将输出文件名中访问的帧计数器的起始值配置为%d. Accepts an integer starting value.

datetime

在输出文件名中使用当前日期和时间,格式为MMDDhhmmss.jpg:

  • MM = 2-digit month number

  • DD = 2-digit day number

  • hh = 2-digit 24-hour hour number

  • mm = 2-digit minute number

  • ss = 2-digit second number

不接受任何值。

timestamp

使用当前系统的Unix 时间作为输出文件名。不接受任何值。

restart

默认值:0

配置 JPEG 输出的重启标记间隔。JPEG 重启标记有助于限制损坏对 JPEG 图像的影响,并且还能启用多线程 JPEG 编码和解码。接受整数值。

immediate

应用程序运行时立即捕获图像。

keypress

别名:-k

当timeout到期或按下输入键时捕获图像,以先发生者为准。按x key, then 输入退出而不捕获。不接受任何值。

signal

当timeout到期或当SIGUSR1 is received. Use SIGUSR2 to exit without capturing. Does not accept a value.

thumb

默认值:320:240:70

使用以下格式配置缩略图的尺寸和质量:<w:h:q> (or none, which omits the thumbnail).

encoding

别名:-e

默认值:jpg

设置用于图像输出的编码器。接受以下值:

  • jpg – JPEG

  • png – PNG

  • bmp – BMP

  • rgb – binary dump of uncompressed RGB pixels

  • yuv420 – binary dump of uncompressed YUV420 pixels

此选项始终决定编码,并覆盖传递给以下项的扩展名:output.

当使用datetime和timestamp选项时,此选项决定输出文件扩展名。

raw

别名:-r

除输出图像外,还保存 DNG 格式的原始 Bayer 文件。将输出文件名的扩展名替换为.dng. You can process these standard DNG files with tools like dcraw或RawTherapee不接受值。

raw 文件中的图像数据与传感器输出的内容完全一致,未经过 ISP 或其他任何处理。文件中保存的 EXIF 数据除其他内容外还包括:

  • 曝光时间

  • 模拟增益(ISO 标签是所用模拟增益的 100 倍)

  • 白平衡增益(它们是“as shot neutral”值的倒数)

  • ISP 使用的颜色矩阵

latest

创建指向最近保存文件的符号链接。接受符号链接名称作为输入。

autofocus-on-capture

如果设置,则运行一次自动对焦循环就在捕获图像之前。与以下autofocus_mode值交互:

  • default or manual: only runs the capture-time autofocus cycle.

  • auto: runs an additional autofocus cycle when the preview window loads.

  • continuous: ignores this option, instead continually focusing throughout the preview.

不需要值,但你可以传递1 to enable and 0 to disable. Not passing a value is equivalent to passing 1.

仅受某些相机模块支持(例如树莓派摄像头模块3)。

视频选项

本节指定的命令行选项仅适用于视频输出。

要将以下选项之一传递给应用程序,请在选项名称前加上--. If the option requires a value, pass the value immediately after the option name, separated by a single space. If the value contains a space, surround the value in quotes.

某些选项有简写别名,例如-h instead of --help. Use these shorthand aliases instead of the full option name to save space and time at the expense of readability.

quality

别名:-q

默认值:50

接受 1 到 100 之间的 MJPEG 质量级别。仅适用于以 MJPEG 格式编码的视频。

bitrate

别名:-b

控制 H.264 编码器使用的目标比特率,单位为比特每秒。仅适用于以 H.264 格式编码的视频。影响输出视频的大小。

示例:rpicam-vid -b 10000000 --width 1920 --height 1080 -o test.h264

intra

别名:-g

默认值:60

设置 H.264 比特流中 Iframes(帧内帧)的频率。接受帧数。仅适用于以 H.264 格式编码的视频。

profile

设置 H.264 profile。接受以下值:

  • baseline

  • main

  • high

仅适用于以 H.264 格式编码的视频。

level

设置 H.264 level。接受以下值:

  • 4

  • 4.1

  • 4.2

仅适用于以 H.264 格式编码的视频。

codec

设置用于视频输出的编码器。接受以下值:

  • h264 – use H.264 encoder (the default)

  • mjpeg – use MJPEG encoder

  • yuv420 – output uncompressed YUV420 frames.

  • libav – use the libav backend to encode audio and video (for more information, see libav)

save-pts

Raspberry Pi 5 不支持save-pts option. Use libav to automatically generate timestamps for container formats instead.

启用帧时间戳输出,这允许你使用类似以下工具将比特流转换为容器格式mkvmerge. Accepts a plaintext file name for the timestamp output file.

示例:rpicam-vid -o test.h264 --save-pts timestamps.txt

然后,你可以使用以下命令从比特流和时间戳文件生成 MKV 容器文件:

$ mkvmerge -o test.mkv --timecodes 0:timestamps.txt test.h264

keypress

别名:-k

允许 CLI 使用输入键启用和禁用视频输出。除非另行指定,否则始终以录制状态启动。initial。输入x key and press 输入退出。不接受值。

signal

别名:-s

允许 CLI 使用SIGUSR1. Use SIGUSR2 to exit. Always starts in the recording state unless specified otherwise with initial不接受值。

initial

默认值:record

指定启动应用程序时启用还是禁用视频输出。接受以下值:

  • record: Starts with video output enabled.

  • pause: Starts with video output disabled.

将此选项与以下任一选项一起使用:keypress或signal以在两种状态之间切换。

split

使用以下选项切换录制时,keypress或signal,将来自不同录制会话的视频输出写入不同文件。不接受值。除非与output结合以为每个文件指定唯一名称,否则每次写入文件时都会覆盖。

segment

将视频输出切分为多个文件,每个文件时长等于传入的持续时间。接受以毫秒为单位的持续时间。如果传入非常小的持续时间(例如,1), records each frame to a separate output file to simulate burst capture.

你可以使用 string formatting 为每个文件指定单独的文件名,例如,--output test%04d.h264.

circular

默认值:4

将视频录制写入内存中的环形缓冲区。应用程序退出时,将环形缓冲区记录到磁盘。接受可选的以兆字节为单位的大小。

inline

在每个 Iframe(intra frame)中写入序列头。这可以帮助客户端从视频中的任意点解码视频序列,而不仅仅是从开头。推荐与segment, split, circular,以及流式传输选项。

仅适用于以 H.264 格式编码的视频。不接受值。

listen

在编码视频之前等待传入的客户端连接。用于通过 TCP/IP 进行网络流式传输。不接受值。

frames

精确记录指定数量的帧。任何非零值都会覆盖timeout。接受非零整数。

framerate

精确记录指定的帧率。接受非零整数。

low-latency

在 Raspberry Pi 5 上,--low-latency option reduces the encoding latency, which might be beneficial for real-time streaming applications, in return for (slightly) less good coding efficiency (for example, B frames and arithmetic coding will no longer be used).

sync

以软件同步模式运行摄像头,其中多个摄像头将帧同步到同一时间点。以下内容说明sync mode can be set to either client or server. For more information, see 软件同步的工作原理.

libav options

本节中指定的命令行选项仅适用于libav video backend.

要启用libav backend, pass the codec选项的值libav.

要将以下选项之一传递给应用程序,请在选项名称前加上--. If the option requires a value, pass the value immediately after the option name, separated by a single space. If the value contains a space, surround the value in quotes.

某些选项有简写别名,例如-h instead of --help. Use these shorthand aliases instead of the full option name to save space and time at the expense of readability.

libav-format

设置libav output format. Accepts the following values:

  • mkv encoding

  • mp4 encoding

  • avi encoding

  • h264 streaming

  • mpegts streaming

如果不提供此选项,则传递给output选项的文件扩展名决定文件格式。

libav-audio

启用音频录制。启用后,还必须指定一个audio-codec不接受值。

audio-codec

默认值:aac

选择用于输出的音频编解码器。要查看可用编解码器列表,请运行ffmpeg -codecs.

audio-bitrate

设置音频编码的比特率,单位为比特每秒。接受数字输入。

示例:rpicam-vid --codec libav -o test.mp4 --audio_codec mp2 --audio-bitrate 16384 (Records audio at 16 kilobits/sec with the mp2 codec)

audio-samplerate

默认值:0

设置音频采样率,单位为 Hz。接受数字输入。0 uses the input sample rate.

audio-device

选择用于音频录制的 ALSA 输入设备。要查看可用设备列表,请运行以下命令:

$ pactl list | grep -A2 'Source #' | grep 'Name: '

您应该会看到类似如下的输出:

Name: alsa_output.platform-bcm2835_audio.analog-stereo.monitor
Name: alsa_output.platform-fef00700.hdmi.hdmi-stereo.monitor
Name: alsa_output.usb-GN_Netcom_A_S_Jabra_EVOLVE_LINK_000736B1214E0A-00.analog-stereo.monitor
Name: alsa_input.usb-GN_Netcom_A_S_Jabra_EVOLVE_LINK_000736B1214E0A-00.mono-fallback

av-sync

将音频样本时间戳偏移一个以微秒为单位的值。接受正数和负数数值。

检测选项

本节中指定的命令行选项仅适用于使用rpicam-detect.

要将以下选项之一传递给rpicam-detect, prefix the option name with --. If the option requires a value, pass the value immediately after the option name, separated by a single space. If the value contains a space, surround the value in quotes.

某些选项有简写别名,例如-h instead of --help. Use these shorthand aliases instead of the full option name to save space and time at the expense of readability.

object

检测具有给定名称的对象,名称来自模型的标签文件。接受纯文本文件名作为输入。

gap

在两次捕获之间至少等待这么多帧。接受数值。

使用rpicam-apps

rpicam-apps share a common post-processing framework. This allows them to pass the images received from the camera system through a number of custom image-processing and image-analysis routines. Each such routine is known as a 阶段进行后处理。要运行后处理阶段,请提供一个 JSON 文件,指示应用程序要应用哪些阶段和选项。你可以在以下位置找到使用内置后处理阶段的示例 JSON 文件:assets folder of the rpicam-apps repository.

例如,……反相阶段将亮像素变暗,将暗像素变亮。因为 negate 阶段是基础阶段,不需要配置,negate.json just names the stage:

{
    "negate": {}
}

要将 negate 阶段应用于图像,请传递negate.json to the post-process-file option:

$ rpicam-hello --post-process-file negate.json

要运行多个后处理阶段,请创建一个 JSON 文件,其中包含多个阶段作为顶层键。例如,以下配置先运行 Sobel 阶段,然后运行 negate 阶段:

{
    "sobel_cv":
    {
        "ksize": 5
    },
    "negate": {}
}

该Sobel 阶段使用 OpenCV,因此cv suffix. It has a user-configurable parameter, ksize, that specifies the kernel size of the filter to be used. In this case, the Sobel filter produces bright edges on a black background, and the negate stage turns this into dark edges on a white background.

A negated Sobel filter
一个取反的 Sobel 滤波器。

某些阶段,例如negate, alter the image in some way. Other stages analyse the image to generate metadata. Post-processing stages can pass this metadata to other stages and even the application.

为了提高性能,图像分析通常使用降低后的分辨率。rpicam-apps provide a dedicated low-resolution feed directly from the ISP.

[8] MiRo-Erpicam-apps supplied with Raspberry Pi OS do not include OpenCV and TensorFlow Lite. As a result, certain post-processing stages that rely on them are disabled. To use these stages, 重新编译rpicam-apps。在运行 32-bit kernel 的 Raspberry Pi 3 或 4 上,使用以下内容编译-DENABLE_COMPILE_FLAGS_FOR_TARGET=armv8-neon flag to speed up certain stages.

内置阶段

negate stage

此阶段将亮像素变暗,将暗像素变亮。

该negate stage has no user-configurable parameters.

默认negate.json file:

{
    "negate" : {}
}

运行以下命令以将此阶段文件与rpicam-hello:

$ rpicam-hello --post-process-file negate.json

示例输出:

A negated image
反相图像。

hdr stage

此阶段使用 High Dynamic Range (HDR) 和 Dynamic Range Compression (DRC) 强调图像中的细节。DRC 使用单张图像,而 HDR 会组合多张图像以获得类似结果。

参数分为三组:LP filter、global tonemapping 和 local contrast。

此阶段对完全处理后的输入图像应用 smoothing filter,以生成 low pass (LP) image。然后,它根据原始图像与 LP image 的 diff 生成 high pass (HP) image。接着,它对 LP image 应用 global tonemap,并将其加回 HP image。此过程有助于保留 local contrast。

你可以使用以下参数配置此阶段:

num_frames

要累积的帧数;对于 DRC,使用 1;对于 HDR,尝试 8

lp_filter_strength

low pass IIR filter 的系数。

lp_filter_threshold

一个 piecewise linear function,它将 pixel level 与 meaningful detail 的 threshold 关联起来

global_tonemap_points

输入图像直方图中的点,映射到输出范围中我们希望将它们移动到的目标。使用以下子配置:

  • 一个 inter-quantile mean(q and width)

  • 一个作为 full output range 比例的目标(target)

  • maximum(max_up) and minimum (max_down) gains to move the measured inter-quantile mean, to prevents the image from changing image too drastically

global_tonemap_strength

global tonemap 的应用强度

local_pos_strength

一个 piecewise linear function,它定义当 positive (bright) detail 加回 tonemapped LP image 时应用于 local contrast 的 gain

local_neg_strength

一个 piecewise linear function,它定义当 negative (dark) detail 加回 tonemapped LP image 时应用于 local contrast 的 gain

local_tonemap_strength

应用于所有加回的 local contrast 的 overall gain

local_colour_scale

一个允许 output colours 受到更强或更弱影响的因子

要控制处理强度,更改global_tonemap_strength and local_tonemap_strength parameters.

在 Raspberry Pi 4 上处理一张 12 MP 图像需要两到三秒。累积多帧时,此阶段仅将处理后的图像发送到应用程序。

默认drc.json file for DRC:

{
    "hdr" : {
		"num_frames" : 1,
		"lp_filter_strength" : 0.2,
		"lp_filter_threshold" : [ 0, 10.0 , 2048, 205.0, 4095, 205.0 ],
		"global_tonemap_points" :
			[
			    { "q": 0.1, "width": 0.05, "target": 0.15, "max_up": 1.5, "max_down": 0.7 },
			    { "q": 0.5, "width": 0.05, "target": 0.5, "max_up": 1.5, "max_down": 0.7 },
			    { "q": 0.8, "width": 0.05, "target": 0.8, "max_up": 1.5, "max_down": 0.7 }
			],
		"global_tonemap_strength" : 1.0,
		"local_pos_strength" : [ 0, 6.0, 1024, 2.0, 4095, 2.0 ],
		"local_neg_strength" : [ 0, 4.0, 1024, 1.5, 4095, 1.5 ],
		"local_tonemap_strength" : 1.0,
		"local_colour_scale" : 0.9
    }
}

举例:

Image without DRC processing
未进行 DRC 处理的图像

运行以下命令以将此阶段文件与rpicam-still:

$ rpicam-still -o test.jpg --post-process-file drc.json
Image with DRC processing
进行 DRC 处理的图像

默认hdr.json file for HDR:

{
    "hdr" : {
		"num_frames" : 8,
		"lp_filter_strength" : 0.2,
		"lp_filter_threshold" : [ 0, 10.0 , 2048, 205.0, 4095, 205.0 ],
		"global_tonemap_points" :
			[
			    { "q": 0.1, "width": 0.05, "target": 0.15, "max_up": 5.0, "max_down": 0.5 },
			    { "q": 0.5, "width": 0.05, "target": 0.45, "max_up": 5.0, "max_down": 0.5 },
			    { "q": 0.8, "width": 0.05, "target": 0.7, "max_up": 5.0, "max_down": 0.5 }
			],
		"global_tonemap_strength" : 1.0,
		"local_pos_strength" : [ 0, 6.0, 1024, 2.0, 4095, 2.0 ],
		"local_neg_strength" : [ 0, 4.0, 1024, 1.5, 4095, 1.5 ],
		"local_tonemap_strength" : 1.0,
		"local_colour_scale" : 0.8
    }
}

举例:

Image without HDR processing
未进行 HDR 处理的图像

运行以下命令以将此阶段文件与rpicam-still:

$ rpicam-still -o test.jpg --ev -2 --denoise cdn_off --post-process-file hdr.json
Image with DRC processing
进行 HDR 处理的图像

motion_detect stage

该motion_detect stage analyses frames from the low-resolution image stream. You must configure the low-resolution stream to use this stage. The stage detects motion by comparing a region of interest (ROI) in the frame to the corresponding part of a previous frame. If enough pixels change between frames, this stage indicates the motion in metadata under the motion_detect.result key.

此阶段不依赖第三方库。

你可以使用以下参数配置此阶段,将尺寸作为低分辨率图像大小的比例传入,取值在 0 到 1 之间:

roi_x

用于比较的感兴趣区域的 x 偏移量(0 到 1 之间的比例)

roi_y

用于比较的感兴趣区域的 y 偏移量(0 到 1 之间的比例)

roi_width

用于比较的感兴趣区域的宽度(0 到 1 之间的比例)

roi_height

用于比较的感兴趣区域的高度(0 到 1 之间的比例)

difference_m

用于构建“像素不同”阈值的线性系数

difference_c

用于构建“像素不同”阈值的常数系数,依据threshold = difference_m * pixel_value + difference_c

frame_period

运动检测器将仅运行这么多帧

hskip

水平方向按此量下采样的像素

vksip

垂直方向按此量下采样的像素

region_threshold

必须被归类为不同才能计为运动的像素(区域)比例

verbose

将消息打印到控制台,包括运动状态变化时

默认motion_detect.json configuration file:

{
    "motion_detect" : {
		"roi_x" : 0.1,
		"roi_y" : 0.1,
		"roi_width" : 0.8,
		"roi_height" : 0.8,
		"difference_m" : 0.1,
		"difference_c" : 10,
		"region_threshold" : 0.005,
		"frame_period" : 5,
		"hskip" : 2,
		"vskip" : 2,
		"verbose" : 0
    }
}

调整差异和阈值,使算法更敏感或不敏感。为提高性能,使用hskip and vskip parameters.

运行以下命令以将此阶段文件与rpicam-hello:

$ rpicam-hello --lores-width 128 --lores-height 96 --post-process-file motion_detect.json

使用 OpenCV 进行后处理

这些阶段需要安装 OpenCV。你可能需要重新构建rpicam-apps with OpenCV support.

sobel_cv stage

此阶段应用一个Sobel滤波器到图像以强调边缘。

你可以使用以下参数配置此阶段:

ksize

Sobel filter 的 Kernel size

默认sobel_cv.json file:

{
    "sobel_cv" : {
        "ksize": 5
    }
}

举例:

Using a Sobel filter to emphasise edges
使用 Sobel filter 来强调边缘。

face_detect_cv stage

此阶段使用 OpenCV Haar classifier 检测图像中的人脸。它在 key 下返回人脸位置 metadataface_detect.results and optionally draws the locations on the image.

你可以使用以下参数配置此阶段:

cascade_name

可找到 Haar cascade 的文件名

scaling_factor

确定在图像中搜索人脸所用的尺度范围

min_neighbors

计为人脸所需的最小重叠邻居数

min_size

最小人脸尺寸

max_size

最大人脸尺寸

refresh_rate

尝试重新运行 face detector 前等待多少帧

draw_features

是否在返回的图像上绘制人脸位置

该face_detect_cv stage runs only during preview and video capture. It ignores still image capture. It runs on the low resolution stream with a resolution between 320×240 and 640×480 pixels.

默认face_detect_cv.json file:

{
    "face_detect_cv" : {
        "cascade_name" : "/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml",
        "scaling_factor" : 1.1,
        "min_neighbors" : 2,
        "min_size" : 32,
        "max_size" : 256,
        "refresh_rate" : 1,
        "draw_features" : 1
    }
}

举例:

Drawing detected faces onto an image
将检测到的人脸绘制到图像上。

annotate_cv stage

此阶段使用相同的% substitutions as the info-text选项。

解析info-text directives首先,然后将任何剩余的 tokens 传递给strftime.

例如,要在视频上获得 datetime stamp,请传递%F %T %z:

  • %F displays the ISO-8601 date (2023-03-07)

  • %T displays 24h local time (for example, "09:57:12")

  • %z displays the timezone relative to UTC (for example, "-0800")

此阶段不输出任何 metadata,但会写入在 中找到的 metadataannotate.text in place of anything in the JSON configuration file. This allows other post-processing stages to write text onto images.

你可以使用以下参数配置此阶段:

text

要写入的文本字符串

fg

前景色

bg

背景色

scale

与文本大小成比例的数字

thickness

决定文本粗细的数字

alpha

覆盖背景像素时应用的 alpha 量

默认annotate_cv.json file:

{
    "annotate_cv" : {
        "text" : "Frame %frame exp %exp ag %ag dg %dg",
        "fg" : 255,
        "bg" : 0,
        "scale" : 1.0,
        "thickness" : 2,
        "alpha" : 0.3
    }
}

举例:

Writing camera and date information onto an image with annotations
将相机和日期信息写入带有标注的图像。

使用 TensorFlow Lite 进行后处理

先决条件

这些阶段需要导出 C++ API 的 TensorFlow Lite (TFLite) 库。从 Raspberry Pi OS特里西起,Raspberry Pi 构建并分发 TFLite 包,可使用以下命令安装:

$ sudo apt install libtensorflow-lite-dev

object_classify_tf stage

object_classify_tf uses a Google MobileNet v1 model to classify objects in the camera image. This stage requires a labels.txt file.

你可以使用以下参数配置此阶段:

top_n_results

要显示的结果数量

refresh_rate

模型运行之间必须经过的帧数

threshold_high

置信度阈值(介于 0 和 1 之间),达到该阈值即认为对象存在

threshold_low

对象在被丢弃为匹配项之前必须降至其以下的置信度阈值

model_file

TFLite 模型文件的文件路径

labels_file

包含对象标签的文件的文件路径

display_labels

是否在图像上显示对象标签;插入annotate.text metadata for the annotate_cv stage to render

verbose

向控制台输出更多信息

示例object_classify_tf.json file:

{
    "object_classify_tf" : {
        "top_n_results" : 2,
        "refresh_rate" : 30,
        "threshold_high" : 0.6,
        "threshold_low" : 0.4,
        "model_file" : "/home/<username>/models/mobilenet_v1_1.0_224_quant.tflite",
        "labels_file" : "/home/<username>/models/labels.txt",
        "display_labels" : 1
    },
    "annotate_cv" : {
        "text" : "",
        "fg" : 255,
        "bg" : 0,
        "scale" : 1.0,
        "thickness" : 2,
        "alpha" : 0.3
    }
}

该阶段处理大小为 224×224 的低分辨率流图像。运行以下命令以使用此阶段文件与rpicam-hello:

$ rpicam-hello --post-process-file object_classify_tf.json --lores-width 224 --lores-height 224
Object classification of a desktop computer and monitor
台式计算机和显示器的对象分类。

pose_estimation_tf stage

pose_estimation_tf uses a Google MobileNet v1 model to detect pose information.

你可以使用以下参数配置此阶段:

refresh_rate

模型运行之间必须经过的帧数

model_file

TFLite 模型文件的文件路径

verbose

向控制台输出额外信息

使用单独的plot_pose_cv stage to draw the detected pose onto the main image.

您可以对……进行配置。plot_pose_cv stage with the following parameters:

confidence_threshold

确定绘制多少的置信度阈值;可以小于零

示例pose_estimation_tf.json file:

{
    "pose_estimation_tf" : {
        "refresh_rate" : 5,
        "model_file" : "posenet_mobilenet_v1_100_257x257_multi_kpt_stripped.tflite"
    },
    "plot_pose_cv" : {
       "confidence_threshold" : -0.5
    }
}

该阶段处理大小为 257×257 的低分辨率流图像。因为 YUV420 图像必须具有偶数尺寸,所以对于 YUV420 图像向上取整为 258×258。

运行以下命令以将此阶段文件与rpicam-hello:

$ rpicam-hello --post-process-file pose_estimation_tf.json --lores-width 258 --lores-height 258
Pose estimation of an adult human male
成年男性的姿态估计。

object_detect_tf stage

object_detect_tf uses a Google MobileNet v1 SSD (Single Shot Detector) model to detect and label objects.

你可以使用以下参数配置此阶段:

refresh_rate

模型运行之间必须经过的帧数

model_file

TFLite 模型文件的文件路径

labels_file

包含标签列表的文件的文件路径

confidence_threshold

接受匹配前的置信度阈值

overlap_threshold

确定匹配之间的重叠量,以便将它们合并为单个匹配。

verbose

向控制台输出额外信息

使用单独的object_detect_draw_cv stage to draw the detected objects onto the main image.

您可以对……进行配置。object_detect_draw_cv stage with the following parameters:

line_thickness

边界框线条的粗细

font_size

用于标签的字体大小

示例object_detect_tf.json file:

{
    "object_detect_tf" : {
        "number_of_threads" : 2,
        "refresh_rate" : 10,
        "confidence_threshold" : 0.5,
        "overlap_threshold" : 0.5,
        "model_file" : "/home/<username>/models/coco_ssd_mobilenet_v1_1.0_quant_2018_06_29/detect.tflite",
        "labels_file" : "/home/<username>/models/coco_ssd_mobilenet_v1_1.0_quant_2018_06_29/labelmap.txt",
        "verbose" : 1
    },
    "object_detect_draw_cv" : {
       "line_thickness" : 2
    }
}

该 stage 在大小为 300×300 的低分辨率流图像上运行。运行以下命令,该命令从 400×300 低分辨率图像的中心将 300×300 的裁剪区域传递给检测器,以将此 stage 文件与rpicam-hello:

$ rpicam-hello --post-process-file object_detect_tf.json --lores-width 400 --lores-height 300
Detecting apple and cat objects
检测苹果和猫对象。

segmentation_tf stage

segmentation_tf uses a Google MobileNet v1 model. This stage requires a label file, found at the assets/segmentation_labels.txt.

该 stage 在大小为 257×257 的图像上运行。由于 YUV420 图像的尺寸必须为偶数,因此低分辨率图像的宽度和高度都应至少为 258 像素。该 stage 会向图像元数据添加一个 257×257 值的向量,其中每个值表示像素所属的类别。你可以选择将分割的表示绘制到图像的右下角。

你可以使用以下参数配置此阶段:

refresh_rate

模型运行之间必须经过的帧数

model_file

TFLite 模型文件的文件路径

labels_file

包含标签列表的文件的文件路径

threshold

当设置 verbose 时,当带有任何标签的像素数超过此数字时打印

draw

将分割图绘制到图像的右下角

verbose

向控制台输出额外信息

示例segmentation_tf.json file:

{
    "segmentation_tf" : {
        "number_of_threads" : 2,
        "refresh_rate" : 10,
        "model_file" : "/home/<username>/models/lite-model_deeplabv3_1_metadata_2.tflite",
        "labels_file" : "/home/<username>/models/segmentation_labels.txt",
        "draw" : 1,
        "verbose" : 1
    }
}

此示例获取相机图像并将其缩小到 258×258 像素大小。此 stage 甚至可以在不裁剪的情况下压缩非正方形图像时工作。此示例启用右下角的分割图。

运行以下命令以将此阶段文件与rpicam-hello:

$ rpicam-hello --post-process-file segmentation_tf.json --lores-width 258 --lores-height 258 --viewfinder-width 1024 --viewfinder-height 1024
Running segmentation and displaying the results on a map in the bottom right
运行分割并将结果显示在右下角的地图上。

编写你自己的后处理 stage

在Terren Peterson的助力下,rpicam-apps post-processing framework, users can create their own custom post-processing stages. You can even include algorithms and routines from OpenCV and TensorFlow Lite.

基础后处理 stage

要创建你自己的后处理 stage,请从PostProcessingStage class. All post-processing stages must implement the following member functions:

char const *Name() const

返回 stage 的名称。与 JSON 后处理配置文件中列出的 stage 进行匹配。

void Read(boost::property_tree::ptree const &params)

从提供的 JSON 文件中读取该 stage 的配置参数。

void AdjustConfig(std::string const &use_case, StreamConfiguration *config)

让 stage 有机会影响相机的配置。对于无需配置相机的 stage,通常为空。

void Configure()

在相机配置完成后调用,以分配资源并检查该 stage 是否可以访问必要的流。

void Start()

在相机启动时调用。对于无需配置相机的 stage,通常为空。

bool Process(CompletedRequest &completed_request)

呈现已完成的相机请求以进行后处理。这里你将实现像素操作和图像分析。返回true if the post-processing framework should 先拔下连接器的一端将此请求传递给应用程序。

void Stop()

在相机停止时调用。用于关闭异步线程上的任何活动处理。

void Teardown()

在相机配置被销毁时调用。可将其用作析构函数,在其中可以释放已在 中设置的资源Configure method.

在任何阶段实现中,请调用RegisterStage to register your stage with the system.

不要忘记将你的阶段添加到meson.build in the post-processing folder. When writing your own stages, keep these tips in mind:

  • 该Process method blocks the imaging pipeline. If it takes too long, the pipeline will stutter. 始终将耗时算法委托给异步线程。

  • 将工作委托给另一个线程时,必须复制图像缓冲区。对于图像分析等不需要全分辨率的应用,尝试使用低分辨率图像流。

  • 后处理框架使用并行性处理每一帧。这提高了吞吐量。但是,一些 OpenCV 和 TensorFlow Lite 函数引入了另一层并行性在每一帧内。考虑在每一帧内串行化调用,因为后处理已经利用了多线程。

  • 大多数流(包括低分辨率流)使用 YUV420 格式。对于某些 OpenCV 或 TFLite 函数,你可能需要将其转换为另一种格式。

  • 为了获得最佳性能,请始终原地修改图像。

有关基本示例,请参见negate_stage.cpp。此阶段通过将亮像素变暗、暗像素变亮来对图像取反。此阶段主要是派生类的样板代码,仅用六行代码就实现了取反逻辑。

另一个示例,请参见sobel_cv_stage.cpp,它仅用几行 OpenCV 函数就实现了 Sobel 滤波器。

TensorFlow Lite 阶段

对于使用 TensorFlow Lite (TFLite) 的阶段,请从TfStage class. This class delegates model execution to a separate thread to prevent camera stuttering.

该TfStage class implements all the PostProcessingStage member functions post-processing stages must normally implement, 派生一个新类,但以下情况除外: Name. All TfStage-derived stages must implement the Name function, and should implement some or all of the following virtual member functions:

void readExtras()

基类读取命名模型以及某些其他参数,例如refresh_rate. Use this function to read extra parameters for the derived stage and check that the loaded model is correct (for example, has right input and output dimensions).

void checkConfiguration()

基类获取 TFLite 所操作的低分辨率流,以及派生阶段可能需要的全分辨率流。使用此函数检查你的阶段所需的流。如果你的阶段无法访问某个所需流,你可以跳过处理或抛出错误。

void interpretOutputs()

使用此函数读取并解释模型输出。在模型完成时与模型在同一线程中运行.

void applyResults()

使用此函数将模型的结果(可能是几帧之前的)应用到当前帧。通常涉及附加元数据或绘制。在主线程中运行,在帧被传递之前.

高级rpicam-apps

构建libcamera and rpicam-apps

构建libcamera and rpicam-apps for yourself for the following benefits:

  • 你可以获取最新的增强功能和特性。

  • rpicam-apps can be compiled with extra optimisation for Raspberry Pi 3 and Raspberry Pi 4 devices running a 32-bit OS.

  • 你可以包含可选的 OpenCV 和/或 TFLite 后处理阶段,或添加你自己的。

  • 你可以自定义或添加你自己的、派生自以下内容的应用程序rpicam-apps

移除预安装的rpicam-apps

Raspberry Pi OS 包含以下内容的预安装副本rpicam-apps. Before building and installing your own version of rpicam-apps, you must first remove the pre-installed version. Run the following command to remove the rpicam-apps package from your Raspberry Pi:

$ sudo apt remove --purge rpicam-apps

构建rpicam-apps without building libcamera

要搭建……rpicam-apps without first rebuilding libcamera and libepoxy, install libcamera, libepoxy and their dependencies with apt:

$ sudo apt install -y libcamera-dev libepoxy-dev libjpeg-dev libtiff5-dev libpng-dev libopencv-dev
如果你不需要对 GLES/EGL 预览窗口的支持,请省略libepoxy-dev.

要使用 Qt 预览窗口,请安装以下额外依赖项:

$ sudo apt install -y qtbase5-dev libqt5core5a libqt5gui5 libqt5widgets5

对于libav支持在rpicam-vid, install the following additional dependencies:

$ sudo apt install libavcodec-dev libavdevice-dev libavformat-dev libswresample-dev

如果你运行 Raspberry Pi OS Lite,请安装git:

$ sudo apt install -y git

构建libcamera

仅构建libcamera from scratch if you need custom behaviour or the latest features that have not yet reached apt repositories.

如果你运行 Raspberry Pi OS Lite,请先安装以下软件包:

$ sudo apt install -y python3-pip git python3-jinja2

首先,安装以下libcamera dependencies:

$ sudo apt install -y libboost-dev
$ sudo apt install -y libgnutls28-dev openssl libtiff5-dev pybind11-dev
$ sudo apt install -y qtbase5-dev libqt5core5a libqt5gui5 libqt5widgets5
$ sudo apt install -y meson cmake
$ sudo apt install -y python3-yaml python3-ply
$ sudo apt install -y libglib2.0-dev libgstreamer-plugins-base1.0-dev

现在我们准备好构建libcamera itself.

下载以下内容的 Raspberry Pi fork 的本地副本libcamera from GitHub:

$ git clone https://github.com/raspberrypi/libcamera.git

导航到仓库的根目录:

$ cd libcamera

接下来,运行meson to configure the build environment:

$ meson setup build --buildtype=release -Dpipelines=rpi/vc4,rpi/pisp -Dipas=rpi/vc4,rpi/pisp -Dv4l2=true -Dgstreamer=enabled -Dtest=false -Dlc-compliance=disabled -Dcam=disabled -Dqcam=disabled -Ddocumentation=disabled -Dpycamera=enabled
你可以禁用gstreamer plugin by replacing -Dgstreamer=enabled with -Dgstreamer=disabled during the meson build configuration. If you disable gstreamer, there is no need to install the libglib2.0-dev and libgstreamer-plugins-base1.0-dev dependencies.

现在,你可以构建libcamera with ninja:

$ ninja -C build

最后,运行以下命令以安装你刚刚构建的libcamera binary:

$ sudo ninja -C build install
在内存为 1 GB 或更少的设备上,构建可能会超出可用内存。追加-j 1 flag to ninja commands to limit the build to a single process. This can prevent the build from exceeding available memory on devices like the Raspberry Pi Zero and the Raspberry Pi 3.

libcamera does not yet have a stable binary interface. Always build rpicam-apps after you build libcamera.

构建rpicam-apps

首先获取以下内容所需的依赖项rpicam-apps.

$ sudo apt install -y cmake libboost-program-options-dev libdrm-dev libexif-dev libpng-dev
$ sudo apt install -y meson ninja-build

下载 Raspberry Pi 设备的本地副本rpicam-apps GitHub repository:

$ git clone https://github.com/raspberrypi/rpicam-apps.git

导航到仓库的根目录:

$ cd rpicam-apps

对于像 Raspberry Pi OS 这样的基于桌面的操作系统,配置rpicam-apps build with the following meson command:

$ meson setup build -Denable_libav=enabled -Denable_drm=enabled -Denable_egl=enabled -Denable_qt=enabled -Denable_opencv=disabled -Denable_tflite=disabled -Denable_hailo=disabled

对于像 Raspberry Pi OS Lite 这样的无头操作系统,请配置rpicam-apps build with the following meson command:

$ meson setup build -Denable_libav=disabled -Denable_drm=enabled -Denable_egl=disabled -Denable_qt=disabled -Denable_opencv=disabled -Denable_tflite=disabled -Denable_hailo=disabled
  • 使用-Dneon_flags=armv8-neon to enable optimisations for 32-bit OSes on Raspberry Pi 3 or Raspberry Pi 4.

  • 使用-Denable_opencv=enabled if you have installed OpenCV and wish to use OpenCV-based post-processing stages.

  • 使用-Denable_tflite=enabled if you have installed TensorFlow Lite and wish to use it in post-processing stages.

  • 使用-Denable_hailo=enabled if you have installed HailoRT and wish to use it in post-processing stages.

现在你可以构建rpicam-apps with the following command:

$ meson compile -C build
在内存为 1 GB 或更少的设备上,构建可能会超出可用内存。追加-j 1 flag to meson commands to limit the build to a single process. This can prevent the build from exceeding available memory on devices like the Raspberry Pi Zero and the Raspberry Pi 3.

最后,运行以下命令以安装你刚刚构建的rpicam-apps binary:

$ sudo meson install -C build

前面的命令会自动更新ldconfig cache. If you have trouble accessing your new rpicam-apps build, run the following command to update the cache:

$ sudo ldconfig

运行以下命令以检查你的设备是否使用新的二进制文件:

$ rpicam-still --version

输出包含你本地rpicam-apps build.

最后,按照dtoverlay and display driver instructions in the 配置部分.

rpicam-apps meson flag reference

该meson build configuration for rpicam-apps supports the following flags:

-Dneon_flags=armv8-neon

加快运行 32 位操作系统的 Raspberry Pi 3 或 Raspberry Pi 4 设备上的某些后处理功能。

-Denable_libav=enabled

启用或禁用libav encoder integration.

-Denable_drm=enabled

启用或禁用DRM/KMS 预览渲染,这是在缺少桌面环境时使用的预览窗口。

-Denable_egl=enabled

启用或禁用基于非 Qt 桌面环境的预览。如果你的系统缺少桌面环境,请禁用。

-Denable_qt=enabled

启用或禁用对预览窗口的基于 Qt 实现的支持。如果未安装桌面环境,或者你不打算使用基于 Qt 的预览窗口,请禁用。通常不建议使用基于 Qt 的预览,因为它的计算开销非常高,不过它确实可与 X display forwarding 一起使用。

-Denable_opencv=enabled

强制基于 OpenCV 的后处理阶段链接或不链接。需要 OpenCV 才能启用。默认值为disabled.

-Denable_tflite=enabled

启用或禁用 TensorFlow Lite 后处理阶段。默认禁用。需要 Tensorflow Lite 才能启用。取决于你如何构建和/或安装 TFLite,你可能需要调整meson.build file in the post_processing_stages directory.

-Denable_hailo=enabled

启用或禁用基于 HailoRT 的后处理阶段。需要 HailoRT 才能启用。默认值为auto.

-Ddownload_hailo_models=true

下载并安装用于 HailoRT 后处理阶段的模型。需要wget to be installed. Defaults to true.

上述每个选项(除了neon_flags) supports the following values:

  • enabled: enables the option, fails the build if dependencies are not available

  • disabled: disables the option

  • auto: enables the option if dependencies are available

构建libepoxy

重新构建libepoxy isn’t normally necessary because this library changes very rarely. If you do want to build it from scratch, follow the instructions below.

首先安装必要的依赖项。

$ sudo apt install -y libegl1-mesa-dev

接下来,下载libepoxy repository from GitHub:

$ git clone https://github.com/anholt/libepoxy.git

导航到仓库的根目录:

$ cd libepoxy

在仓库根目录级别创建一个构建目录,然后进入该目录:

$ mkdir _build
$ cd _build

接下来,运行meson to configure the build environment:

$ meson

现在,你可以构建libexpoxy with ninja:

$ ninja

最后,运行以下命令以安装你刚刚构建的libepoxy binary:

$ sudo ninja install

编写你自己的rpicam apps

rpicam-apps does not provide all of the camera-related features that anyone could ever need. Instead, these applications are small and flexible. Users who require different behaviour can implement it themselves.

所有的rpicam-apps use an event loop that receives messages when a new set of frames arrives from the camera system. This set of frames is called a CompletedRequest. The CompletedRequest contains:

  • 由该单个相机帧派生的所有图像:通常是低分辨率图像和全尺寸输出

  • 来自相机和后处理系统的元数据

rpicam-hello

rpicam-hello is the smallest application, and the best place to start understanding rpicam-apps design. It extracts the CompletedRequestPtr, a shared pointer to the CompletedRequest, from the message, and forwards it to the preview window:

CompletedRequestPtr &completed_request = std::get<CompletedRequestPtr>(msg.payload);
app.ShowPreview(completed_request, app.ViewfinderStream());

每个CompletedRequest must be recycled back to the camera system so that the buffers can be reused. Otherwise, the camera runs out of buffers for new camera frames. This recycling process happens automatically when no references to the CompletedRequest remain using C++'s 共享指针和自定义删除器机制。

因此,rpicam-hello must complete the following actions to recycle the buffer space:

  • 事件循环必须完成一个周期,以便消息(msg in the code), which holds a reference to CompletedRequest, can be replaced with the next message. This discards the reference to the previous message.

  • 当事件线程调用ShowPreview, it passes the preview thread a reference to the CompletedRequest. The preview thread discards the last CompletedRequest instance each time ShowPreview is called.

rpicam-vid

rpicam-vid is similar to rpicam-hello with encoding added to the event loop. Before the event loop starts, rpicam-vid configures the encoder with a callback. The callback handles the buffer containing the encoded image data. In the code below, we send the buffer to the Output object. Output could write it to a file or stream it, depending on the options specified.

app.SetEncodeOutputReadyCallback(std::bind(&Output::OutputReady, output.get(), _1, _2, _3, _4));

因为此代码将以下对象的引用传递给编码器:CompletedRequest, rpicam-vid can’t recycle buffer data until the event loop, preview window, 和编码器全部丢弃它们的引用。

rpicam-raw

rpicam-raw is similar to rpicam-vid. It also encodes during the event loop. However, rpicam-raw uses a dummy encoder called the NullEncoder. This uses the input image as the output buffer instead of encoding it with a codec. NullEncoder only discards its reference to the buffer when the output callback completes. This guarantees that the buffer isn’t recycled before the callback processes the image.

rpicam-raw doesn’t forward anything to the preview window.

NullEncoder is possibly overkill in rpicam-raw. We could probably send images straight to the Output object, instead. However, rpicam-apps need to limit work in the event loop. NullEncoder demonstrates how you can handle most processes (even holding onto a reference) in other threads.

rpicam-jpeg

rpicam-jpeg starts the camera in preview mode in the usual way. When the timer completes, it stops the preview and switches to still capture:

app.StopCamera();
app.Teardown();
app.ConfigureStill();
app.StartCamera();

事件循环抓取静态模式返回的第一帧,并将其保存为 JPEG。

使用libcamera with Qt

Qt 是一个流行的应用程序框架和 GUI 工具包。rpicam-apps includes an option to use Qt for a camera preview window.

不幸的是,Qt 定义了某些符号(例如slot and emit) as macros in the global namespace. This causes errors when including libcamera files. The problem is common to all platforms that use both Qt and libcamera. Try the following workarounds to avoid these errors:

  • 列出libcamera include files, or files that include libcamera files (such as rpicam-apps files), 之前任何 Qt 头文件(尽可能)。

  • 如果你确实需要将你的 Qt 应用程序文件与libcamera includes, replace signals: with Q_SIGNALS:, slots: with Q_SLOTS:, emit with Q_EMIT and foreach with Q_FOREACH.

  • 在任意 的顶部添加以下内容:libcamera include files:

    #undef signals
    #undef slots
    #undef emit
    #undef foreach
  • 如果你的项目使用qmake, add CONFIG += no_keywords to the project file.

  • 如果你的项目使用cmake, add SET(QT_NO_KEYWORDS ON).

使用libcamera from Python with Picamera2

Picamera2 是用于 Raspberry Pi 相机的 Python 库。它构建于libcamera, the same camera software stack that rpicam-apps uses, and replaces Picamera, the Python library for the legacy camera stack.

当你想要通过自己的 Python 代码控制相机时,请使用 Picamera2,例如捕获图像和视频、更改相机设置、在帧到达时处理帧,或将相机集成到更大的应用程序中。对于现成的命令行应用程序,请使用rpicam-apps.

完整文档请参阅Picamera2 手册树莓派5Picamera2 GitHub 仓库.

安装

较新的 Raspberry Pi OS 镜像包含 Picamera2 以及所有图形用户界面(GUI)依赖项,例如 Qt 和 OpenGL。较新的 Raspberry Pi OS Lite 镜像包含 Picamera2,但不含 GUI 依赖项,不过你仍可以通过 Direct Rendering Manager(DRM)和 Kernel Mode Setting(KMS)显示预览图像。

如果你的镜像未包含 Picamera2,请运行以下命令以安装包含所有 GUI 依赖项的 Picamera2:

$ sudo apt install -y python3-picamera2

如果你不想要 GUI 依赖项,可以运行以下命令安装不带 GUI 依赖项的 Picamera2:

$ sudo apt install -y python3-picamera2 --no-install-recommends
如果你之前安装了 Picamera2,并使用pip, uninstall it with: pip3 uninstall picamera2.

更新 Picamera2

Picamera2 依赖其他系统软件包,包括libcamera. To keep these packages compatible with each other, update Picamera2 as part of a full system upgrade, rather than updating the python3-picamera2 package on its own.

在执行完整系统升级之前,请备份所有重要文件。

要更新 Picamera2:

  1. 更新可用软件包列表:

    $ sudo apt update
  2. 升级所有已安装的软件包,包括 Picamera2 和libcamera, so that they’re up to date:

    $ sudo apt full-upgrade

    使用full-upgrade rather than upgrade. Unlike upgrade, full-upgrade can install new dependencies and remove packages that conflict with them, so all your camera packages update together.

  3. 重启你的 Raspberry Pi,以确保加载任何已更新的内核、固件和摄像头驱动程序:

    $ sudo reboot
  4. 可选:检查已安装的 Picamera2 版本:

    $ dpkg -s python3-picamera2 | grep Version
如果你使用的是较早的 Raspberry Pi OS 镜像,请考虑改用 Raspberry Pi Imager 安装最新镜像。

使用 hello world 脚本测试你的摄像头

要检查 Picamera2 是否能与你的摄像头配合工作,请创建一个名为hello_world.py containing the following code:

from picamera2 import Picamera2
import time

picam2 = Picamera2()
picam2.start(show_preview=True)
time.sleep(5)

运行脚本:

$ python3 hello_world.py

预览窗口会打开并显示摄像头画面五秒钟,然后脚本退出。Picamera2 会为你选择预览窗口的类型:在带桌面的 Raspberry Pi OS 上使用 Qt 窗口,在 Raspberry Pi OS Lite 上使用 DRM/KMS 预览。

使用 USB 网络摄像头

大多数 Raspberry Pi 设备都有用于摄像头模块的专用端口。摄像头模块是高质量、高度可配置的摄像头,深受 Raspberry Pi 用户欢迎。

但是,对于许多用途来说,USB 网络摄像头具备从你的 Raspberry Pi 录制图片和视频所需的一切。本节介绍如何在你的 Raspberry Pi 上使用 USB 网络摄像头。

安装依赖项

首先,安装fswebcam package:

$ sudo apt install fswebcam

接下来,将你的用户名添加到video group, otherwise you might see 'permission denied' errors:

$ sudo usermod -a -G video <username>

要检查用户是否已正确添加到该组,请使用groups command.

拍摄照片

运行以下命令使用网络摄像头拍摄照片,并将图像保存到名为image.jpg:

$ fswebcam image.jpg

您应该会看到类似如下的输出:

--- Opening /dev/video0...
Trying source module v4l2...
/dev/video0 opened.
No input was specified, using the first.
Adjusting resolution from 384x288 to 352x288.
--- Capturing frame...
Corrupt JPEG data: 2 extraneous bytes before marker 0xd4
Captured frame in 0.00 seconds.
--- Processing captured image...
Writing JPEG image to 'image.jpg'.
By default
默认情况下,fswebcam uses a low resolution and adds a banner displaying a timestamp.

要为捕获的图像指定不同的分辨率,请使用-r flag, passing a width and height as two numbers separated by an x:

$ fswebcam -r 1280x720 image2.jpg

您应该会看到类似如下的输出:

--- Opening /dev/video0...
Trying source module v4l2...
/dev/video0 opened.
No input was specified, using the first.
--- Capturing frame...
Corrupt JPEG data: 1 extraneous bytes before marker 0xd5
Captured frame in 0.00 seconds.
--- Processing captured image...
Writing JPEG image to 'image2.jpg'.
Specify a resolution to capture a higher quality image
指定分辨率以捕获更高质量的图像。

移除横幅

要从捕获的图像中移除横幅,请使用--no-banner flag:

$ fswebcam --no-banner image3.jpg

您应该会看到类似如下的输出:

--- Opening /dev/video0...
Trying source module v4l2...
/dev/video0 opened.
No input was specified, using the first.
--- Capturing frame...
Corrupt JPEG data: 2 extraneous bytes before marker 0xd6
Captured frame in 0.00 seconds.
--- Processing captured image...
Disabling banner.
Writing JPEG image to 'image3.jpg'.
Specify `--no-banner` to save the image without the timestamp banner
指定--no-banner to save the image without the timestamp banner.

自动化图像捕获

不同于rpicam-apps, fswebcam doesn’t have any built-in functionality to substitute timestamps and numbers in output image names. This can be useful when capturing multiple images, since manually editing the file name every time you record an image can be tedious. Instead, use a Bash script to implement this functionality yourself.

创建一个新文件,命名为webcam.sh in your home folder. Add the following example code, which uses the bash programming language to save images to files with a file name containing the year, month, day, hour, minute, and second:

#!/bin/bash

DATE=$(date +"%Y-%m-%d_%H-%M-%S")

fswebcam -r 1280x720 --no-banner $DATE.jpg

然后,通过运行以下命令使 bash 脚本可执行:

$ chmod +x webcam.sh

使用以下命令运行脚本以捕获图像并将其保存到以时间戳命名的文件中,类似于2024-05-10_12-06-33.jpg:

$ ./webcam.sh

您应该会看到类似如下的输出:

--- Opening /dev/video0...
Trying source module v4l2...
/dev/video0 opened.
No input was specified, using the first.
--- Capturing frame...
Corrupt JPEG data: 2 extraneous bytes before marker 0xd6
Captured frame in 0.00 seconds.
--- Processing captured image...
Disabling banner.
Writing JPEG image to '2024-05-10_12-06-33.jpg'.

拍摄延时摄影

使用cron to schedule photo capture at a given interval. With the right interval, such as once a minute, you can capture a time lapse.

首先,打开 cron 表进行编辑:

$ crontab -e

在编辑器中打开文件后,将以下行添加到计划中,以每分钟拍摄一张照片,替换<username> with your username:

* * * * * /home/<username>/webcam.sh 2>&1

保存并退出,你应该会看到以下消息:

crontab: installing new crontab

V4L2 驱动程序

V4L2 驱动程序提供标准 Linux 接口,用于访问摄像头和编解码器功能。通常,Linux 在启动期间会自动加载驱动程序。但在某些情况下,你可能需要显式加载摄像头驱动程序.

使用以下内容时的设备节点libcamera

/dev/videoX 默认操作

video0

第一个 CSI-2 接收器的 Unicam 驱动程序

video1

第二个 CSI-2 接收器的 Unicam 驱动程序

video10

视频解码

video11

视频编码

video12

简单 ISP,除 Bayer 到 RGB/YUV 转换外,还可以在 RGB/YUV 格式之间执行转换和调整大小

video13

完全可编程 ISP 的输入

video14

完全可编程 ISP 的高分辨率输出

video15

完全可编程 ISP 的低结果输出

video16

来自完全可编程 ISP 的图像统计信息

video19

HEVC 解码

使用 V4L2 驱动程序

有关如何使用 V4L2 驱动程序的更多信息,请参阅V4L2 文档.

尤尼卡姆

Raspberry Pi SoC 均具有两个摄像头接口,支持 CSI-2 D-PHY 1.1 或 Compact Camera Port 2 (CCP2) 源。此接口的代号为 Unicam。Unicam 的第一个实例支持两条 CSI-2 数据通道,而第二个实例支持四条。每条通道最高可运行在 1Gbit/s(DDR,因此最大链路频率为 500 MHz)。

Compute Modules 和 Raspberry Pi 5 会从两个外设引出所有通道。Raspberry Pi 5 之前的其他型号仅暴露第二个实例,并且只将两条数据通道引出到摄像头连接器。

软件接口

V4L2 软件接口是与 Unicam 外设通信的唯一方式。过去还曾有固件和 MMAL rawcam 组件接口,但这些已不再受支持。

V4L2

Unicam 的 V4L2 接口仅在使用时可用libcamera.

Unicam 模块有一个完全开源的内核驱动程序可用;此内核模块名为bcm2835-unicam, interfaces with V4L2 subdevice drivers to deliver raw frames. This bcm2835-unicam driver controls the sensor and configures the Camera Serial Interface 2 (CSI-2) receiver. Peripherals write raw frames (after Debayer) to SDRAM for V4L2 to deliver to applications. There is no image processing between the camera sensor capturing the image and the bcm2835-unicam driver placing the image data in SDRAM except for Bayer unpacking to 16bits/pixel.

Architecture diagram showing the relationship between the bcm2835-unicam kernel module
bcm2835-unicam 架构图

主线 Linux 包含一系列现有驱动程序。Raspberry Pi 内核树有一些附加驱动程序和用于配置它们的 Device Tree overlays:

设备 类型 注释

Omnivision OV5647

5 MP 摄像头

原始树莓派摄像头

Sony IMX219 和 IMX355

8 MP 摄像头

第2版树莓派摄像头

三星 IMX477

12 MP 摄像头

树莓派高分辨率摄像头

三星 IMX708

12 MP 摄像头

树莓派摄像头模块3

三星 IMX296

1.6 MP 摄像头

树莓派全局快门摄像头模块

东芝 TC358743

HDMI 转 CSI-2 桥接

模拟器件 ADV728x-M

模拟视频转 CSI-2 桥接

不支持隔行扫描

英飞凌 IRS1125

飞行时间深度传感器

由第三方支持

由于子设备驱动也是具有标准化 API 的内核驱动,第三方可以自由地为他们选择的任何信号源编写自己的驱动。

编写第三方驱动

这是通过 Unicam 进行对接的推荐方法。

在开发用于新设备的驱动并打算提交到bcm2835-unicam module, you need the driver and corresponding device tree overlays. Ideally, you submit the driver to the linux-media邮件列表进行代码审查并合并到主线时。然后它会被移到Raspberry Pi 内核树;但也可以例外地让驱动直接审查并合并到 Raspberry Pi 内核。

所有内核驱动均依据 GPLv2 许可证授权,因此源代码必须可用。仅发布二进制模块违反了 Linux 内核所采用的 GPLv2 许可证。

该bcm2835-unicam module has been written to try and accommodate all types of CSI-2 source driver that are currently found in the mainline Linux kernel. These can be split broadly into camera sensors and bridge chips. Bridge chips allow for conversion between some other format and CSI-2.

摄像头传感器

摄像头传感器的传感器驱动负责设备的所有配置,通常通过 I2C 或 SPI。与其从头编写驱动,通常更容易以现有驱动为基础并酌情修改。

该IMX219 驱动是一个不错的起点。该驱动同时支持 8bit 和 10bit Bayer 读出,因此枚举帧格式和帧大小会稍微复杂一些。

传感器通常支持V4L2 用户控件。并非所有这些控件都需要在驱动程序中实现。IMX219 驱动程序只实现了下面列出的一小部分,其实现由imx219_set_ctrl function.

  • V4L2_CID_PIXEL_RATE / V4L2_CID_VBLANK / V4L2_CID_HBLANK: allows the application to set the frame rate

  • V4L2_CID_EXPOSURE: sets the exposure time in lines; the application needs to use V4L2_CID_PIXEL_RATE, V4L2_CID_HBLANK, and the frame width to compute the line time

  • V4L2_CID_ANALOGUE_GAIN: analogue gain in sensor specific units

  • V4L2_CID_DIGITAL_GAIN: optional digital gain in sensor specific units

  • V4L2_CID_HFLIP / V4L2_CID_VFLIP: flips the image either horizontally or vertically; this operation can change the Bayer order of the data in the frame, as is the case on the IMX219.

  • V4L2_CID_TEST_PATTERN / V4L2_CID_TEST_PATTERN_*: enables output of various test patterns from the sensor; useful for debugging

对于 IMX219,其中许多控件直接映射为对传感器本身的寄存器写入。

更多指导可在libcamera 传感器驱动要求中找到,以及在第 3 章中,见Raspberry Pi Camera 调优指南.

设备树

Device Tree 用于选择传感器驱动程序并配置参数,例如 CSI-2 lane 数量、连续时钟 lane 操作和链路频率(通常只支持一种)。

IMX219 的设备树叠加层(用于 6.1 内核)可在 GitHub 上获得。

桥接芯片

这些设备将传入的视频流(例如 HDMI 或复合视频)转换为可被 Raspberry Pi CSI-2 接收器接受的 CSI-2 流。

处理桥接芯片更为复杂。与相机传感器不同,它们必须响应传入信号并将其报告给应用程序。

处理桥接芯片的机制可分为两类:模拟或数字。

使用ioctls in the sections below, an S in the ioctl name means it is a set function, while G is a get function and ENUM enumerates a set of permitted values.

模拟视频源

模拟视频源使用标准ioctls for detecting and setting video standards. VIDIOC_G_STD, VIDIOC_S_STD, VIDIOC_ENUMSTD以及VIDIOC_QUERYSTD可用。

选择错误的标准通常会导致图像损坏。设置标准通常还会设置 V4L2 CAPTURE 队列上的分辨率。它不能通过VIDIOC_S_FMT. Generally, requesting the detected standard through VIDIOC_QUERYSTD and then setting it with VIDIOC_S_STD before streaming is a good idea.

数字视频源

对于数字视频源(例如 HDMI),还有另一组调用可用于指定所有数字时序参数:VIDIOC_G_DV_TIMINGS, VIDIOC_S_DV_TIMINGS, VIDIOC_ENUM_DV_TIMINGS以及VIDIOC_QUERY_DV_TIMINGS.

与模拟桥接芯片一样,时序通常固定 V4L2 CAPTURE 队列分辨率,并且调用VIDIOC_S_DV_TIMINGS with the result of VIDIOC_QUERY_DV_TIMINGS before streaming ensures that the format is correct.

取决于桥接芯片和驱动程序,输入源的变化可能可以通过以下方式报告给应用程序:VIDIOC_SUBSCRIBE_EVENT and V4L2_EVENT_SOURCE_CHANGE.

当前支持的设备

目前 Raspberry Pi Linux 内核支持两种桥接芯片:用于模拟视频源的 Analog Devices ADV728x-M,以及用于 HDMI 源的 Toshiba TC358743。

Analog Devices ADV728x(A)-M 模拟视频到 CSI2 桥接芯片可将复合、S-video(Y/C)或分量(YPrPb)视频转换为单通道 CSI-2 接口,并由以下驱动支持:ADV7180 内核驱动.

该芯片各版本的产品详情可在 Analog Devices 网站上找到:ADV7280A, ADV7281A以及ADV7282A.

由于当前核心 V4L2 实现中缺少一些代码,选择源会失败,因此 Raspberry Pi 内核版本添加了一个名为dbg_input to the ADV7180 kernel driver which sets the input source every time VIDIOC_S_STD is called. At some point mainstream will fix the underlying issue (a disjoin between the kernel API call s_routing, and the userspace call VIDIOC_S_INPUT) and this modification will be removed.

不支持接收隔行视频,因此该芯片的 ADV7281(A)-M 版本用途有限,因为它没有必要的 I2P 去隔行模块。另外,在选择器件时请确保指定 -M 选项。否则你会得到并行输出总线,无法与 Raspberry Pi 对接。

目前没有已知的使用这些芯片的商用板卡,但该驱动已由 Analog DevicesEVAL-ADV7282-M 评估板测试.

该驱动可使用以下方式加载:config.txt dtoverlay adv7282m if you are using the ADV7282-M chip variant; or adv728x-m with a parameter of either adv7280m=1, adv7281m=1, or adv7281ma=1 if you are using a different variant.

dtoverlay=adv728x-m,adv7280m=1

Toshiba TC358743 是一款 HDMI 到 CSI-2 桥接芯片,能够转换最高 1080p60 的视频数据。

有关该桥接芯片的信息可在以下网站找到:Toshiba 网站.

TC358743 将 HDMI 接口转换为 CSI-2 和 I2S 输出。它由以下模块支持:TC358743 内核模块.

该芯片支持接收 RGB888、YUV444 或 YUV422 的 HDMI 输入信号,最高可达 1080p60。它可以转发 RGB888,或将其转换为 YUV444 或 YUV422,并可在 YUV444 与 YUV422 之间双向转换。仅测试了 RGB888 和 YUV422 支持。使用两个 CSI-2 通道时,可支持的最高速率为 RGB888 的 1080p30,或 YUV422 的 1080p50。在 Compute Module 上使用四个通道时,两种格式均可接收 1080p60。

HDMI 通过接收设备通告一个[25] 对于具备多个 HDMI 端口的设备,某些 HDMI 命令可应用于任意端口。您可以使用语法来协商分辨率,该 EDID 包含其可支持的所有模式。内核驱动并不知道你希望接收的分辨率、帧率或格式,因此需要用户通过 VIDIOC_S_EDID ioctl 提供合适的文件,或更简便地使用v4l2-ctl --fix-edid-checksums --set-edid=file=filename.txt (adding the --fix-edid-checksums option means that you don’t have to get the checksum values correct in the source file). Generating the required EDID file (a textual hexdump of a binary EDID file) is not too onerous, and there are tools available to generate them, but it is beyond the scope of this page.

如上所述,使用DV_TIMINGS ioctls to configure the driver to match the incoming video. The easiest approach for this is to use the command v4l2-ctl --set-dv-bt-timings query. The driver does support generating the SOURCE_CHANGED events, if you want to write an application to handle a changing source. Changing the output pixel format is achieved by setting it by using VIDIOC_S_FMT, but only the pixel format field will be updated as the resolution is configured by the DV timings.

有几款商用板卡可将该芯片连接到 Raspberry Pi。Auvidea B101 和 B102 最容易获得,但还有其他等效板卡可用。

该驱动使用以下方式加载:config.txt dtoverlay tc358743.

该芯片还支持通过 I2S 采集立体声 HDMI 音频。Auvidea 板卡将相关信号引出到排针,可连接到 Raspberry Pi 设备的 40-pin header。所需接线如下:

信号 B101 排针 40 针排针 BCM GPIO

LRCK/WFS

7

35

https://www.raspberrypi.org/?p=65103

BCK/SCK

6

英国皇家学会圣诞讲座:抢先看

18

DATA/SD

5

38

20

GND

8

39

不适用

该tc358743-audio overlay is required 除……之外[11] 图像信号处理器tc358743 overlay. This creates an ALSA recording device for the HDMI audio.

音频未进行重采样。音频的存在情况反映在 V4L2 控件中TC358743_CID_AUDIO_PRESENT (audio-present), and the sample rate of the incoming audio is reflected in the V4L2 control TC358743_CID_AUDIO_SAMPLING_RATE (audio sampling-frequency). Recording when no audio is present or at a sample rate different from that reported emits a warning.

……之间的差异rpicam and raspicam

该rpicam-apps emulate most features of the legacy raspicam applications. However, you might notice the following differences:

  • Boostprogram_options don’t allow multi-character short versions of options, so where these were present they have had to be dropped. The long form options are named the same way, and any single-character short forms are preserved.

  • rpicam-still and rpicam-jpeg do not show the captured image in the preview window.

  • rpicam-apps removed the following raspicam features:

    • 不透明度(--opacity)

    • 图像效果(--imxfx)

    • 色彩效果(--colfx)

    • 标注(--annotate, --annotateex)

    • 动态范围压缩,即 DRC(--drc)

    • 立体声(--stereo, --decimate and --3dswap)

    • 图像稳定(--vstab)

    • 演示模式(--demo)

      后处理替代了其中许多功能。

  • rpicam-apps removed rotation选项支持 90° 和 270° 旋转。

  • raspicam conflated metering and exposure; rpicam-apps separates these options.

  • 要禁用 Auto White Balance (AWB),在rpicam-apps, set a pair of colour gains with awbgains(例如,1.0,1.0).

  • rpicam-apps cannot set Auto White Balance (AWB) into greyworld mode for NoIR camera modules. Instead, pass the tuning-file选择一个类似 NoIR-specific tuning file 的选项,例如imx219_noir.json.

  • rpicam-apps does not provide explicit control of digital gain. Instead, the gain该选项会隐式设置它。

  • rpicam-apps removed the --ISO option. Instead, calculate the gain corresponding to the ISO value required. Vendors can provide mappings of gain to ISO.

  • rpicam-apps does not support setting a flicker period.

  • rpicam-still does not support burst capture. Instead, consider using rpicam-vid in MJPEG mode with --segment 1 to force each frame into a separate file.

  • rpicam-apps uses open source drivers for all image sensors, so the mechanism for enabling or disabling on-sensor Defective Pixel Correction (DPC) is different. The imx477 driver on the Raspberry Pi HQ Camera enables on-sensor DPC by default. To disable on-sensor DPC on the HQ Camera, run the following command:

    $ sudo echo 0 > /sys/module/imx477/parameters/dpc_enable

故障排除

如果您的 Camera Module 未按预期工作,请尝试以下一些修复方法:

  • 在 Raspberry Pi 3 及更早版本上,图形硬件最多只能支持 2048×2048 像素的图像,这限制了可缩放至预览窗口的相机图像。因此,对宽度超过 2048 像素的图像进行视频编码会产生损坏或缺失的预览图像。

  • 在 Raspberry Pi 4 上,图形硬件最多只能支持 4096×4096 像素的图像,这限制了可缩放至预览窗口的相机图像。因此,对宽度超过 4096 像素的图像进行视频编码会产生损坏或缺失的预览图像。

  • 在桌面环境中,预览窗口可能出现显示撕裂。这是一个已知且无法修复的问题。

  • 检查 FFC(Flat Flexible Cable)是否牢固就位、完全插入,并且触点朝向正确方向。FFC 应均匀插入,不得倾斜。

  • 如果您在相机与 Raspberry Pi 之间使用连接器,请检查连接器上的端口是否牢固就位、完全插入,并且触点朝向正确方向。

  • 检查以确保 FFC(Flat Flexible Cable)连接到 CSI(Camera Serial Interface),先拔下连接器的一端而不是 DSI(Display Serial Interface)。该连接器可插入任一端口,但只有 CSI 端口为相机供电并控制相机。请查找CSI label printed on the board near the port.

  • 更新到最新软件。

  • 尝试使用不同的电源。Camera Module 会使 Raspberry Pi 的电源需求增加约 200-250mA。如果电源质量较差,您的 Raspberry Pi 可能无法为 Camera Module 供电。

  • 如果您已检查上述所有问题,而 Camera Module 仍未按预期工作,请尝试在我们的论坛上发帖以获取更多帮助。

获取帮助

如需以下方面的进一步帮助:libcamera and the rpicam-apps, check the Raspberry Pi Camera 论坛。发帖前:

  • 记下您的操作系统版本(uname -a).

  • 记下您的libcamera and rpicam-apps versions (rpicam-hello --version).

  • 报告您正在使用的相机模块的品牌和型号。

  • 报告您尝试使用的软件。我们不支持第三方相机模块供应商的软件。

  • 报告你的 Raspberry Pi 型号,包括内存大小。

  • 包含应用程序控制台输出中的任何相关摘录。

如果相机软件中存在特定问题(例如崩溃),请考虑在rpicam-apps GitHub repository中创建一个 issue,并包含上面列出的相同详细信息。