Bird
0
0
Raspberry Piprogramming~5 mins

picamera2 library basics in Raspberry Pi

Choose your learning style9 modes available
Introduction

The picamera2 library helps you take pictures and videos with the Raspberry Pi camera easily.

You want to capture photos with your Raspberry Pi camera.
You want to record videos using the Raspberry Pi camera.
You want to preview what the camera sees on your screen.
You want to control camera settings like brightness or resolution.
You want to build a project that needs camera input, like a security camera.
Syntax
Raspberry Pi
from picamera2 import Picamera2

picam2 = Picamera2()
picam2.start()
image = picam2.capture_array()

picam2.stop()

Always import Picamera2 from the picamera2 library first.

Use start() to begin the camera and stop() to end it.

Examples
Basic example to start the camera, take a picture as an array, then stop the camera.
Raspberry Pi
from picamera2 import Picamera2

picam2 = Picamera2()
picam2.start()
image = picam2.capture_array()
picam2.stop()
This example shows how to configure and start a live preview from the camera.
Raspberry Pi
from picamera2 import Picamera2

picam2 = Picamera2()
preview_config = picam2.create_preview_configuration()
picam2.configure(preview_config)
picam2.start()
# Now you can see the camera preview on screen
picam2.stop()
This example sets up the camera to record video instead of just photos.
Raspberry Pi
from picamera2 import Picamera2

picam2 = Picamera2()
video_config = picam2.create_video_configuration()
picam2.configure(video_config)
picam2.start()
# Record video here
picam2.stop()
Sample Program

This program starts the camera, takes a photo, saves it as a JPEG file, then stops the camera. It uses OpenCV to save the image.

Raspberry Pi
from picamera2 import Picamera2
import cv2

picam2 = Picamera2()
picam2.start()

# Capture one image
image = picam2.capture_array()

# Save the image using OpenCV
image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
cv2.imwrite('captured_image.jpg', image_bgr)

picam2.stop()
print('Image saved as captured_image.jpg')
OutputSuccess
Important Notes

Make sure your Raspberry Pi camera is enabled in the Raspberry Pi settings before using picamera2.

Use capture_array() to get the image as a NumPy array for easy processing.

Always stop the camera with stop() to free resources.

Summary

picamera2 lets you control the Raspberry Pi camera with simple commands.

You start the camera, capture images or video, then stop it when done.

You can preview, capture photos, or record videos by configuring the camera.