Difference between revisions of "OV5647 Camera"
Yousimaier17 (talk | contribs) |
Yousimaier17 (talk | contribs) |
||
(20 intermediate revisions by the same user not shown) | |||
Line 17: | Line 17: | ||
OV5647 Camera (220) | OV5647 Camera (220) | ||
|categories= | |categories= | ||
− | {{Category| | + | {{Category|Raspberry Pi}} |
{{Category|Camera}} | {{Category|Camera}} | ||
|brand=Diustou | |brand=Diustou | ||
Line 43: | Line 43: | ||
== User Instructions == | == User Instructions == | ||
=== Driver Support === | === Driver Support === | ||
− | *[[File:Raspberry Pi Camera User Manual_驱动.png| | + | *[[File:Raspberry Pi Camera User Manual_驱动.png|600px]] |
=== Hardware Connection === | === Hardware Connection === | ||
Line 1,222: | Line 1,222: | ||
</pre> | </pre> | ||
:* Set the metering mode for the AEC/AGC algorithm. Available options are: | :* Set the metering mode for the AEC/AGC algorithm. Available options are: | ||
− | <pre> | + | <pre> |
centre - Center-weighted metering (default) | centre - Center-weighted metering (default) | ||
Spot - Spot metering | Spot - Spot metering | ||
Line 1,248: | Line 1,248: | ||
</pre> | </pre> | ||
:* Available white balance modes: | :* Available white balance modes: | ||
− | <pre> | + | <pre> |
Mode Color Temperature | Mode Color Temperature | ||
Auto 2500K ~ 8000K | Auto 2500K ~ 8000K | ||
Line 1,279: | Line 1,279: | ||
</pre> | </pre> | ||
:* Supported denoising modes: | :* Supported denoising modes: | ||
− | <pre> | + | <pre> |
auto - Default mode, uses standard spatial denoising. For video, it uses fast color denoising, and for still images, it uses high-quality color denoising. Preview images do not use any color denoising. | auto - Default mode, uses standard spatial denoising. For video, it uses fast color denoising, and for still images, it uses high-quality color denoising. Preview images do not use any color denoising. | ||
off - Disables both spatial and color denoising. | off - Disables both spatial and color denoising. | ||
Line 1,306: | Line 1,306: | ||
</pre> | </pre> | ||
:* Set the autofocus mode. The following modes are available: | :* Set the autofocus mode. The following modes are available: | ||
− | <pre> | + | <pre> |
default - By default, the camera will operate in continuous autofocus mode unless --lens-position or --autofocus-on-capture is set for manual focus methods. | default - By default, the camera will operate in continuous autofocus mode unless --lens-position or --autofocus-on-capture is set for manual focus methods. | ||
manual - Manual focus mode, where the focus position can be set via --lens-position. | manual - Manual focus mode, where the focus position can be set via --lens-position. | ||
Line 1,318: | Line 1,318: | ||
</pre> | </pre> | ||
:* Set the autofocus range with the following options: | :* Set the autofocus range with the following options: | ||
− | <pre> | + | <pre> |
normal - Default, from the closest to infinity. | normal - Default, from the closest to infinity. | ||
macro - Macro mode, focuses only on nearby objects. | macro - Macro mode, focuses only on nearby objects. | ||
Line 1,329: | Line 1,329: | ||
</pre> | </pre> | ||
:* Set the focus speed with the following options: | :* Set the focus speed with the following options: | ||
− | <pre> | + | <pre> |
normal - Default, normal speed. | normal - Default, normal speed. | ||
fast - Fast focus mode. | fast - Fast focus mode. | ||
Line 1,347: | Line 1,347: | ||
</pre> | </pre> | ||
:* Move the lens to a fixed focal distance, typically given in diopters (1/meter distance). For example: | :* Move the lens to a fixed focal distance, typically given in diopters (1/meter distance). For example: | ||
− | <pre> | + | <pre> |
− | 0.0 -- Set the focus position to infinity. | + | 0.0 -- Set the focus position to infinity. |
Any other number -- Set the focus position to 1/number, where number is any value you set. For example, if set to 2, it will focus at a 0.5m distance. | Any other number -- Set the focus position to 1/number, where number is any value you set. For example, if set to 2, it will focus at a 0.5m distance. | ||
− | default -- Focus to the default position relative to the lens's hyperfocal distance. | + | default -- Focus to the default position relative to the lens's hyperfocal distance. |
</pre> | </pre> | ||
:* Note that the lens can only be approximately calibrated, and there may be differences between different camera modules. | :* Note that the lens can only be approximately calibrated, and there may be differences between different camera modules. | ||
:* This option is only supported by certain camera modules (e.g., Raspberry Pi Camera Module 3 series). | :* This option is only supported by certain camera modules (e.g., Raspberry Pi Camera Module 3 series). | ||
− | ====== | + | ====== Output File Options ====== |
− | *''' | + | *'''Output File Name''' |
<pre> | <pre> | ||
--output -o | --output -o | ||
</pre> | </pre> | ||
− | :* | + | :*Set the filename for the output image or video. In addition to setting a filename, you can specify a UDP or TCP server address to stream the image to. For those interested, please refer to the subsequent sections on TCP and UDP settings for more details. |
− | :* | + | :*Example: |
<pre> | <pre> | ||
libcamera-vid -t 100000 --segment 10000 -o chunk%04d.h264 | libcamera-vid -t 100000 --segment 10000 -o chunk%04d.h264 | ||
</pre> | </pre> | ||
− | :: | + | ::Record a 100-second file, with each 10-second segment named chunk.h264, including an incrementing counter. Note that %04d writes the counter as a string, padded with leading zeros to a total width of at least 4 characters. |
<pre> | <pre> | ||
libcamera-vid -t 0 --inline -o udp://192.168.1.13:5000 | libcamera-vid -t 0 --inline -o udp://192.168.1.13:5000 | ||
</pre> | </pre> | ||
− | :: | + | ::Stream the H.264 video to the network address 192.168.1.13 on port 5000. |
− | *''' | + | *'''Output File Counter''' |
<pre> | <pre> | ||
--wrap <number> | --wrap <number> | ||
</pre> | </pre> | ||
− | :* | + | :*When outputting to files with an incrementing counter (such as %d in the output filename), reset the counter to zero when it reaches this value. |
− | :* | + | :*Example: |
<pre> | <pre> | ||
libcamera-vid -t 0 --codec mjpeg --segment 1 --wrap 100 -o image%d.jpg | libcamera-vid -t 0 --codec mjpeg --segment 1 --wrap 100 -o image%d.jpg | ||
</pre> | </pre> | ||
− | *''' | + | *'''Flush Output File Immediately''' |
<pre> | <pre> | ||
--flush | --flush | ||
</pre> | </pre> | ||
− | :*- | + | :*-flush writes each frame to the disk immediately, reducing latency, instead of waiting for the system to flush. |
− | :* | + | :*Example: |
<pre> | <pre> | ||
libcamera-vid -t 10000 --flush -o test.h264 | libcamera-vid -t 10000 --flush -o test.h264 | ||
</pre> | </pre> | ||
− | ====== | + | ====== Post-Processing ====== |
− | * | + | *The post-process-file option specifies a JSON file that configures the post-processing applied to the camera image by the imaging pipeline before it reaches the application. It can be regarded as an alternative to the traditional raspicam "image effects". |
− | * | + | *Post-processing is a broad topic that involves using third-party software such as OpenCV and TensorFlowLite to analyze and process images. For more information, please refer to the [https://www.raspberrypi.com/documentation/computers/camera_software.html#post-processing post-processing section]. |
− | : | + | :Example: |
<pre> | <pre> | ||
libcamera-hello --post-process-file negate.json | libcamera-hello --post-process-file negate.json | ||
</pre> | </pre> | ||
− | ===== | + | ===== Settings for Capturing Static Images ===== |
<pre> | <pre> | ||
− | -- | + | --quality, -q # Set JPEG image quality <0 - 100> |
− | --exif, -x # | + | --exif, -x # Add additional EXIF tags |
− | --timelapse | + | --timelapse # Set time interval for time-lapse photography, in ms |
− | --framestart # | + | --framestart # Set starting value for frame count |
− | --datetime | + | --datetime # Name output file with date format |
− | --timestamp # | + | --timestamp # Name output file with system timestamp |
− | -- restart | + | --restart # Set JPEG restart interval |
− | --keypress, -k | + | --keypress, -k # Set enter key to trigger photo capture |
− | --signal, -s | + | --signal, -s # Set signal to trigger photo capture |
− | --thumb # | + | --thumb # Set thumbnail parameters <w:h:q> |
− | -- | + | --encoding, -e # Set image encoding type: jpg / png / bmp / rgb / yuv420 |
− | --raw, -r | + | --raw, -r # Save raw image |
− | --latest # | + | --latest # Link symbol to the latest saved file |
− | --autofocus-on-capture | + | --autofocus-on-capture # Perform autofocus before capturing a photo |
− | </pre> | + | </pre> |
− | ===== | + | |
− | <pre> | + | ===== Settings for Video Recording ===== |
− | --quality, -q # | + | <pre> |
− | --bitrate, -b # | + | --quality, -q # Set JPEG quality <0 - 100> |
− | --intra, -g # | + | --bitrate, -b # Set H.264 bitrate |
− | --profile # | + | --intra, -g # Set intra-frame period (only supported for H.264) |
− | --level | + | --profile # Set H.264 profile --level # Set H.264 level |
− | --codec | + | --codec # Set encoding type: h264 / mjpeg / yuv420 |
− | --keypress, -k | + | --keypress, -k # Set enter key to pause and resume recording |
− | -- | + | --signal, -s # Set signal to pause and resume recording |
− | --initial # | + | --initial # Start the program in recording or paused state |
− | --split # | + | --split # Split video and save to a separate file |
− | --segment # | + | --segment # Split video into multiple segments |
− | --circular | + | --circular # Write video to a circular buffer |
− | --inline # | + | --inline # Write header in each I-frame (only supported for H.264) |
− | --listen # | + | --listen # Wait for TCP connection |
− | --frames # | + | --frames # Set the number of frames to record |
− | </pre> | + | </pre> |
− | ==== | + | ==== Buster System ==== |
− | ===== | + | ===== Taking Photos ===== |
− | + | To take a photo, simply execute the following command in the terminal: | |
<pre> | <pre> | ||
raspistill -o image.jpg | raspistill -o image.jpg | ||
</pre> | </pre> | ||
− | + | Here, image.jpg is the filename of the photo. | |
− | ===== | + | ===== Recording Video ===== |
+ | To record a video, execute the following command in the terminal: | ||
终端执行以下语句即可摄像: | 终端执行以下语句即可摄像: | ||
<pre> | <pre> | ||
raspivid -o video.h264 -t 10000 | raspivid -o video.h264 -t 10000 | ||
</pre> | </pre> | ||
− | + | Where -t 10000 indicates recording for 10 seconds. Users can adjust this according to their needs. | |
− | === | + | === References === |
− | + | [http://www.raspberrypi.org/camera Raspberry Pi Camera Tutorial] | |
− | == Python | + | == Controlling the Camera with Python == |
− | * | + | *The picamera library can be used to enable Python support for camera control. |
− | * | + | *Starting from the Bullseye version of the Raspberry Pi image, the underlying camera driver has switched from Raspicam to libcamera. libcamera is an open-source software stack (hereinafter referred to as the driver for simplicity) that facilitates third-party porting and development of their own camera drivers. Currently, libcamera does not support Python, so the Raspberry Pi official website still provides installation and download methods for Raspicam. For users who find it difficult to switch to libcamera but need to use the latest system, please proceed directly to the instructions for using Raspicam. |
− | === | + | === Preview === |
− | * | + | *Open a Python IDE, such as Thonny Python IDE, or open a text editor. |
[[File:thonny-app-menu.png|400px]] | [[File:thonny-app-menu.png|400px]] | ||
− | * | + | *Create a new Python file named camera.py and save it to the desktop. |
− | * | + | *Enter the following code: |
<source lang="python"> | <source lang="python"> | ||
from picamera import PiCamera | from picamera import PiCamera | ||
Line 1,471: | Line 1,472: | ||
camera.stop_preview() | camera.stop_preview() | ||
</source> | </source> | ||
− | * | + | |
− | <source lang="python"> | + | *In the terminal, execute: |
+ | <source lang="python"> | ||
python3 Desktop/camera.py | python3 Desktop/camera.py | ||
</source> | </source> | ||
− | + | A preview window will pop up on the desktop, providing a live view. | |
<source lang="python"> | <source lang="python"> | ||
− | + | Note that the preview window is only effective when connected directly to a screen. It will not pop up if you are remotely connected to the Raspberry Pi desktop using software like VNC. | |
</source> | </source> | ||
− | + | If the preview image is upside down, you can rotate it 180 degrees with the following code: | |
<source lang="python"> | <source lang="python"> | ||
camera = PiCamera() | camera = PiCamera() | ||
camera.rotation = 180 | camera.rotation = 180 | ||
</source> | </source> | ||
− | |||
− | |||
− | ==== | + | *The preview image can be rotated 90, 180, or 270 degrees. |
+ | *To reset the image, set the rotation to 0 degrees. | ||
+ | |||
+ | ==== Setting Preview Window Transparency ==== | ||
<source lang="python"> | <source lang="python"> | ||
camera.start_preview(alpha=100) | camera.start_preview(alpha=100) | ||
</source> | </source> | ||
− | + | The alpha value ranges from 0-255. | |
− | === | + | === Taking Photos === |
− | * | + | *Insert the camera.capture() command in the middle of the preview code: |
<source lang="python"> | <source lang="python"> | ||
camera.start_preview() | camera.start_preview() | ||
Line 1,501: | Line 1,504: | ||
camera.stop_preview() | camera.stop_preview() | ||
</source> | </source> | ||
− | + | Please note: The sleep(5) code must be executed to allow the camera sensor time to adjust brightness and white balance. | |
− | === | + | === Recording Video === |
− | + | Remove camera.capture() and add camera.start_recording() and camera.stop_recording(): | |
<source lang="python"> | <source lang="python"> | ||
camera.start_preview() | camera.start_preview() | ||
Line 1,512: | Line 1,515: | ||
camera.stop_preview() | camera.stop_preview() | ||
</source> | </source> | ||
− | + | After executing the above code, a video.h264 video will be generated on the desktop, with a length of 5 seconds. | |
− | === | + | === More Parameters === |
− | * | + | *The picamera library allows for many parameters to be added to images. |
− | ==== | + | ==== Setting Resolution ==== |
− | * | + | *By default, the image resolution matches the display resolution, but the maximum image size does not exceed 2592x1944 pixels, and the video size does not exceed 1920x1080 pixels; the minimum size for both images and videos is 64x64 pixels. |
− | * | + | *The following code can be used to set the image resolution: |
<source lang="python"> | <source lang="python"> | ||
camera.resolution = (2592, 1944) | camera.resolution = (2592, 1944) | ||
Line 1,528: | Line 1,531: | ||
camera.stop_preview() | camera.stop_preview() | ||
</source> | </source> | ||
− | * | + | *Please note that the camera's frame rate should be set to ≤15 frames per second to support the maximum resolution. |
− | ==== | + | ==== Adding Text to Images ==== |
− | ''' | + | '''Adding Text''' |
<source lang="python"> | <source lang="python"> | ||
camera.start_preview() | camera.start_preview() | ||
Line 1,539: | Line 1,542: | ||
camera.stop_preview() | camera.stop_preview() | ||
</source> | </source> | ||
− | ''' | + | |
+ | '''Text Size''' | ||
<source lang="python"> | <source lang="python"> | ||
camera.annotate_text_size = 50 | camera.annotate_text_size = 50 | ||
</source> | </source> | ||
− | + | annotate_text_size ranges from 6-160, default is 32 | |
− | ''' | + | '''Text Color''' |
<source lang="python"> | <source lang="python"> | ||
camera.start_preview() | camera.start_preview() | ||
Line 1,554: | Line 1,558: | ||
camera.stop_preview() | camera.stop_preview() | ||
</source> | </source> | ||
− | ''' | + | |
− | * | + | '''Modifying Image Parameters''' |
+ | * Brightness | ||
<source lang="python"> | <source lang="python"> | ||
camera.start_preview() | camera.start_preview() | ||
Line 1,563: | Line 1,568: | ||
camera.stop_preview() | camera.stop_preview() | ||
</source> | </source> | ||
− | + | brightness ranges from 0-100, default is 50 | |
− | * | + | |
+ | * Contrast | ||
<source lang="python"> | <source lang="python"> | ||
− | + | camera.contrast = 50 | |
</source> | </source> | ||
− | + | contrast ranges from 0-100, default is 50 | |
− | |||
− | |||
− | + | * Image Effect | |
− | * none( | + | Use camera.image_effect to add special effects to the image |
+ | |||
+ | Valid values: | ||
+ | * none (default) | ||
* negative | * negative | ||
* solarize | * solarize | ||
Line 1,596: | Line 1,603: | ||
* deinterlace2 | * deinterlace2 | ||
− | + | For example | |
<source lang="python"> | <source lang="python"> | ||
camera.start_preview() | camera.start_preview() | ||
Line 1,605: | Line 1,612: | ||
</source> | </source> | ||
− | * | + | * Mode |
− | + | Use camera.exposure_mode to set the photography mode (such as night, sports, snow, etc.) | |
− | + | Valid values: | |
* off | * off | ||
− | * auto( | + | * auto (default) |
* night | * night | ||
* nightpreview | * nightpreview | ||
Line 1,623: | Line 1,630: | ||
* fireworks | * fireworks | ||
− | + | For example | |
<source lang="python"> | <source lang="python"> | ||
camera.start_preview() | camera.start_preview() | ||
Line 1,631: | Line 1,638: | ||
camera.stop_preview() | camera.stop_preview() | ||
</source> | </source> | ||
− | |||
− | |||
− | + | * White Balance | |
+ | Use camera.awb_mode to set the white balance | ||
+ | |||
+ | Valid values: | ||
* off | * off | ||
− | * auto( | + | * auto (default) |
* sunlight | * sunlight | ||
* cloudy | * cloudy | ||
Line 1,646: | Line 1,654: | ||
* horizon | * horizon | ||
− | + | For example, setting the white balance to "sunlight" | |
<source lang="python"> | <source lang="python"> | ||
camera.start_preview() | camera.start_preview() |
Latest revision as of 11:00, 24 January 2025
| ||||||||||||||||||||||
| ||||||||||||||||||||||
|
Contents
- 1 Product Parameters
- 2 User Instructions
- 2.1 Driver Support
- 2.2 Hardware Connection
- 2.3 Test Camera
- 2.4 Accessing the Camera
- 2.5 References
- 3 Controlling the Camera with Python
Product Parameters
- Pixel: 5 Megapixels
- Image Sensor: OV5647
- Static Image Resolution: 2592 x 1944
- Supports 1080p30, 720p60, and 640x480p60/90 Video Recording
- CMOS Size: 1/4 Inch
- Field of View (FOV): 77°/120°/160°/220°
- Focal Length:
- OV5647 Camera (77): 2.85mm ±5%
- OV5647 Camera (120): 1.79mm ±5%
- OV5647 Camera (160): 1.05mm ±5%
- OV5647 Camera (220): 2.16mm ±5% (Manually Adjustable Focus)
- Infrared Function: Without Infrared, With Infrared
User Instructions
Driver Support
Hardware Connection
Insert the camera's ribbon cable into the slot between the Ethernet port and the HDMI port, with the silver shiny side facing the HDMI port. You need to open the latch of the Raspberry Pi's on-board ribbon cable slot before inserting the cable. The ribbon cable should be inserted tightly into the slot, and care should be taken to avoid bending it. After inserting the ribbon cable, make sure to close the latch of the slot again.
Test Camera
Bullseye System
- Raspberry Pi 5 requires the latest version of Raspberry Pi OS Bookworm.
Note: For the latest Bullseye image, the camera interface is already enabled by default, so there is no need to configure it using raapi-config.
- Open the command line terminal and execute the following commands to get system updates:
sudo apt-get update sudo apt-get upgrade
- Enter the command to preview the camera feed:
sudo libcamera-hello -t 0
- To close the preview window, you can click the 'x' to close it. Alternatively, you can return to the terminal interface and use ctrl-c to terminate the program.
- If you want to capture an image, you can execute the command:
libcamera-jpeg -o test.jpg
Note: If using Camera module 3, autofocus functionality will be enabled.
Buster System
- Open the command line terminal and execute the following commands to get system updates:
sudo apt-get update sudo apt-get upgrade
- Configure the camera using raspi-config. Execute:
sudo raspi-config
- Navigate to: Interfacing Options --> Camera --> Would you like the camera interface to be enabled? Select <Yes>
- Reboot the system: When prompted "Would you like to reboot now?", select Yes
- Alternatively, you can reboot by executing the command:
sudo reboot
- After configuring and connecting the camera, you can use the photo and video functions by powering on the Raspberry Pi.
- Open the Raspberry Pi terminal and start the camera preview:
sudo raspistill -t 0
- To close the preview window, you can terminate the program using ctrl-c.
Checking the Camera
- After installing the camera, you can use the following command to check if there are any issues with the camera and if the development board detects the camera and the number of cameras:
ls /dev/video*
- You can use v4l2-utils to further check the number and specifications of the cameras.
'''Check for comprehensive camera information''' v4l2-ctl --list-devices When multiple cameras are connected, you can use this command to determine the corresponding camera numbers. '''Check the camera's specification parameters''' v4l2-ctl --device=/dev/video0 --list-formats-ext You can change video0 to the camera you want to query.
Accessing the Camera
- To check the version of your system, please execute sudo cat /etc/os-release and look for information related to the following two images, then choose accordingly.
- Raspberry Pi OS Bookworm has changed the camera capture applications from libcamera-* to rpicam-*. Currently, users are allowed to continue using the old libcamera, but libcamera will be deprecated in the future, so please transition to using rpicam as soon as possible.
- If you are using the Raspberry Pi OS Bullseye system, please scroll down to use the #libcamera software stack tutorial in this guide.
Rpicam
- When running the latest version of Raspberry Pi OS, rpicam-apps comes with five basic functions already installed. In this case, the official Raspberry Pi camera will also be detected and automatically enabled.
- You can check if everything is working properly by entering:
rpicam-hello 0
- You will see a camera preview window for about five seconds.
- Note: If you are running on a Raspberry Pi 3 or earlier device with Bullseye, you may need to re-enable Glamor for the X Windows hardware-accelerated preview window to work properly. In the terminal window, enter sudo raspi-config, then select Advanced Options, Glamor, and Yes. Exit and restart your Raspberry Pi. By default, Raspberry Pi 3 and earlier devices running Bullseye may not be using the correct display driver. Please refer to the /boot/firmware/config.txt file and ensure that dtoverlay=vc4-fkms-v3d or dtoverlay=vc4-kms-v3d is currently active. If you need to change this setting, please restart.
rpicam-hello
- This command is used to preview the camera and display the camera feed on the screen.
- Example:
- To preview the camera in real-time, execute the following command in the terminal
rpicam-hello -t 0
- Where -t 0 indicates continuous preview until the program is terminated, and users can adjust it according to their needs.
- Tuning Files:
- Libcamera on Raspberry Pi has tuning files for each different type of camera module. The parameters in these files are passed to the algorithms and hardware to produce the best quality images. Libcamera can only automatically determine the image sensor being used, not the entire module, even though the entire module affects the "tuning". Therefore, it is sometimes necessary to override the default tuning file for a specific sensor.
- For example, the NoIR (No Infra-Red filter) version of the sensor requires different AWB (Auto White Balance) settings compared to the standard version, so the IMX219 NoIR used with a Pi 4 or earlier device should be run as follows:
rpicam-hello --tuning-file /usr/share/libcamera/ipa/rpi/vc4/imx219_noir.json
- The Raspberry Pi 5 uses different tuning files in a different folder, so here you would use:
rpicam-hello --tuning-file /usr/share/libcamera/ipa/rpi/pisp/imx219_noir.json
- This also means that users can copy existing tuning files and make changes according to their preferences, as long as the --tuning-file parameter points to the new version.
- The --tuning-file parameter, like other command-line options, is applicable to all rpicam-apps.
rpicam-jpeg
- This command is a simple program for capturing static images. To capture a full-resolution JPEG image, use the following command, which will display a preview for about five seconds and then capture a full-resolution JPEG image to the file test.jpg.
- Example:
- Executing the following command in the terminal will display a preview for about 5 seconds and then take a full-pixel JPEG image:
rpicam-jpeg -o test.jpg
- Where test.jpg represents the filename.
- The -t <duration> option can be used to change the length of the preview display, and the --width and --height options will change the resolution of the captured static image.
rpicam-jpeg -o test.jpg -t 2000 --width 640 --height 480
Exposure Control:
- All of these rpicam-apps allow users to run the camera with a fixed shutter speed and gain. To capture an image with an exposure time of 20ms and a gain of 1.5x, the gain will be used as analog gain within the sensor until it reaches the maximum analog gain allowed by the kernel sensor driver, after which the remainder will be used as digital gain.
rpicam-jpeg -o test.jpg -t 2000 --shutter 20000 --gain 1.5
- Where --shutter 20000 represents an exposure of 20ms, and --gain 1.5 means the camera gain is set to 1.5x.
- The AEC/AGC algorithm on Raspberry Pi allows applications to specify exposure compensation: it can make the image darker or brighter by a given number of stops.
rpicam-jpeg --ev -0.5 -o darker.jpg rpicam-jpeg --ev 0 -o normal.jpg rpicam-jpeg --ev 0.5 -o brighter.jpg
- Digital Gain:
- Digital gain is applied by the ISP, not by the sensor. The digital gain will always be very close to 1.0 unless:
- The total requested gain (via the --gain option or through the exposure profile in camera adjustments) exceeds the gain that can be used as analog gain within the sensor. Only the additional gain needed will be used as digital gain.
- One of the color gains is less than 1 (please note that color gains are also used as digital gains). In this case, the reported digital gain will stabilize at 1 / the minimum (of red gain, blue gain). This means that a unit digital gain is applied to one of the color channels (other than the green channel).
- AEC/AGC is changing. When AEC/AGC moves, there is usually some degree of change in digital gain to try to eliminate any fluctuations, but it quickly returns to normal.
rpicam-still
- rpicam-still and rpicam-jpeg are very similar, mimicking many of the functions of the original raspistill application.
- Example: To take a photo, execute the following command in the terminal:
rpicam-still -o test.jpg
- Where test.jpg represents the filename.
- Encoder:
- rpicam-still allows files to be saved in multiple different formats. It supports png and bmp encoding. It also allows files to be saved as binary dumps of RGB or YUV pixels, without encoding or file format. In the latter case, the application reading the file must understand its own pixel arrangement.
rpicam-still -e png -o test.png rpicam-still -e bmp -o test.bmp rpicam-still -e rgb -o test.data rpicam-still -e yuv420 -o test.data
- Note that the format in which the image is saved depends on the -e (equivalent to --encoding) option and is not automatically selected based on the output filename.
- Raw Image Capture
- A raw image is the image produced directly by the image sensor before any processing by the ISP (Image Signal Processor) or any CPU cores. For color image sensors, these are typically Bayer format images. Please note that raw images are quite different from the processed but unencoded RGB or YUV images we saw earlier.
- To capture a raw image:
rpicam-still --raw --output test.jpg
- Here, the -r option (also --raw) indicates capturing both the raw image and a JPEG. In practice, the raw image is the raw image from which the JPEG is generated. The raw image is saved in DNG (Adobe Digital Negative) format and is compatible with many standard applications (such as draw or RawTherapee). The raw image is saved to a file with the same name but with a .dng extension, hence test.dng.
- These DNG files contain metadata related to the image capture, including black level, white balance information, and the color matrix used by the ISP to generate the JPEG. This makes these DNG files more convenient for "manual" raw conversion using some of the tools mentioned above at a later time. Use exiftool to display all the metadata encoded into the DNG file:
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
- We note that there is only one calibration illuminant (the illuminant determined by the AWB algorithm, although it is always labeled as "D65"), and dividing the ISO number by 100 gives the analog gain being used.
- Long Exposure
- To capture images with long exposures, disable AEC/AGC and AWB, as these algorithms will force the user to wait for many frames while they converge.
- The way to disable them is by providing explicit values. Additionally, the --immediate option can be used to skip the entire preview phase of the capture. Therefore, to perform a 100-second exposure capture, use:
rpicam-still -o long_exposure.jpg --shutter 100000000 --gain 1 --awbgains 1,1 --immediate
- For reference, the maximum exposure times for the three official Raspberry Pi cameras can be found in this table.
rpicam-vid
- rpicam-vid helps us capture video on Raspberry Pi devices. Rpicam-vid displays a preview window and writes the encoded bitstream to the specified output. This produces an unpacked video bitstream that is not packaged in any type of container (such as an mp4 file) format.
- Rpicam-vid uses H.264 encoding.
- For example, the following command writes a 10-second video to a file named test.h264:
rpicam-vid -t 10s -o test.h264
- Where -t 10s indicates recording a 10-second video, and test.h264 is the filename.
- You can play the resulting file using VLC and other video players:
VLC test.h264
- On the Raspberry Pi 5, you can output directly to the MP4 container format by specifying the MP4 file extension for the output file:
rpicam-vid -t 10s -o test.mp4
- Encoder
- Rpicam-vid supports Motion JPEG as well as uncompressed and unformatted YUV420:
rpicam-vid -t 10000 --codec mjpeg -o test.mjpeg rpicam-vid -t 10000 --codec yuv420 -o test.data
- --The --codec option sets the output format, not the file extension of the output file.
- The --segment option splits the output file into chunks of a specified size (in milliseconds). By specifying very short (1 millisecond) segments, this can conveniently decompose a Motion JPEG stream into individual JPEG files. For example, the following command combines 1-millisecond segments with a counter in the output filename, generating a new filename for each segment:
rpicam-vid -t 10000 --codec mjpeg --segment 1 -o test%05d.jpeg
- Capturing High Frame Rate Video
- To minimize frame loss for high frame rate (> 60fps) video, try the following configuration adjustments:
- Set the H.264 target level to 4.2 using the --level 4.2 parameter.
- Disable software color denoising by setting the denoise option to cdn_off.
- Disable the display window with the nopreview option to free up some additional CPU cycles.
- Set force_turbo=1 in /boot/firmware/config.txt to ensure that the CPU clock does not throttle during video capture. For more information, refer to the force_turbo documentation.
- Adjust the ISP output resolution parameters to --width 1280 --height 720 or lower to achieve the frame rate target.
- On the Raspberry Pi 4, you can overclock the GPU to improve performance by adding gpu_freq=550 or a higher frequency in /boot/firmware/config.txt. For details, refer to the overclocking documentation.
- The following command demonstrates how to achieve 1280×720 120fps video:
- To minimize frame loss for high frame rate (> 60fps) video, try the following configuration adjustments:
rpicam-vid --level 4.2 --framerate 120 --width 1280 --height 720 --save-pts timestamp.pts -o video.264 -t 10000 --denoise cdn_off -n
- Integration of Libav with picam-vid
- Rpicam-vid can encode audio and video streams using the ffmpeg/libav codec backend. You can save these streams to files or stream them over a network.
- To enable the libav backend, pass libav to the codec option:
rpicam-vid --codec libav --libav-format avi --libav-audio --output example.avi
- UDP
- To stream video over UDP using the Raspberry Pi as a server, use the following command, replacing the <IP-addr> placeholder with the IP address of the client or multicast address, and the <port> placeholder with the port you want to use for streaming:
rpicam-vid -t 0 --inline -o udp://<ip-addr>:<port>
- To view the video stream over UDP using the Raspberry Pi as a client, use the following command, replacing the <port> placeholder with the port you want to stream on:
vlc udp://@:<port> :demux=h264
- Alternatively, use the following command on the client to stream using ffplay:
ffplay udp://<ip-addr-of-server>:<port> -fflags nobuffer -flags low_delay -framedrop
- TCP
- Video can also be transmitted over TCP. Use the Raspberry Pi as a server:
rpicam-vid -t 0 --inline --listen -o tcp://0.0.0.0:<port>
- To view the video stream over TCP using the Raspberry Pi as a client, use the following command:
vlc tcp/h264://<ip-addr-of-server>:<port>
- Alternatively, use the following command on the client to stream using ffplay at 30 frames per second:
ffplay tcp://<ip-addr-of-server>:<port> -vf "setpts=N/30" -fflags nobuffer -flags low_delay -framedrop
- RTSP
- To stream video over RTSP using VLC with the Raspberry Pi as a server, use the following command:
rpicam-vid -t 0 --inline -o - | cvlc stream:///dev/stdin --sout '#rtp{sdp=rtsp://:8554/stream1}' :demux=h264
- To view the video stream over RTSP using the Raspberry Pi as a client, use the following command:
ffplay rtsp://<ip-addr-of-server>:8554/stream1 -vf "setpts=N/30" -fflags nobuffer -flags low_delay -framedrop
- Or use the following command on the client to stream using VLC:
vlc rtsp://<ip-addr-of-server>:8554/stream1
- If you need to close the preview window on the server, use the nopreview command.
- Use the inline flag to force stream header information into each inline frame, which helps clients understand the stream if they miss the beginning.
rpicam-raw
- rpicam-raw records video directly from the sensor as raw Bayer frames. It does not display a preview window. To record a two-second raw clip into a file named test.raw, execute the following command:
- To record a 2-second raw data clip, run the following command in the terminal:
rpicam-raw -t 2000 -o test.raw
- Rpicam-raw outputs raw frames without any format information. The application prints the pixel format and image dimensions to the terminal window to assist users in parsing the pixel data.
- By default, rpicam-raw outputs raw frames in a single, potentially very large file. Use the segment option to direct each raw frame to a separate file, using the %05d directive to make
rpicam-raw -t 2000 --segment 1 -o test%05d.raw
- With fast storage devices, rpicam-raw can write 18MB, 12MP HQ camera frames to disk at 10fps. Rpicam-raw cannot format output frames as DNG files; to achieve this, use rpicam-still with a framerate option below 10 to avoid dropped frames:
rpicam-raw -t 5000 --width 4056 --height 3040 -o test.raw --framerate 8
- For more information on the raw format, please refer to the mode documentation.
rpicam-detect
- Note: rpicam-detect is not included in the Raspberry Pi OS. If you have installed TensorFlow Lite, you can build rpicam-detect. For more information, see the rpicam-apps build instructions. Don't forget to pass -DENABLE_TFLITE=1 when running cmake.
- rpicam-detect displays a preview window and uses the Google MobileNet v1 SSD (Single Shot Detector) neural network, trained to recognize approximately 80 classes of objects using the Coco dataset. Rpicam-detect can identify people, cars, cats, and many other objects.
- Whenever rpicam-detect detects a target object, it captures a full-resolution JPEG. It then returns to monitoring preview mode.
- For general information on using the model, please refer to the TensorFlow Lite Object Detector section. For example, you can monitor your cat while you're away:
rpicam-detect -t 0 -o cat%04d.jpg --lores-width 400 --lores-height 300 --post-process-file object_detect_tf.json --object cat
rpicam Parameter Settings
- Print program help information, which lists the available setting options for each program command, and then exit.
rpicam-hello -h
- --version outputs the version strings for libcamera and rpicam-apps
rpicam-hello --version
- Example output:
rpicam-apps build: ca559f46a97a 27-09-2021 (14:10:24) libcamera build: v0.0.0+3058-c29143f7
- --list-cameras lists the cameras connected to the Raspberry Pi and their available sensor modes
rpicam-hello --list-cameras
- Sensor mode identifiers have the following format:
S<Bayer order><Bit-depth>_<Optional packing> : <Resolution list>
- Cropping is specified in native sensor pixels (even in pixel binning modes) as (<x>, <y>)/<Width>×<Height>. (x, y) specifies the position of the cropping window of size width × height within the sensor array.
- For example, the following output shows information for an IMX219 sensor with index 0 and an IMX477 sensor with 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]
- --camera Select the camera to use. Specify an index from the list of available cameras.
rpicam-hello --list-cameras 0 rpicam-hello --list-cameras 1
- --config -c, Specify a file containing command parameters and values. Typically named example_configuration.txt, with options and values specified as key-value pairs, one per line.
timeout=99000 verbose=
- Note: Omit the -- prefix usually used for parameters in the command line. For flags without values, such as verbose in the example above, a trailing = must be included.
- Then you can run the following command to specify a timeout of 99000 milliseconds and verbose output:
rpicam-hello --config example_configuration.txt
- --time -t, Default delay of 5000 milliseconds.
rpicam-hello -t
- Specify how long the application runs before shutting down. This applies to video recording and preview windows. When capturing still images, the application displays a preview window for the timeout milliseconds before capturing the output image.
rpicam-hello -t 0
- --preview Set the position (x, y coordinates) and size (w, h dimensions) of the desktop or DRM preview window. Does not affect the resolution or aspect ratio of the image requested from the camera.
- Pass the preview window dimensions in the following comma-separated format: x,y,w,h
rpicam-hello --preview 100,100,500,500
- --fullscreen -f, Forces the preview window to use the entire screen with no borders or title bar. Scales the image to fit the entire screen. Does not accept a value.
rpicam-hello -f
- --qt-preview Uses a Qt preview window, which consumes more resources than other options but supports X window forwarding. Incompatible with the fullscreen flag. Does not accept a value.
rpicam-hello --qt-preview
- --nopreview Prevents the application from displaying a preview window. Does not accept a value.
rpicam-hello --nopreview
- --info-text
- Default: "#%frame (%fps fps) exp %exp ag %ag dg %dg"
- When running in a desktop environment, sets the provided string as the title of the preview window. Supports the following image metadata substitutions:
Command Description %frame Frame sequence number %fps Instantaneous frame rate %exp Shutter speed when the image was captured, in ms %ag Image analog gain controlled by the sensor chip %dg Image digital gain controlled by the ISP %rg Gain for the red component of each pixel %bg Gain for the blue component of each pixel %focus Focus measure of the image, with higher values indicating sharper images %lp Current lens diopter (distance in 1/meters) %afstate Auto-focus status (idle, scanning, focused, failed)
rpicam-hello --info-test "Focus measure: %focus"
- --width
- --height
- Each accepts a single number to define the dimensions (in pixels) of the captured image.
- For rpicam-still, rpicam-jpeg, and rpicam-vid, specifies the output resolution.
- For rpicam-raw, specifies the raw frame resolution. For cameras with a 2×2 bin readout mode, specify a resolution equal to or less than the bin mode to capture 2×2 bin raw frames.
- Has no effect with rpicam-hello.
- Record 1080p video
rpicam-vid -o test.h264 --width 1920 --height 1080
- Capture a JPEG at 2028×1520 resolution. If used with an HQ camera, uses 2×2 bin mode, so the raw file (test.ng) contains a 2028×1520 raw Bayer image.
rpicam-still -r -o test.jpg --width 2028 --height 1520
- --viewfinder-width
- --viewfinder-height
- Each accepts a number to define the dimensions (in pixels) of the image displayed in the preview window. Does not affect the size of the preview window, as the image is resized to fit. Does not affect captured still images or videos.
rpicam-still --viewfinder-width 1920 --viewfinder-height 1080
- --mode Allows specifying the camera mode in the following colon-separated format: <width>:<height>:<bit-depth>:<packing>. If the provided values do not match exactly, the system selects the closest available option for the sensor. Use packed (P) or unpacked (U) formats, which affect the format of stored video and still images but not the format of frames passed to the preview window.
- Bit-depth and packing are optional, with a default bit-depth of 12 and packing of P (packed). For information on bit depths, resolutions, and packing options available for your sensor, see list-cameras. Examples:
- 4056:3040:12:P - 4056×3040 resolution, 12 bits/pixel, packed.
- 1632:1224:10 - 1632×1224 resolution, 10 bits/pixel.
- 2592:1944:10:U - 2592×1944 resolution, 10 bits/pixel, unpacked.
- 3264:2448 - 3264×2448 resolution.
- --viewfinder-mode Same as the mode option but applies to the data passed to the preview window. For more information, see the mode documentation.
- --lores-width and --lores-height
- Provide a second, low-resolution image stream from the camera, scaled down to the specified dimensions. Each accepts a number to define the dimensions (in pixels) of the low-resolution stream. Available for preview and video modes. Not provided for still captures. For rpicam-vid, disables additional color denoising processing. Useful for image analysis in conjunction with image post-processing.
rpicam-hello --lores-width 224 --lores-height 224
- --hflip Horizontally flips the image. Does not accept a value.
rpicam-hello --hflip -t 0
- --vflip Vertically flips the image. Does not accept a value.
rpicam-hello --vflip -t 0
- --rotation Rotates the image extracted from the sensor. Only accepts values 0 or 180.
rpicam-hello --rotation 0
- --roi Crops the image extracted from the full sensor domain. Accepts four decimal values ranging from 0 to 1 in the following format: <x>,<y>,<w>,<h>. Each of these values represents a percentage of the available width and height as a decimal between 0 and 1.
- These values define the following proportions:
<x>: X coordinate to skip before extracting the image <y>: Y coordinate to skip before extracting the image <w>: Width of the image to extract <h>: Height of the image to extract
- Default is 0,0,1,1 (start from the first X coordinate and the first Y coordinate, use 100% of the image width, and use 100% of the image height).
- Examples:
- rpicam-hello --roi 0.25,0.25,0.5,0.5 selects half of the total pixels cropped from the center of the image (skip the first 25% of the X coordinates, skip the first 25% of the Y coordinates, use 50% of the total image width, and use 50% of the total image height).
- rpicam-hello --roi 0,0,0.25,0.25 selects one-quarter of the total pixels cropped from the top-left corner of the image (skip 0% of the X coordinates, skip 0% of the Y coordinates, use 25% of the image width, and use 25% of the image height).
- --rotation Rotate the image extracted from the sensor. Only values 0 or 180 are accepted.
- off - Disable HDR.
- auto - Enable HDR on supported devices. Use the sensor's built-in HDR mode if available. If the sensor does not have a built-in HDR mode, use the on-board HDR mode (if available).
- single-exp Enable HDR on supported devices. Use the sensor's built-in HDR mode if available. If the sensor does not have a built-in HDR mode, use the on-board HDR mode (if available).
rpicam-hello --hdr
- Use the on-board HDR mode if available, even if the sensor has a built-in HDR mode. If the on-board HDR mode is not available, disable HDR.
- Raspberry Pi 5 and later devices have an on-board HDR mode.
- To check for built-in HDR mode in the sensor, add this option to list the cameras.
rpicam-hello --rotation 0
Camera Control Options
- The following options control the image processing and algorithms that affect the camera's image quality.
- Sharpness
- Sets the image sharpness. Accepts values within the following range:
- 0.0 applies no sharpening
- Values greater than 0.0 but less than 1.0 apply less sharpening than the default
- 1.0 applies the default amount of sharpening
- Values greater than 1.0 apply additional sharpening
- Sets the image sharpness. Accepts values within the following range:
rpicam-hello --sharpness 0.0
- Contrast
- Specifies the image contrast. Accepts values within the following range:
- 0.0 applies minimum contrast
- Values greater than 0.0 but less than 1.0 apply less contrast than the default
- 1.0 applies the default contrast
- Values greater than 1.0 apply additional contrast
- Specifies the image contrast. Accepts values within the following range:
rpicam-hello --contrast 0.0
- Brightness
- Specifies the image brightness, added as an offset to all pixels in the output image. Accepts values within the following range:
- -1.0 for minimum brightness (black)
- 0.0 applies standard brightness
- 1.0 applies maximum brightness (white)
- For more usage, refer to ev.
- Specifies the image brightness, added as an offset to all pixels in the output image. Accepts values within the following range:
rpicam-hello --brightness 1.0
- Saturation
- Specifies the image color saturation. Accepts values within the following range:
- 0.0 applies minimum saturation (grayscale)
- Values greater than 0.0 but less than 1.0 apply less saturation than the default
- 1.0 applies the default saturation
- Values greater than 1.0 apply additional saturation
- Specifies the image color saturation. Accepts values within the following range:
rpicam-hello --saturation 0.6
- EV
- Specifies the Exposure Value (EV) compensation for the image. Accepts a numerical value that controls the target value passed to the auto-exposure/gain control (AEC/AGC) processing algorithm along the following spectrum:
- -10.0 applies the minimum target value
- 0.0 applies the standard target value
- 10.0 applies the maximum target value
- Specifies the Exposure Value (EV) compensation for the image. Accepts a numerical value that controls the target value passed to the auto-exposure/gain control (AEC/AGC) processing algorithm along the following spectrum:
rpicam-hello --ev 10.0
- Shutter
- Specifies the exposure time using the shutter, in microseconds. When you use this option, the gain can still vary. If the camera operates at a frame rate that is too fast to allow the specified exposure time (e.g., 1 fps with an exposure time of 10000 microseconds), the sensor will use the maximum exposure time allowed by the frame rate.
- For a list of minimum and maximum shutter times for the official camera, please refer to the camera hardware documentation. Values higher than the maximum may result in undefined behavior.
rpicam-hello --shutter 10000
- Gain
- analoggain has the same effect as gain
- Sets the combined analog and digital gain. Only analog gain is used when the sensor driver can provide the required gain. When the analog gain reaches its maximum, the ISP applies digital gain. Accepts numerical values.
- For a list of analog gain limits for the official camera, please refer to the camera hardware documentation.
- Sometimes, the digital gain may exceed 1.0 even when the analog gain limit is not exceeded. This can occur in the following situations:
- When any of the color gains are below 1.0, which results in the digital gain stabilizing at 1.0/min(red gain, blue gain). This applies the total digital gain to any color channel above 1.0 to avoid color shift artifacts.
- Slight differences when auto-exposure/gain control (AEC/AGC) changes.
rpicam-hello --gain 0.8
- Metering (Default: centre)
- Sets the metering mode for the auto-exposure/gain control (AEC/AGC) algorithm. Accepts the following values:
- centre for center-weighted metering
- spot for spot metering
- average for average or full-frame metering
- custom for a custom metering mode defined in the camera tuning file
- For more information on defining custom metering modes and adjusting zone weights in existing metering modes, please refer to the Tuning Guide for Raspberry Pi Camera and libcamera.
- Sets the metering mode for the auto-exposure/gain control (AEC/AGC) algorithm. Accepts the following values:
rpicam-hello --metering centre
- Exposure
- Sets the exposure profile. Changing the exposure profile should not affect the image exposure. Instead, different modes adjust the gain settings to achieve the same net result. Accepts the following values:
- sport: short exposure time, high gain
- normal: normal exposure, normal gain
- long: long exposure time, low gain
- You can edit the exposure profiles using a tuning file. For more information, please refer to the Tuning Guide for Raspberry Pi Camera and libcamera.
- Sets the exposure profile. Changing the exposure profile should not affect the image exposure. Instead, different modes adjust the gain settings to achieve the same net result. Accepts the following values:
rpicam-hello --exposure sport
- AWB
- Sets the exposure profile. Changing the exposure profile should not affect the image exposure. Instead, different modes adjust the gain settings to achieve the same final result. Available white balance modes:
Mode Color Temperature auto 2500K ~ 8000K incadescent 2500K ~ 3000K tungsten 3000K ~3500K fluorescent 4000K ~ 4700K indoor 3000K ~ 5000K daylight 5500K ~ 6500 K cloudy 7000K ~ 8500K custom custom Custom range, set via tuning file
- No mode completely disables AWB. Instead, you can use awbgains to adjust color gains.
- For more information on AWB modes, including how to define custom modes, please refer to the Tuning Guide for Raspberry Pi Camera and libcamera.
rpicam-hello --awb auto
- AWBGains
- Sets fixed red and blue gain values to replace the auto white balance (AWB) algorithm. Setting non-zero values disables AWB. Accepts comma-separated numerical input in the format: <red_gain>,<blue_gain>
rpicam-jpeg -o test.jpg --awbgains 1.5,2.0
- Denoise
- Default: auto
- Sets the denoising mode. Accepts the following values:
- auto: enables standard spatial denoising. Uses ultra-fast color denoising for video and high-quality color denoising for images. Does not enable additional color noise reduction in the preview window.
- off: turns off both spatial and color denoising.
- cdn_off: disables color noise.
- cdn_fast: uses fast color denoising.
- cdn_hq: uses high-quality color denoising. Not suitable for video/viewfinder due to reduced throughput.
- Even fast color denoising can reduce the frame rate. High-quality color denoising significantly reduces the frame rate.
rpicam-hello --denoise off
- Tuning-file
- Specifies the camera tuning file. Tuning files allow you to control many aspects of image processing, including auto-exposure/gain control (AEC/AGC), auto white balance (AWB), color shading correction, color processing, denoising, and more. Accepts the tuning file path as input. For detailed information on tuning files, please refer to Tuning Files.
- Autofocus-mode
- Default: default
- Specifies the autofocus mode. Accepts the following values:
- default: puts the camera in continuous autofocus mode unless the lens position or autofocus capture overrides to manual mode
- manual: does not move the lens unless the lens position is manually configured
- auto: only moves the lens for an autofocus scan when the camera starts or before capturing, if autofocus capture is also used
- continuous: automatically adjusts the lens position as the scene changes
- This option is only supported by certain camera
rpicam-hello --autofocus-mode auto
- autofocus-range
- Default value: normal
- Specifies the autofocus range. Accepts the following values:
- normal: Focus range is fairly close to infinity
- macro: Only focuses on nearby objects, including the closest focal distance supported by the camera
- full: Focuses on the entire range, from the nearest object to infinity
- This option is only supported by certain camera modules.
rpicam-hello autofocus-range normal
- autofocus-speed
- Default value: normal
- Specifies the autofocus speed. Accepts the following values:
- normal: Changes the lens position at a normal speed
- fast: Quickly changes the lens position
- This option is only supported by certain camera modules.
rpicam-hello --autofocus-speed normal
- autofocus-window
- Specifies the autofocus window within the full area of the sensor. Accepts four decimal values ranging from 0 to 1, in the format: <x>, <y>, <w>, <h>. Each of these values is represented as a fraction between 0 and 1, indicating a percentage of the available width and height.
- These values define the following proportions:
- <x>: X-coordinate to skip before applying autofocus
- <y>: Y-coordinate to skip before applying autofocus
- <w>: Width of the autofocus area
- <h>: Height of the autofocus area
- The default value uses the middle third of the output image in both dimensions (1/9 of the total image area).
- Examples:
rpicam-hello—autofocus-window 0.25,0.25,0.5,0.5
- Selects half of the total number of pixels cropped from the center of the image (skips the first 25% of the X-coordinate, skips the first 25% of the Y-coordinate, 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 one-quarter of the total number of pixels cropped from the top-left corner of the image (skips 0% of the X-coordinate, skips 0% of the Y-coordinate, uses 25% of the image width, uses 25% of the image height).
This option is only supported by certain camera modules.
- lens-position
- Default value: default
- Moves the lens to a fixed focal distance, typically represented in diopters (units of 1/meter distance). Accepts the following range of values:
- 0.0: Moves the lens to the "infinity" position
- Any other number: Moves the lens to the 1/number position. For example, a value of 2.0 will focus at approximately 0.5m
- normal: Moves the lens to the default position corresponding to the lens's hyperfocal distance
- Lens calibration is not perfect, so different camera modules of the same model may vary.
- verbose
- Alias: -v
- Default value: 1
- Sets the verbosity level. Accepts the following values:
- 0: No output
- 1: Normal output
- 2: Verbose output
rpicam-hello --verbose 1
- For more detailed information, refer here.
libcamera Software Stack
libcamera-hello
- This command is used to preview the camera and display the camera feed on the screen.
- Example:
- Run the following command in the terminal to preview the camera in real-time
libcamera-hello -t 0
- Where -t 0 indicates continuous preview until the program is terminated. Users can adjust this according to their needs.
- Tuning File:
- The libcamera driver for Raspberry Pi calls a tuning file specific to each camera module. The tuning file provides various parameters that libcamera uses, along with algorithms, to process the image and ultimately output the preview. While the libcamera driver can only automatically sense the sensor signal, the final display effect of the camera is also influenced by the entire module. The use of tuning files allows for flexible handling of different camera modules and adjustments to improve image quality.
- If the camera's output image is not satisfactory when using the default tuning file, users can adjust the image by calling a custom tuning file. For example, if you are using the official NOIR version of the camera, it may require different white balance parameters compared to the regular Raspberry Pi Camera V2. In this case, you can switch by calling the appropriate tuning file.
libcamera-hello --tuning-file /usr/share/libcamera/ipa/raspberrypi/imx219_noir.json
- * Users can copy the default tuning file and modify it according to their needs.
- * Note: The use of tuning files applies to other libcamera commands and will not be repeated in subsequent instructions.
- Preview Window:
- Most libcamera commands display a preview window on the screen. Users can customize the title information of the preview window using the --info-text parameter and also display some camera parameters in the window by using %directives.
- For example, if using an HQ Camera: you can display the camera's focus distance in the window by using --info-text "%focus"
libcamera-hello --info-text "focus %focus"
- Note: For more parameter settings, please refer to the subsequent section on command parameter settings.
libcamera-jpeg
- This command is a simple program for capturing static images. Compared to libcamera-still, libcamera-jpeg is more concise while sharing many of the same functionalities for image capture.
- Example:
- Running the following command in the terminal will display a preview for about 5 seconds and then capture a full-resolution JPEG image
libcamera-jpeg -o test.jpg
- Where test.jpg represents the filename.
- Exposure Control:
- Users can set the preview time with the -t parameter and the resolution of the captured image with --width and --height. For example:
libcamera-jpeg -o test.jpg -t 2000 --width 640 --height 480
- All libcamera commands allow users to set the shutter time and gain. For example:
libcamera-jpeg -o test.jpg -t 2000 --shutter 20000 --gain 1.5
- Where --shutter 20000 represents an exposure of 20ms, and --gain 1.5 sets the camera gain to 1.5x.
- This command will capture an image with a 20ms exposure and a camera gain set to 1.5x. The set gain parameter will first adjust the analog gain within the sensor. If the set gain exceeds the maximum analog gain supported by the driver, the maximum analog gain will be applied, and the remaining gain will be applied as digital gain.
- Note: Digital gain is implemented through the ISP (Image Signal Processing) and is not a direct adjustment of the sensor's internal registers. Normally, the default digital gain is close to 1.0, except in the following three situations:
- When the overall gain requirement cannot be met by analog gain alone, digital gain is used as compensation.
- When one of the color gains is less than 1 (color gains are implemented through digital gain), the final gain will stabilize at 1/min(red_gain, blue_gain), effectively applying a uniform digital gain equal to the gain value of one of the color channels (non-green).
- When AEC/AGC is adjusted. If AEC/AGC changes, the digital gain may also change to some extent to eliminate any fluctuations, but this change will quickly return to a "normal" value.
- The AEC/AGC algorithm on Raspberry Pi allows the program to specify exposure compensation by adjusting the aperture value to change the image brightness. For example:
libcamera-jpeg --ev -0.5 -o darker.jpg libcamera-jpeg --ev 0 -o normal.jpg libcamera-jpeg --ev 0.5 -o brighter.jpg
libcamera-still
- libcamera-still is very similar to libcamera-jpeg, but it inherits more functionalities from raspistill.
- Example: Running the following command in the terminal will capture a photo.
libcamera-still -o test.jpg
- Where test.jpg represents the filename.
- Encoder:
- libcamera-still supports different image file formats, including PNG and BMP encoding, as well as saving raw RGB or YUV pixel data without any encoding or image format. When saving raw RGB or YUV data, programs reading these files must understand the pixel arrangement.
libcamera-still -e png -o test.png libcamera-still -e bmp -o test.bmp libcamera-still -e rgb -o test.data libcamera-still -e yuv420 -o test.data
- The image format is controlled by the -e parameter. If the -e parameter is not used, the format is inferred from the file extension of the output filename.
- Raw Image Capture
- A raw image is the image directly output by the image sensor without any ISP or CPU processing. For color camera sensors, the raw image output format is typically Bayer. Note that raw images are different from the bit-encoded RGB and YUV images, which are processed by the ISP.
- Command to capture a raw image:
libcamera-still -r -o test.jpg
- Raw images are usually saved in DNG (Adobe Digital Negative) format, which is compatible with most standard programs like dcraw or RawTherapee. The raw image will be saved with a .dng extension, and a JPEG file with the same name will also be generated. The DNG file contains metadata related to image acquisition, such as white balance data and ISP color matrix.
- Long Exposure
- To capture a long-exposure image, we need to disable AEC/AGC and white balance, otherwise, these algorithms will cause the image to wait for many frames to converge. Disabling these algorithms requires setting explicit values. Additionally, users can use the --immediate option to skip the preview process.
- Command to capture an image with a 100-second exposure:
libcamera-still -o long_exposure.jpg --shutter 100000000 --gain 1 --awbgains 1,1 --immediate
- Note: Refer to the table for the maximum exposure times of several official cameras.
libcamera-vid
- libcamera-vid is a video recording program that uses the Raspberry Pi's hardware H.264 encoder by default. When this program is run, it displays a preview window on the screen while encoding the bitstream output to a specified file.
- Example: To record a video, execute the following command in the terminal:
libcamera-vid -t 10000 -o test.h264
- Where -t 10000 indicates recording a 10-second video, and test.h264 is the filename.
- To view the video, you can use vlc to play it:
vlc test.h264
- Note: The recorded video is an unpacked video stream. Users can use the --save-pts option to output timestamps, which will facilitate converting the bitstream into other video formats later.
libcamera-vid -o test.h264 --save-pts timestamps.txt
- To output an mkv file, you can use the following command:
mkvmerge -o test.mkv --timecodes 0:timestamps.txt test.h264
- Encoder
- The Raspberry Pi supports JPEG format and uncompressed YUV420 without formatting:
libcamera-vid -t 10000 --codec mjpeg -o test.mjpeg libcamera-vid -t 10000 --codec yuv420 -o test.data
- --The --codec option sets the output format, not the file extension.
- Using the --segment parameter allows you to split the output file into segments (in milliseconds), which is useful for splitting a JPEG video stream into individual shorter (approximately 1ms) JPEG files.
libcamera-vid -t 10000 --codec mjpeg --segment 1 -o test%05d.jpeg
- UDP Video Streaming
- You can use UDP for video streaming. On the Raspberry Pi (server), run:
libcamera-vid -t 0 --inline -o udp://<ip-addr>:<port>
- Where <ip-addr> needs to be replaced with the actual client IP address or multicast address.
- On the client side, use one of the following commands to receive and display the video stream:
vlc udp://@:<port> :demux=h264 vlc udp://@:<port> :demux=h264
- Note: The port must match the one set on the Raspberry Pi.
- TCP Video Streaming
- You can use TCP for video streaming. On the Raspberry Pi (server), run:
libcamera-vid -t 0 --inline --listen -o tcp://0.0.0.0:<port>
- On the client side, run:
vlc tcp/h264://<ip-addr-of-server>:<port> # Use either of the two commands ffplay tcp://<ip-addr-of-server>:<port> -vf "setpts=N/30" -fflags nobuffer -flags low_delay -framedrop
- RTSP Video Streaming
- On the Raspberry Pi, vlc is commonly used to handle RTSP video streams:
libcamera-vid -t 0 --inline -o - | cvlc stream:///dev/stdin --sout '#rtp{sdp=rtsp://:8554/stream1}' :demux=h264
- On the playback side, you can use either of the following commands:
vlc rtsp://<ip-addr-of-server>:8554/stream1 ffplay rtsp://<ip-addr-of-server>:8554/stream1 -vf "setpts=N/30" -fflags nobuffer -flags low_delay -framedrop
- In all preview commands, if you want to turn off the preview window on the Raspberry Pi, you can use the -n (--nopreview) option. Also, note the --inline option, which forces the inclusion of stream header information in each I (intra) frame. This setting allows the client to correctly parse the video stream even if the video header is lost.
- High Frame Rate Mode
- If you use the libcamera-vid command to record high frame rate videos (typically above 60fps) and want to reduce frame drops, consider the following points:
- The H264 target level should be set to 4.2 using the --level 4.2 option.
- Color noise reduction must be turned off using the --denoise cdn_off option.
- If the frame rate is set above 100fps, turn off the preview window to free up more CPU resources and avoid frame drops. Use the -n option.
- It is recommended to add the setting force_turbo=1 in the /boot/config.txt file to ensure that the CPU clock is not limited during video streaming.
- Adjust the ISP output resolution using the -width 1280 --height 720 options, or set it to a lower resolution depending on the camera model.
- If you are using a Pi 4 or a higher-performance model, you can add the setting gpu_freq=550 or higher in the /boot/config.txt file to overclock the board's GPU for better performance.
- For example, to record a 1280x720 video at 120fps:
- If you use the libcamera-vid command to record high frame rate videos (typically above 60fps) and want to reduce frame drops, consider the following points:
libcamera-vid --level 4.2 --framerate 120 --width 1280 --height 720 --save-pts timestamp.pts -o video.264 -t 10000 --denoise cdn_off -n
libcamera-raw
- libcamera-raw is similar to a video recording program, with the difference being that it records Bayer format data directly output by the sensor, which is raw image data. libcamera-raw does not display a preview window.
- To record a 2-second segment of raw data, execute the following command in the terminal:
libcamera-raw -t 2000 -o test.raw
- The program dumps raw frames without format information, and prints the pixel format and image dimensions directly in the terminal, allowing users to view the pixel data based on the output. By default, the program saves the raw frames into a file, which is usually quite large. Users can split the file using the --segment parameter.
libcamera-raw -t 2000 --segment 1 -o test%05d.raw
- If memory conditions are good (e.g., using an SSD), libcamera-raw can write data from the official HQ Camera to the hard drive at approximately 10 frames per second (about 18MB per frame). To achieve this speed, the program writes unformatted raw frames and cannot save them as DNG files like libcamera-still. To ensure no frames are dropped, you can use the --framerate option to lower the frame rate.
libcamera-raw -t 5000 --width 4056 --height 3040 -o test.raw --framerate 8
Common Command Line Options
Common command line options apply to all libcamera commands.
- Print program help information, which lists the available options for each command, and then
--help -h
- When the --version option is seen, all libcamera-apps will print out the version strings for both libcamera and libcamera-apps, and then exit.
--version
libcamera-apps build: ca559f46a97a 27-09-2021 (14:10:24) libcamera build: v0.0.0+3058-c29143f7
- Display the recognized and supported cameras, along with the sensor modes supported by each camera.
--list-cameras
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]
- According to the printed information, the IMX219 camera has a suffix of 0, and the IMX477 camera has a suffix of 1. When invoking the camera, you can specify the corresponding suffix.
- Specify the camera
--camera
- The corresponding suffix can be referenced from the output of the --list-camera command.
- Set a configuration file
--config -c
- Normally, camera parameters can be set directly through commands. Using the --config parameter allows you to specify a configuration file to read settings from, which can be used to configure the camera preview. For example:
libcamera-hello -c config.txt
- In the configuration file, each line represents a setting parameter in the format of key=value, such as:
timeout=99000 verbose=
- Note: Even for implicit options, the = must be used, and the -- used in the command line is omitted. Only long-format options are allowed (t=99000 is not accepted).
- Set program runtime
--timeout -t
- If running a video recording command, the timeout option sets the recording duration. If running an image capture command, timeout sets the preview time before capturing and outputting the image.
- If timeout is not set when running a libcamera program, the default value is 5000 (5 seconds). If timeout is set to 0, the program will run indefinitely. For example:
libcamera-hello -t 0
Preview Window
- Preview window settings
--preview -p
- -p sets the size and position of the preview window (this setting is effective in both X and DRM versions of the window). The format is --preview <x, y, w, h>, where x and y set the coordinates of the preview window on the display, and w and h set the width and height of the preview window.
- The preview window settings do not affect the resolution and aspect ratio of the camera image preview. The program will scale the preview image to fit within the preview window while maintaining the original aspect ratio. For example:
libcamera-hello -p 100,100,500,500
- Fullscreen preview mode
--fullscreen -f
- -f sets the preview window to display in fullscreen mode. Like -p, it does not affect the resolution and aspect ratio and will automatically adapt. For example:
libcamera-still -f -o test.jpg
- Use a Qt-based preview window
--qt-preview
- Use a preview window based on the Qt framework. Normally, this setting is not recommended because the preview program does not use zero-copy buffer sharing and GPU acceleration, which can lead to high resource usage. The Qt preview window supports X forwarding (the default preview program does not).
- The Qt preview window does not support the --fullscreen option. If users need to use Qt preview, it is recommended to keep the preview window small to avoid excessive resource usage that may affect system performance. For example:
libcamera-hello --qt-preview
- Disable image preview
--nopreview -n
- This setting disables the image preview function. Example:
libcamera-still -n -o test.jpg
- Set the title and information display for the preview window
--info-text
- The provided string is set as the title of the preview window (when running under X Windows). Additionally, the string may contain multiple % directives that are replaced with information from the image metadata. Allowed directives:
Directive Description %frame Frame sequence number %fps Instantaneous frame rate %exp Shutter speed when the image was captured, in ms %ag Analog gain controlled by the sensor %dg Digital gain controlled by the ISP %rg Gain for the red component of each pixel %bg Gain for the blue component of each pixel %focus Corner metric of the image, higher values indicate sharper images %lp Current lens diopter (distance in 1/m) %afstate Auto-focus status (idle, scanning, focused, failed)
- If no window information is specified, the default --info-text setting is "#%frame (%fps fps) exp %exp ag %ag dg %dg". For example:
libcamera-hello --info-text "Focus measure: %focus"
Camera Resolution and Settings
- Set Image Resolution
--width --height
- These two parameters set the width and height of the image, respectively. For the libcamera-still, libcamera-jpeg, and libcamera-vid commands, these parameters set the resolution of the output image/video.
- If using the libcamera-raw command, these parameters affect the size of the metadata frame captured. The camera has a 2x2 binned readout mode, and if the set resolution is smaller than the binned mode, the camera will capture metadata frames at the 2x2 binned size.
- If using the libcamera-hello command, resolution cannot be specified.
- Examples:
#to record 1080p video libcamera-vid -o test.h264 --width 1920 --height 1080 #to capture a JPEG image with a resolution of 2028x1520 libcamera-still -r -o test.jpg --width 2028 --height 1520
- Set Preview Image Resolution
--viewfinder-width --viewfinder-height
- This setting only affects the size of the preview image (for the preview stage of libcamera-hello, libcamera-jpeg, and libcamera-still) and does not affect the resolution of the final output image or video. The device's preview image size does not affect the preview window size, which will adapt to the window. For example:
libcamera-hello --viewfinder-width 640 --viewfinder-height 480
- Force Resolution
--rawfull
- Regardless of the requested output resolution (specified by --width and --height), this option forces the sensor to operate in full-resolution readout mode for both still and video capture. This setting is not valid for libcamera-hello.
- Using this option typically results in a decrease in frame rate. In full-resolution mode, frame readout speed may be slower. For example:
libcamera-raw -t 2000 --segment 1 --rawfull -o test%03d.raw
- This command will capture multiple full-resolution raw images. If you are using an HQ camera, each frame will be 18MB in size, whereas without the --rawfull setting, the HQ camera defaults to 2x2 mode, with each frame being only 4.5MB in size.
- Specify Sensor Mode
--mode
- This parameter is more versatile than --rawfull and is used to set the camera mode by specifying width, height, bit depth, and packing mode, separated by colons. The specified values do not need to be exact, as the system will automatically match the closest values. Additionally, bit depth and packing mode are configurable (default is 12 and P, meaning packed). For example:
- 4056:3040:12:P - 4056x3040 resolution, 12 bits per pixel, packed. Packing means that raw image data is packed in the buffer, so two pixels occupy only 3 bytes, saving memory.
- 1632:1224:10 - 1632x1224 resolution, 10 bits per pixel, default packed. In 10-bit packed mode, 4 pixels occupy 5 bytes.
- 2592:1944:10:U - 2592x1944 resolution, 10 bits per pixel, unpacked. In unpacked mode, each pixel occupies 2 bytes of memory, with the top 6 bits set to 0.
- 3262:2448 - 3264x2448 resolution, defaulting to 12 bits and packed mode. However, if the camera model, such as Camera V2 (IMX219), does not support 12-bit mode, the system will automatically select 10-bit mode.
- The --mode parameter is used to set the camera mode when recording video and capturing still images. To set it during the preview, use --viewfinder-mode.
- This parameter is more versatile than --rawfull and is used to set the camera mode by specifying width, height, bit depth, and packing mode, separated by colons. The specified values do not need to be exact, as the system will automatically match the closest values. Additionally, bit depth and packing mode are configurable (default is 12 and P, meaning packed). For example:
--viewfinder-mode #Specify sensor mode as <width>:<height>:<bit-depth>:<packing>
- This option is identical to the --mode option, except it only applies to the preview stage of still capture (also used by the libcamera-hello application).
- Low-Resolution Image Settings
--lores-width --lores-height
- Libcamera allows the transmission of a second, lower-resolution image stream from the camera system to the application. This image stream is available in preview and video modes (i.e., libcamera-hello, libcamera-still, and libcamera-vid) and can be used, among other things, for image analysis. For still captures, the low-resolution image stream is not available.
- The field of view of the low-resolution image stream is the same as the other image streams. If a different aspect ratio is specified for the low-resolution stream, these images will be compressed, and the pixels will no longer be square.
- During video recording (libcamera-vid), if low resolution is set, features such as color denoising may be disabled. For example:
libcamera-hello --lores-width 224 --lores-height 224
- Note that low-resolution settings are typically used in conjunction with image post-processing, otherwise, their utility may be limited.
- Flip Image
--hflip #Horizontally flip the image --vflip #Vertically flip the image --rotation #Flip the image horizontally or vertically based on the given angle
- The --rotation parameter currently only supports 0 and 180, which are equivalent to --hflip and --vflip, respectively. For example:
libcamera-hello --vflip --hflip
- Crop Image
--roi #Crop image <x, y, w, h>
- -roi allows users to crop their desired image area from the full image provided by the sensor, essentially performing digital zoom. Note that the coordinate values must be within the valid range. For example, --roi 0, 0, 1, 1 is an invalid command.
- Example: This command will crop out 1/4 of the image from the center.
libcamera-hello --roi 0.25,0.25,0.5,0.5
- Run in HDR Mode
--hdr
- The --hdr option enables the camera to operate in HDR (High Dynamic Range) mode. This option is only available for certain supported cameras, including the Raspberry Pi Camera Module 3 series. For example:
libcamera-still --hdr -o hdr.jpg #to capture a still image, libcamera-vid --hdr -o hdr.h264 #to capture video.
- Using the HDR option typically results in a different camera mode, which can be checked by comparing the output of libcamera-hello --list-cameras and libcamera-hello --hdr --list-cameras.
- Users can also provide --hdr 0 or --hdr 1, where the former disables HDR mode (equivalent to omitting the option entirely), and the latter is the same as using --hdr alone.
- Note: For the Raspberry Pi Camera Module 3, non-HDR modes include the usual full-resolution (12MP) mode and its equivalent half-resolution 2x2 binned (3MP) mode. In HDR mode, only one half-resolution (3MP) mode is available, and it is not possible to switch between HDR and non-HDR modes without restarting the camera application.
Camera Control
The following options will affect the image processing and control algorithms, thereby impacting the camera's image quality.
- Set Image Sharpness
--sharpness <number>
- Adjust the sharpness of the image through the <number> value. If set to 0, no sharpening is applied. If the value set exceeds 1.0, additional sharpening is used. For example:
libcamera-still -o test.jpg --sharpness 2.0
- Set Image Contrast
--contrast <number>
- Adjust the image contrast through the <number> value. A value of 0 results in minimal contrast; a value of 1.0 uses the default contrast; values greater than 1.0 apply additional contrast. For example:
libcamera-still -o test.jpg --contrast 1.5
- Set Image Brightness
--brightness <number>
- Adjust the image brightness through the <number> value, with a range of -1.0 to 1.0. A value of -1.0 produces an (almost) black image, 1.0 produces an almost entirely white image, and 0.0 produces standard image brightness. For example:
libcamera-still -o test.jpg --brightness 0.2
- Note that the brightness parameter increases (or decreases) the offset for all pixels in the output image. Using the --ev option is generally more appropriate.
- Set Image Saturation
--saturation <number>
- Adjust the color saturation through the <number> value. A value of 0 generates a grayscale image, 1.0 uses the default color saturation, and values greater than 1.0 apply additional color saturation. For example:
libcamera-still -o test.jpg --saturation 0.8
- Set EV Compensation
--ev <number>
- Set the EV compensation of the image through the <number> value, in stops, with a range of -10 to 10. The default value is 0. It works by raising or lowering the target value that the AEC/AGC algorithm attempts to match. For example:
libcamera-still -o test.jpg --ev 0.3
- Set Shutter Time
--shutter <number>
- Note: If the camera's frame rate is too fast, it may not work with the set shutter time. If this occurs, try reducing the frame rate with --framerate.
libcamera-hello --shutter 30000
- Set Gain Value
--gain <number> # Set the gain value (combination of digital and analog gain) --analoggain # Analog gain, synonymous with --gain
- --analoggain and --gain are actually the same; they set the analog and digital gain to be used. Using analoggain is just for compatibility with raspicam programs. If the sensor driver can provide the required gain, only analog gain will be used. Once the analog gain reaches its maximum allowed value, any excess will be provided as digital gain.
- Note: In some cases, the digital gain may exceed 1 even if the analog gain limit has not been exceeded. This can happen when:
- Any color gain below 1.0 will cause the digital gain to stabilize at 1.0/min(red_gain, blue_gain). This means that the total digital gain applied to any color channel will not be less than 1.0, as this would lead to color distortion.
- When AEC/AGC changes, the digital gain may vary slightly, but this effect should be temporary.
- Set Metering Mode
--metering <string>
- Set the metering mode for the AEC/AGC algorithm. Available options are:
centre - Center-weighted metering (default) Spot - Spot metering averag - Average or full-frame metering custom - Custom metering mode, configurable through a tuning file
- For details on defining a custom metering mode and how to adjust region weights within existing metering modes, please refer to the Raspberry Pi Camera and libcamera Tuning Guide.
- Example:
libcamera-still -o test.jpg --metering spot
- Set Exposure Profile
--exposure <string>
- The exposure mode can be set to normal or sport. These two exposure profiles do not affect the overall exposure of the image, but in sport mode, the program will shorten the exposure time and increase the gain to achieve the same exposure effect.
- The exposure profile can be edited in the camera tuning file. For details, please refer to the Raspberry Pi Camera and libcamera Tuning Guide.
- Example:
libcamera-still -o test.jpg --exposure sport
- Set White Balance Mode
--awb <string>
- Available white balance modes:
Mode Color Temperature Auto 2500K ~ 8000K incandescent 2500K ~ 3000K Tungsten 3000K ~ 3500K fluorescent 4000K ~ 4700K indoor 3000K ~ 5000K daylight 5500K ~ 6500K cloudy 7000K ~ 8500K custom Custom range, configurable through a tuning file
- Note: These values are approximate and may vary based on camera adjustments.
- For more information on AWB modes and how to define custom modes, please refer to the Raspberry Pi Camera and libcamera Tuning Guide.
- Example:
libamera-still -o test.jpg --awb tungsten
- Set Fixed Color Gains
--awbgains <number,number>
- Set the red and blue gain values through <number> and use them directly instead of the AWB algorithm. Setting non-zero values here will disable AWB calculations.
- Example:
libcamera-still -o test.jpg --awbgains 1.5, 2.0
- Set Denoising Mode
--denoise <string>
- Supported denoising modes:
auto - Default mode, uses standard spatial denoising. For video, it uses fast color denoising, and for still images, it uses high-quality color denoising. Preview images do not use any color denoising. off - Disables both spatial and color denoising. cdn_off - Disables color denoising. cdn_fast - Uses fast color denoising. cdn_hq - Uses high-quality color denoising, not suitable for video recording.
- Note that even using fast color denoising can reduce the frame rate. High-quality color denoising typically results in an even lower frame rate.
- Example:
libcamera-vid -o test.h264 --denoise cdn_off
- Specify Camera Tuning File
--tuning-file <string>
- This specifies the name of the JSON-formatted tuning file that should be used. Tuning files cover many aspects of image processing, including AEC/AGC, AWB, color shading correction, color processing, denoising, etc.
- For more information on tuning files, please refer to the official guide.
- Example:
libcamera-hello --tuning-file ~/my~camera-tuning.json
- Set Autofocus Mode
--autofocus-mode <string>
- Set the autofocus mode. The following modes are available:
default - By default, the camera will operate in continuous autofocus mode unless --lens-position or --autofocus-on-capture is set for manual focus methods. manual - Manual focus mode, where the focus position can be set via --lens-position. auto - The camera will only focus once when it is turned on and will not adjust the focus in other situations. (If using the libcamera-still command, it will only focus once before taking a photo when --autofocus-on-capture is used.) continuous - The camera will automatically adjust the focus position based on changes in the scene.
- This option is only supported by certain camera modules (e.g., Raspberry Pi Camera Module 3 series).
- Setting the Autofocus Range
--autofocus-range <string>
- Set the autofocus range with the following options:
normal - Default, from the closest to infinity. macro - Macro mode, focuses only on nearby objects. full - Full range mode, adjusts from the closest object to infinity.
- This option is only supported by certain camera modules (e.g., Raspberry Pi Camera Module 3 series).
- Setting the Focus Speed
--autofocus-speed <string>
- Set the focus speed with the following options:
normal - Default, normal speed. fast - Fast focus mode.
- This option is only supported by certain camera modules (e.g., Raspberry Pi Camera Module 3 series).
- Displaying the Autofocus Window
--autofocus-window
- Display the autofocus window with the format x,y,width,height, where coordinates are given as proportions of the entire image. For example, --autofocus-window 0.25,0.25,0.5,0.5 will select a window that is half the size of the output image in each dimension, centered in the middle.
- The default value causes the algorithm to use the middle third of the output image in both dimensions (i.e., 1/9 of the total image area).
- This option is only supported by certain camera modules (e.g., Raspberry Pi Camera Module 3 series).
- Setting the Focus Position
--lens-position <string>
- Move the lens to a fixed focal distance, typically given in diopters (1/meter distance). For example:
0.0 -- Set the focus position to infinity. Any other number -- Set the focus position to 1/number, where number is any value you set. For example, if set to 2, it will focus at a 0.5m distance. default -- Focus to the default position relative to the lens's hyperfocal distance.
- Note that the lens can only be approximately calibrated, and there may be differences between different camera modules.
- This option is only supported by certain camera modules (e.g., Raspberry Pi Camera Module 3 series).
Output File Options
- Output File Name
--output -o
- Set the filename for the output image or video. In addition to setting a filename, you can specify a UDP or TCP server address to stream the image to. For those interested, please refer to the subsequent sections on TCP and UDP settings for more details.
- Example:
libcamera-vid -t 100000 --segment 10000 -o chunk%04d.h264
- Record a 100-second file, with each 10-second segment named chunk.h264, including an incrementing counter. Note that %04d writes the counter as a string, padded with leading zeros to a total width of at least 4 characters.
libcamera-vid -t 0 --inline -o udp://192.168.1.13:5000
- Stream the H.264 video to the network address 192.168.1.13 on port 5000.
- Output File Counter
--wrap <number>
- When outputting to files with an incrementing counter (such as %d in the output filename), reset the counter to zero when it reaches this value.
- Example:
libcamera-vid -t 0 --codec mjpeg --segment 1 --wrap 100 -o image%d.jpg
- Flush Output File Immediately
--flush
- -flush writes each frame to the disk immediately, reducing latency, instead of waiting for the system to flush.
- Example:
libcamera-vid -t 10000 --flush -o test.h264
Post-Processing
- The post-process-file option specifies a JSON file that configures the post-processing applied to the camera image by the imaging pipeline before it reaches the application. It can be regarded as an alternative to the traditional raspicam "image effects".
- Post-processing is a broad topic that involves using third-party software such as OpenCV and TensorFlowLite to analyze and process images. For more information, please refer to the post-processing section.
- Example:
libcamera-hello --post-process-file negate.json
Settings for Capturing Static Images
--quality, -q # Set JPEG image quality <0 - 100> --exif, -x # Add additional EXIF tags --timelapse # Set time interval for time-lapse photography, in ms --framestart # Set starting value for frame count --datetime # Name output file with date format --timestamp # Name output file with system timestamp --restart # Set JPEG restart interval --keypress, -k # Set enter key to trigger photo capture --signal, -s # Set signal to trigger photo capture --thumb # Set thumbnail parameters <w:h:q> --encoding, -e # Set image encoding type: jpg / png / bmp / rgb / yuv420 --raw, -r # Save raw image --latest # Link symbol to the latest saved file --autofocus-on-capture # Perform autofocus before capturing a photo
Settings for Video Recording
--quality, -q # Set JPEG quality <0 - 100> --bitrate, -b # Set H.264 bitrate --intra, -g # Set intra-frame period (only supported for H.264) --profile # Set H.264 profile --level # Set H.264 level --codec # Set encoding type: h264 / mjpeg / yuv420 --keypress, -k # Set enter key to pause and resume recording --signal, -s # Set signal to pause and resume recording --initial # Start the program in recording or paused state --split # Split video and save to a separate file --segment # Split video into multiple segments --circular # Write video to a circular buffer --inline # Write header in each I-frame (only supported for H.264) --listen # Wait for TCP connection --frames # Set the number of frames to record
Buster System
Taking Photos
To take a photo, simply execute the following command in the terminal:
raspistill -o image.jpg
Here, image.jpg is the filename of the photo.
Recording Video
To record a video, execute the following command in the terminal: 终端执行以下语句即可摄像:
raspivid -o video.h264 -t 10000
Where -t 10000 indicates recording for 10 seconds. Users can adjust this according to their needs.
References
Controlling the Camera with Python
- The picamera library can be used to enable Python support for camera control.
- Starting from the Bullseye version of the Raspberry Pi image, the underlying camera driver has switched from Raspicam to libcamera. libcamera is an open-source software stack (hereinafter referred to as the driver for simplicity) that facilitates third-party porting and development of their own camera drivers. Currently, libcamera does not support Python, so the Raspberry Pi official website still provides installation and download methods for Raspicam. For users who find it difficult to switch to libcamera but need to use the latest system, please proceed directly to the instructions for using Raspicam.
Preview
- Open a Python IDE, such as Thonny Python IDE, or open a text editor.
- Create a new Python file named camera.py and save it to the desktop.
- Enter the following code:
from picamera import PiCamera
from time import sleep
camera = PiCamera()
camera.start_preview()
sleep(5)
camera.stop_preview()
- In the terminal, execute:
python3 Desktop/camera.py
A preview window will pop up on the desktop, providing a live view.
Note that the preview window is only effective when connected directly to a screen. It will not pop up if you are remotely connected to the Raspberry Pi desktop using software like VNC.
If the preview image is upside down, you can rotate it 180 degrees with the following code:
camera = PiCamera()
camera.rotation = 180
- The preview image can be rotated 90, 180, or 270 degrees.
- To reset the image, set the rotation to 0 degrees.
Setting Preview Window Transparency
camera.start_preview(alpha=100)
The alpha value ranges from 0-255.
Taking Photos
- Insert the camera.capture() command in the middle of the preview code:
camera.start_preview()
sleep(5)
camera.capture('/home/pi/Desktop/image.jpg')
camera.stop_preview()
Please note: The sleep(5) code must be executed to allow the camera sensor time to adjust brightness and white balance.
Recording Video
Remove camera.capture() and add camera.start_recording() and camera.stop_recording():
camera.start_preview()
camera.start_recording('/home/pi/Desktop/video.h264')
sleep(5)
camera.stop_recording()
camera.stop_preview()
After executing the above code, a video.h264 video will be generated on the desktop, with a length of 5 seconds.
More Parameters
- The picamera library allows for many parameters to be added to images.
Setting Resolution
- By default, the image resolution matches the display resolution, but the maximum image size does not exceed 2592x1944 pixels, and the video size does not exceed 1920x1080 pixels; the minimum size for both images and videos is 64x64 pixels.
- The following code can be used to set the image resolution:
camera.resolution = (2592, 1944)
camera.framerate = 15
camera.start_preview()
sleep(5)
camera.capture('/home/pi/Desktop/max.jpg')
camera.stop_preview()
- Please note that the camera's frame rate should be set to ≤15 frames per second to support the maximum resolution.
Adding Text to Images
Adding Text
camera.start_preview()
camera.annotate_text = "Hello world!"
sleep(5)
camera.capture('/home/pi/Desktop/text.jpg')
camera.stop_preview()
Text Size
camera.annotate_text_size = 50
annotate_text_size ranges from 6-160, default is 32
Text Color
camera.start_preview()
camera.annotate_background = Color('blue')
camera.annotate_foreground = Color('yellow')
camera.annotate_text = " Hello world "
sleep(5)
camera.stop_preview()
Modifying Image Parameters
- Brightness
camera.start_preview()
camera.brightness = 70
sleep(5)
camera.capture('/home/pi/Desktop/bright.jpg')
camera.stop_preview()
brightness ranges from 0-100, default is 50
- Contrast
camera.contrast = 50
contrast ranges from 0-100, default is 50
- Image Effect
Use camera.image_effect to add special effects to the image
Valid values:
- none (default)
- negative
- solarize
- sketch
- denoise
- emboss
- oilpaint
- hatch
- gpen
- pastel
- watercolor
- film
- blur
- saturation
- colorswap
- washedout
- posterise
- colorpoint
- colorbalance
- cartoon
- deinterlace1
- deinterlace2
For example
camera.start_preview()
camera.image_effect = 'colorswap'
sleep(5)
camera.capture('/home/pi/Desktop/colorswap.jpg')
camera.stop_preview()
- Mode
Use camera.exposure_mode to set the photography mode (such as night, sports, snow, etc.)
Valid values:
- off
- auto (default)
- night
- nightpreview
- backlight
- spotlight
- sports
- snow
- beach
- verylong
- fixedfps
- antishake
- fireworks
For example
camera.start_preview()
camera.exposure_mode = 'beach'
sleep(5)
camera.capture('/home/pi/Desktop/beach.jpg')
camera.stop_preview()
- White Balance
Use camera.awb_mode to set the white balance
Valid values:
- off
- auto (default)
- sunlight
- cloudy
- shade
- tungsten
- fluorescent
- incandescent
- flash
- horizon
For example, setting the white balance to "sunlight"
camera.start_preview()
camera.awb_mode = 'sunlight'
sleep(5)
camera.capture('/home/pi/Desktop/sunlight.jpg')
camera.stop_preview()