### Get Camera Properties and Info Source: https://context7.com/raspberrypi/picamera2/llms.txt Queries available cameras and their capabilities using the `Picamera2` library. This example shows how to list cameras, open a specific camera, and retrieve its properties, controls, and sensor modes. ```python from picamera2 import Picamera2 # Get info about all connected cameras cameras = Picamera2.global_camera_info() for cam in cameras: print(f"Camera {cam['Num']}: {cam['Model']}") print(f" ID: {cam['Id']}") print(f" Location: {cam.get('Location', 'unknown')}") # Open specific camera by index picam2 = Picamera2(camera_num=0) # Get camera properties props = picam2.camera_properties print(f"Sensor resolution: {picam2.sensor_resolution}") print(f"Camera model: {props.get('Model', 'unknown')}") # Get available controls and their ranges controls = picam2.camera_controls for name, (min_val, max_val, default) in controls.items(): print(f"{name}: min={min_val}, max={max_val}, default={default}") # Get available sensor modes modes = picam2.sensor_modes for mode in modes: print(f"Mode: {mode['size']} @ {mode.get('fps', '?')}fps, {mode.get('bit_depth', '?')}-bit") picam2.close() ``` -------------------------------- ### Install from TestPyPI Source: https://github.com/raspberrypi/picamera2/wiki/Releasing-and-Packaging Install your package from the TestPyPI repository to confirm it is correctly published and can be installed. ```bash pip3 install --index-url https://test.pypi.org/simple/ picamera2 ``` -------------------------------- ### Install and Run Pre-commit Hook Source: https://github.com/raspberrypi/picamera2/blob/main/README.md Install the pre-commit hook to ensure code conforms to PEP 8 standards before committing. This installs flake8 in a virtual environment. ```bash pip3 install pre-commit pre-commit install ``` -------------------------------- ### Create Basic and Custom Preview Configurations Source: https://context7.com/raspberrypi/picamera2/llms.txt Configure the camera for live preview. Supports basic setup or custom stream sizes, formats, buffer counts, and frame rate limits. ```python from picamera2 import Picamera2 picam2 = Picamera2() # Basic preview configuration preview_config = picam2.create_preview_configuration() # Custom preview with specific main stream size and format preview_config = picam2.create_preview_configuration( main={"size": (1280, 720), "format": "RGB888"}, lores={"size": (640, 480), "format": "YUV420"}, # Low resolution stream for processing buffer_count=4, controls={"FrameDurationLimits": (33333, 33333)} # Lock to 30fps ) picam2.configure(preview_config) picam2.start() ``` -------------------------------- ### Upload to TestPyPI Source: https://github.com/raspberrypi/picamera2/wiki/Releasing-and-Packaging Upload your package to the TestPyPI repository for initial testing. This allows you to verify the upload process and installation without affecting the live PyPI. ```bash python3 -m twine upload --repository testpypi dist/* ``` -------------------------------- ### MJPEG Streaming Server Source: https://context7.com/raspberrypi/picamera2/llms.txt Creates an HTTP MJPEG streaming server for network viewing. This example sets up a basic server to stream JPEG frames over HTTP. ```python import io import socketserver from http import server from threading import Condition from picamera2 import Picamera2 from picamera2.encoders import JpegEncoder from picamera2.outputs import FileOutput class StreamingOutput(io.BufferedIOBase): def __init__(self): self.frame = None self.condition = Condition() def write(self, buf): with self.condition: self.frame = buf self.condition.notify_all() class StreamingHandler(server.BaseHTTPRequestHandler): def do_GET(self): if self.path == '/stream.mjpg': self.send_response(200) self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME') self.end_headers() while True: with output.condition: output.condition.wait() frame = output.frame self.wfile.write(b'--FRAME\r\n') self.send_header('Content-Type', 'image/jpeg') self.send_header('Content-Length', len(frame)) self.end_headers() self.wfile.write(frame) class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer): allow_reuse_address = True picam2 = Picamera2() picam2.configure(picam2.create_video_configuration(main={"size": (640, 480)})) output = StreamingOutput() picam2.start_recording(JpegEncoder(), FileOutput(output)) # Access stream at http://:8000/stream.mjpg server = StreamingServer(('', 8000), StreamingHandler) server.serve_forever() ``` -------------------------------- ### Build Distribution Packages Source: https://github.com/raspberrypi/picamera2/wiki/Releasing-and-Packaging Build source distribution (sdist) and wheel (bdist_wheel) archives for your package. You may need to install the 'wheel' package first. ```bash python setup.py sdist bdist_wheel ``` -------------------------------- ### Manual Camera Control and JPEG Capture with Picamera2 Source: https://context7.com/raspberrypi/picamera2/llms.txt Provides fine-grained control over camera setup, preview, and capture. Includes manual waiting for exposure/white balance and captures metadata. ```python import time from picamera2 import Picamera2, Preview picam2 = Picamera2() # Create and apply preview configuration with custom size preview_config = picam2.create_preview_configuration(main={"size": (800, 600)}) picam2.configure(preview_config) # Start preview window and camera picam2.start_preview(Preview.QTGL) picam2.start() # Wait for auto exposure/white balance to settle time.sleep(2) # Capture image and get metadata metadata = picam2.capture_file("test.jpg") print(f"Exposure time: {metadata['ExposureTime']}us") print(f"Analogue gain: {metadata['AnalogueGain']}") picam2.close() ``` -------------------------------- ### Create Video Recording Configurations Source: https://context7.com/raspberrypi/picamera2/llms.txt Configure the camera for video recording with specified resolutions, frame rates, and color spaces. Supports a low-resolution stream for processing. ```python from picamera2 import Picamera2 picam2 = Picamera2() # Basic video configuration (1280x720 at 30fps) video_config = picam2.create_video_configuration() # Custom video configuration video_config = picam2.create_video_configuration( main={"size": (1920, 1080), "format": "XBGR8888"}, lores={"size": (640, 480), "format": "YUV420"}, # For motion detection buffer_count=6, controls={"FrameDurationLimits": (16666, 16666)} # 60fps ) picam2.configure(video_config) ``` -------------------------------- ### Create Git Tag Source: https://github.com/raspberrypi/picamera2/wiki/Releasing-and-Packaging Create a new Git tag for a release. Ensure the tag name matches the version number specified in setup.py. ```bash git tag -a vx.x.x ``` -------------------------------- ### Create Still Image Capture Configurations Source: https://context7.com/raspberrypi/picamera2/llms.txt Configure the camera for high-quality still image capture at full sensor resolution. Supports enabling raw capture and custom stream formats. ```python from picamera2 import Picamera2 picam2 = Picamera2() # Basic still configuration (uses full sensor resolution) still_config = picam2.create_still_configuration() # Custom still configuration still_config = picam2.create_still_configuration( main={"size": (4056, 3040), "format": "BGR888"}, # Full resolution raw={"size": (4056, 3040)}, # Enable raw capture buffer_count=2 ) picam2.configure(still_config) ``` -------------------------------- ### Configure PyPI Credentials Source: https://github.com/raspberrypi/picamera2/wiki/Releasing-and-Packaging Store your PyPI API tokens in the ~/.pypirc file for authentication. Ensure you use '__token__' as the username. ```ini [pypi] username = __token__ password = pypi-AgEIcH... [testpypi] username = __token__ password = pypi-AgENdG... ``` -------------------------------- ### Upload to PyPI Source: https://github.com/raspberrypi/picamera2/wiki/Releasing-and-Packaging Upload your package to the main PyPI repository after successful testing on TestPyPI. Ensure the package version has been updated and tagged. ```bash python3 -m twine upload dist/* ``` -------------------------------- ### Switch Between Camera Modes for Capture Source: https://context7.com/raspberrypi/picamera2/llms.txt Seamlessly switch from preview mode to still capture mode and back. Captures a full-resolution image and automatically returns to the preview configuration. ```python import time from picamera2 import Picamera2, Preview picam2 = Picamera2() # Configure for preview preview_config = picam2.create_preview_configuration() capture_config = picam2.create_still_configuration() picam2.configure(preview_config) picam2.start_preview(Preview.QTGL) picam2.start() time.sleep(2) # Switch to still mode, capture, and return to preview automatically picam2.switch_mode_and_capture_file(capture_config, "full_resolution.jpg") ``` -------------------------------- ### Capture Raw DNG File Source: https://context7.com/raspberrypi/picamera2/llms.txt Captures raw sensor data in DNG format from the 'raw' stream. Requires a still configuration with raw enabled. ```python # Enable raw stream in still configuration capture_config = picam2.create_still_configuration(raw={}) preview_config = picam2.create_preview_configuration() picam2.configure(preview_config) picam2.start() time.sleep(2) # Switch mode and capture DNG from raw stream picam2.switch_mode_and_capture_file(capture_config, "photo.dng", name="raw") ``` -------------------------------- ### Available Outputs Source: https://context7.com/raspberrypi/picamera2/llms.txt Lists various output types available in `picamera2.outputs` for different use cases, including file output, container formats, and circular buffers. ```python from picamera2.outputs import ( FileOutput, PyavOutput, FfmpegOutput, CircularOutput, CircularOutput2, SplittableOutput ) ``` -------------------------------- ### Run Autofocus Cycle Source: https://context7.com/raspberrypi/picamera2/llms.txt Initiates an autofocus cycle and checks for success. Manual focus can also be set. ```python success = picam2.autofocus_cycle() print(f"Autofocus {'succeeded' if success else 'failed'}") # Manual focus control picam2.set_controls({"AfMode": controls.AfModeEnum.Manual, "LensPosition": 2.0}) ``` -------------------------------- ### Simple Video Recording Source: https://context7.com/raspberrypi/picamera2/llms.txt Conveniently records video to an MP4 file for a specified duration. Supports audio recording if a microphone is available. ```python from picamera2 import Picamera2 picam2 = Picamera2() # Record a 5 second video to MP4 picam2.start_and_record_video("test.mp4", duration=5) # Record with audio (requires microphone) picam2.start_and_record_video("test_audio.mp4", duration=10, audio=True) ``` -------------------------------- ### Check Distribution Package Integrity Source: https://github.com/raspberrypi/picamera2/wiki/Releasing-and-Packaging Verify that your built distribution packages are valid before uploading them to PyPI. ```bash python3 -m twine check dist/* ``` -------------------------------- ### Available Encoders Source: https://context7.com/raspberrypi/picamera2/llms.txt Demonstrates the usage of different encoder options provided by `picamera2.encoders`. These include hardware-accelerated H264 and MJPEG encoders, as well as a software JPEG encoder. ```python from picamera2.encoders import ( H264Encoder, MJPEGEncoder, JpegEncoder, Quality ) # H264 with specific bitrate h264 = H264Encoder(bitrate=10000000) # 10 Mbps # H264 with quality preset h264 = H264Encoder() # Use with: picam2.start_encoder(h264, quality=Quality.HIGH) # MJPEG encoder mjpeg = MJPEGEncoder() # JPEG encoder for streaming jpeg = JpegEncoder() ``` -------------------------------- ### Push Git Tags Source: https://github.com/raspberrypi/picamera2/wiki/Releasing-and-Packaging Push all local tags to the remote repository to make them available. ```bash git push --tags ``` -------------------------------- ### Set Exposure and Gain Controls Source: https://context7.com/raspberrypi/picamera2/llms.txt Manually controls exposure time, analogue gain, and white balance. It's recommended to let auto exposure settle before capturing initial values. ```python import time from picamera2 import Picamera2 picam2 = Picamera2() picam2.configure(picam2.create_preview_configuration()) picam2.start() # Let auto exposure settle time.sleep(1) # Capture current auto-determined values metadata = picam2.capture_metadata() controls = { "ExposureTime": metadata["ExposureTime"], "AnalogueGain": metadata["AnalogueGain"], "ColourGains": metadata["ColourGains"] } print(f"Locking controls to: {controls}") # Apply fixed controls (disables auto exposure/gain) picam2.set_controls(controls) # Additional control examples picam2.set_controls({ "Brightness": 0.2, # Range: -1.0 to 1.0 "Contrast": 1.2, # Range: 0.0 to 32.0 "Saturation": 1.0, # Range: 0.0 to 32.0 "Sharpness": 1.5, # Range: 0.0 to 16.0 "AeEnable": False, # Disable auto exposure "AwbEnable": False, # Disable auto white balance }) time.sleep(5) picam2.close() ``` -------------------------------- ### Face Detection with OpenCV Source: https://context7.com/raspberrypi/picamera2/llms.txt Integrates Picamera2 with OpenCV for real-time face detection. Uses a lores stream for efficient grayscale processing and draws rectangles on the main stream preview. ```python # Load face detection classifier face_detector = cv2.CascadeClassifier( "/usr/share/opencv4/haarcascades/haarcascade_frontalface_default.xml" ) cv2.startWindowThread() picam2 = Picamera2() # RGB888 for display, YUV420 lores for efficient grayscale processing config = picam2.create_preview_configuration( main={"format": "RGB888", "size": (640, 480)}, lores={"format": "YUV420", "size": (640, 480)} ) picam2.configure(config) picam2.start() while True: with picam2.captured_request() as request: # Get grayscale from YUV420 lores stream (Y channel only) grey = request.make_array("lores")[:480, :640] # Detect faces faces = face_detector.detectMultiScale(grey, 1.1, 5) # Draw rectangles on main stream with MappedArray(request, "main") as m: for (x, y, w, h) in faces: cv2.rectangle(m.array, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.imshow("Camera", m.array) if cv2.waitKey(1) & 0xFF == ord('q'): break picam2.close() cv2.destroyAllWindows() ``` -------------------------------- ### Save Video to MP4 File Source: https://context7.com/raspberrypi/picamera2/llms.txt Use PyavOutput for recommended MP4 video recording. This often provides better compatibility and features than raw H.264. ```python from picamera2.outputs import PyavOutput output = PyavOutput("video.mp4") ``` -------------------------------- ### Save Video to H.264 File Source: https://context7.com/raspberrypi/picamera2/llms.txt Use FileOutput to save raw H.264 video streams. Ensure the filename has a .h264 extension. ```python from picamera2.outputs import FileOutput output = FileOutput("video.h264") ``` -------------------------------- ### Capture a Single JPEG Image with Picamera2 Source: https://context7.com/raspberrypi/picamera2/llms.txt Use this method for a quick capture with default settings. A short preview delay is included by default. ```python from picamera2 import Picamera2 picam2 = Picamera2() # Capture one image with default configurations (includes 1 second preview delay) picam2.start_and_capture_file("photo.jpg") # Capture with custom delay before capture picam2.start_and_capture_file("photo.jpg", delay=2) ``` -------------------------------- ### Use Circular Buffer for Video Source: https://context7.com/raspberrypi/picamera2/llms.txt Employ CircularOutput to store video in a buffer, useful for capturing short clips or debugging. The buffersize determines the duration (e.g., 150 frames at 30fps is 5 seconds). ```python from picamera2.outputs import CircularOutput output = CircularOutput(buffersize=150) ``` -------------------------------- ### Capture Frame as PIL Image Source: https://context7.com/raspberrypi/picamera2/llms.txt Captures a frame from the 'main' stream as a PIL Image object. Allows for image manipulation and saving. ```python image = picam2.capture_image("main") print(f"Image size: {image.size}, mode: {image.mode}") # Manipulate and save image = image.rotate(45) image.save("rotated.png") ``` -------------------------------- ### Capture Request with Context Manager Source: https://context7.com/raspberrypi/picamera2/llms.txt Uses a context manager to safely handle captured requests, access metadata, and modify frame buffers directly. ```python # Context manager automatically releases the request when done with picam2.captured_request() as request: # Get metadata metadata = request.get_metadata() print(f"Exposure: {metadata['ExposureTime']}us") # Make array from the request array = request.make_array("main") # Direct buffer access for in-place modification with MappedArray(request, "main") as m: # Draw a red rectangle (modifies the actual frame buffer) m.array[100:200, 100:300] = [255, 0, 0] # Save the modified image request.save("main", "modified.jpg") ``` -------------------------------- ### Capture Timelapse Images Source: https://context7.com/raspberrypi/picamera2/llms.txt Captures a series of images at fixed intervals with locked exposure and white balance for consistent lighting. Uses captured_request for efficiency. ```python # Let auto exposure/white balance settle time.sleep(1) # Lock exposure and white balance for consistent lighting picam2.set_controls({ "AeEnable": False, "AwbEnable": False, "FrameRate": 1.0 # 1 frame per second for timelapse }) time.sleep(1) start_time = time.time() for i in range(1, 51): # Use captured_request for efficient capture request = picam2.capture_request() request.save("main", f"timelapse_{i:04d}.jpg") request.release() print(f"Captured frame {i}/50 at {time.time() - start_time:.2f}s") ``` -------------------------------- ### Record Video to MP4 File with PyAV Source: https://context7.com/raspberrypi/picamera2/llms.txt Records video using the H264 encoder and PyAV output for proper MP4 container format. Ensure the bitrate is set appropriately for your needs. ```python import time from picamera2 import Picamera2 from picamera2.encoders import H264Encoder from picamera2.outputs import PyavOutput picam2 = Picamera2() video_config = picam2.create_video_configuration() picam2.configure(video_config) # Create encoder with 10 Mbps bitrate encoder = H264Encoder(bitrate=10000000) output = PyavOutput('video.mp4') picam2.start_recording(encoder, output) time.sleep(10) # Record for 10 seconds picam2.stop_recording() ``` -------------------------------- ### Capture Multiple Streams as NumPy Arrays Source: https://context7.com/raspberrypi/picamera2/llms.txt Captures frames from multiple streams simultaneously and returns them as NumPy arrays. ```python arrays, metadata = picam2.capture_arrays(["main", "lores"]) ``` -------------------------------- ### Capture Frame as NumPy Array Source: https://context7.com/raspberrypi/picamera2/llms.txt Captures a frame from the 'main' stream as a NumPy array. Useful for direct image processing. ```python array = picam2.capture_array("main") print(f"Array shape: {array.shape}, dtype: {array.dtype}") ``` -------------------------------- ### Autofocus Control Source: https://context7.com/raspberrypi/picamera2/llms.txt Provides control over autofocus functionality, primarily for cameras that support it, such as the Camera Module 3. This snippet initializes the camera and prepares for autofocus control. ```python import time from picamera2 import Picamera2 from libcamera import controls picam2 = Picamera2() picam2.configure(picam2.create_preview_configuration()) picam2.start() ``` -------------------------------- ### Circular Buffer Motion Detection Source: https://context7.com/raspberrypi/picamera2/llms.txt Captures video before and after motion is detected using a circular buffer. Requires `numpy` and `picamera2` libraries. Motion is detected by comparing consecutive frames. ```python import time import numpy as np from picamera2 import Picamera2 from picamera2.encoders import H264Encoder from picamera2.outputs import CircularOutput lsize = (320, 240) picam2 = Picamera2() video_config = picam2.create_video_configuration( main={"size": (1280, 720), "format": "RGB888"}, lores={"size": lsize, "format": "YUV420"} ) picam2.configure(video_config) # Setup circular buffer encoder encoder = H264Encoder(bitrate=1000000, repeat=True) encoder.output = CircularOutput(buffersize=5 * 30) # 5 seconds at 30fps picam2.start() picam2.start_encoder(encoder) prev = None encoding = False last_motion_time = 0 while True: # Get grayscale frame from lores stream cur = picam2.capture_array("lores")[:lsize[1], :lsize[0]] if prev is not None: # Calculate mean squared error between frames mse = np.square(np.subtract(cur, prev)).mean() if mse > 7: # Motion threshold if not encoding: # Start recording filename = f"{int(time.time())}.h264" encoder.output.fileoutput = filename encoder.output.start() encoding = True print(f"Motion detected! Recording to {filename}") last_motion_time = time.time() else: # Stop recording 5 seconds after last motion if encoding and time.time() - last_motion_time > 5.0: encoder.output.stop() encoding = False print("Recording stopped") prev = cur picam2.stop_encoder() picam2.close() ``` -------------------------------- ### Capture Multiple JPEG Images with Picamera2 Source: https://context7.com/raspberrypi/picamera2/llms.txt Capture a sequence of images with a specified delay between each capture. Useful for time-lapse photography or data collection. ```python from picamera2 import Picamera2 picam2 = Picamera2() # Capture 5 images with 0.5 second delay between them picam2.start_and_capture_files("image{:03d}.jpg", num_files=5, delay=0.5) # Creates: image000.jpg, image001.jpg, image002.jpg, image003.jpg, image004.jpg ``` -------------------------------- ### Record Raw H264 Stream Source: https://context7.com/raspberrypi/picamera2/llms.txt Records a raw H264 video stream without container formatting, suitable for later processing. The encoder is configured with a constant quality parameter. ```python import time from picamera2 import Picamera2 from picamera2.encoders import H264Encoder picam2 = Picamera2() video_config = picam2.create_video_configuration() picam2.configure(video_config) # H264 encoder with constant quality parameter encoder = H264Encoder(bitrate=10000000) picam2.start_recording(encoder, 'video.h264') time.sleep(10) picam2.stop_recording() ``` -------------------------------- ### Control Frame Rate Source: https://context7.com/raspberrypi/picamera2/llms.txt Sets fixed or variable frame rate limits for video recording. The frame duration is specified in microseconds. ```python from picamera2 import Picamera2 picam2 = Picamera2() # Fixed 30fps (frame duration in microseconds: 1000000/30 = 33333) config = picam2.create_video_configuration( controls={"FrameDurationLimits": (33333, 33333)} ) picam2.configure(config) picam2.start() # Variable frame rate between 15-60fps picam2.set_controls({"FrameDurationLimits": (16666, 66666)}) ``` -------------------------------- ### TCP H264 Stream Server Source: https://context7.com/raspberrypi/picamera2/llms.txt Streams H264 video over a TCP socket to network clients. Requires `socket` and `picamera2` libraries. The server binds to all interfaces on port 10001 and listens for connections. ```python import socket import time from picamera2 import Picamera2 from picamera2.encoders import H264Encoder from picamera2.outputs import FileOutput picam2 = Picamera2() video_config = picam2.create_video_configuration({"size": (1280, 720)}) picam2.configure(video_config) encoder = H264Encoder(bitrate=1000000) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(("0.0.0.0", 10001)) sock.listen() print("Waiting for client connection on port 10001...") conn, addr = sock.accept() print(f"Client connected: {addr}") stream = conn.makefile("wb") encoder.output = FileOutput(stream) picam2.start_encoder(encoder) picam2.start() time.sleep(20) # Stream for 20 seconds picam2.stop() picam2.stop_encoder() conn.close() # Client can view with: ffplay tcp://:10001 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.