0
# Image and Video Capture
1
2
Comprehensive capture functionality supporting various output formats, synchronous and asynchronous operations, and different data types. The capture system provides both high-level convenience methods and low-level control for advanced applications.
3
4
## Capabilities
5
6
### File Capture
7
8
Direct capture to files with automatic format detection and encoding.
9
10
```python { .api }
11
def capture_file(
12
self,
13
file_output: str,
14
name: str = "main",
15
format: str = None,
16
wait: bool = True,
17
signal_function: callable = None,
18
exif_data: dict = None
19
):
20
"""
21
Capture image directly to file.
22
23
Parameters:
24
- file_output: str, output file path
25
- name: str, stream name to capture ("main", "lores", "raw")
26
- format: str, output format (auto-detected from filename if None)
27
- wait: bool, wait for capture completion
28
- signal_function: callable, completion callback
29
- exif_data: dict, EXIF metadata for JPEG files
30
31
Returns:
32
Job object if wait=False, None if wait=True
33
"""
34
```
35
36
### Array Capture
37
38
Capture images as numpy arrays for image processing and analysis.
39
40
```python { .api }
41
def capture_array(
42
self,
43
name: str = "main",
44
wait: bool = True,
45
signal_function: callable = None
46
) -> np.ndarray:
47
"""
48
Capture image as numpy array.
49
50
Parameters:
51
- name: str, stream name to capture
52
- wait: bool, wait for capture completion
53
- signal_function: callable, completion callback
54
55
Returns:
56
np.ndarray: Image data with shape appropriate for format
57
"""
58
59
def capture_arrays(
60
self,
61
names: list[str] = None,
62
wait: bool = True,
63
signal_function: callable = None
64
) -> dict[str, np.ndarray]:
65
"""
66
Capture multiple streams as numpy arrays.
67
68
Parameters:
69
- names: list, stream names to capture (default: all active streams)
70
- wait: bool, wait for capture completion
71
- signal_function: callable, completion callback
72
73
Returns:
74
dict: Stream names mapped to numpy arrays
75
"""
76
```
77
78
### Image Capture
79
80
Capture images as PIL Image objects for easy manipulation and saving.
81
82
```python { .api }
83
def capture_image(
84
self,
85
name: str = "main",
86
wait: bool = True,
87
signal_function: callable = None
88
) -> PIL.Image.Image:
89
"""
90
Capture image as PIL Image object.
91
92
Parameters:
93
- name: str, stream name to capture
94
- wait: bool, wait for capture completion
95
- signal_function: callable, completion callback
96
97
Returns:
98
PIL.Image.Image: PIL Image object
99
"""
100
```
101
102
### Buffer Capture
103
104
Low-level buffer capture for direct memory access and custom processing.
105
106
```python { .api }
107
def capture_buffer(
108
self,
109
name: str = "main",
110
wait: bool = True,
111
signal_function: callable = None
112
) -> bytes:
113
"""
114
Capture raw buffer data.
115
116
Parameters:
117
- name: str, stream name to capture
118
- wait: bool, wait for capture completion
119
- signal_function: callable, completion callback
120
121
Returns:
122
bytes: Raw buffer data
123
"""
124
125
def capture_buffers(
126
self,
127
names: list[str] = None,
128
wait: bool = True,
129
signal_function: callable = None
130
) -> dict[str, bytes]:
131
"""
132
Capture multiple streams as raw buffers.
133
134
Parameters:
135
- names: list, stream names to capture
136
- wait: bool, wait for capture completion
137
- signal_function: callable, completion callback
138
139
Returns:
140
dict: Stream names mapped to buffer data
141
"""
142
```
143
144
### Request Capture
145
146
Advanced capture interface providing access to complete request objects with metadata.
147
148
```python { .api }
149
def capture_request(
150
self,
151
wait: bool = True,
152
signal_function: callable = None,
153
flush: bool = False
154
) -> CompletedRequest:
155
"""
156
Capture complete request with all streams and metadata.
157
158
Parameters:
159
- wait: bool, wait for capture completion
160
- signal_function: callable, completion callback
161
- flush: bool, flush pending requests before capture
162
163
Returns:
164
CompletedRequest: Complete request object with all stream data
165
"""
166
167
def capture_metadata(
168
self,
169
wait: bool = True,
170
signal_function: callable = None
171
) -> dict:
172
"""
173
Capture only metadata without image data.
174
175
Parameters:
176
- wait: bool, wait for capture completion
177
- signal_function: callable, completion callback
178
179
Returns:
180
dict: Camera metadata
181
"""
182
```
183
184
### Convenience Capture Methods
185
186
High-level methods combining common capture operations.
187
188
```python { .api }
189
def start_and_capture_file(
190
self,
191
name: str,
192
delay: float = 1,
193
preview_mode: bool = None,
194
show_preview: bool = None,
195
initial_delay: float = None,
196
exif_data: dict = None
197
):
198
"""
199
Start camera and capture single file with delay.
200
201
Parameters:
202
- name: str, output filename
203
- delay: float, delay before capture (seconds)
204
- preview_mode: bool, use preview configuration
205
- show_preview: bool, show preview window
206
- initial_delay: float, initial settling delay
207
- exif_data: dict, EXIF metadata
208
"""
209
210
def start_and_capture_files(
211
self,
212
name: str,
213
delay: float = 1,
214
preview_mode: bool = None,
215
initial_delay: float = None,
216
num_files: int = 1,
217
show_preview: bool = None
218
):
219
"""
220
Start camera and capture multiple files with delay.
221
222
Parameters:
223
- name: str, output filename pattern
224
- delay: float, delay between captures
225
- preview_mode: bool, use preview configuration
226
- initial_delay: float, initial settling delay
227
- num_files: int, number of files to capture
228
- show_preview: bool, show preview window
229
"""
230
```
231
232
### CompletedRequest Class
233
234
Object representing a completed camera request with access to all stream data and metadata.
235
236
```python { .api }
237
class CompletedRequest:
238
"""Completed camera request with stream data and metadata."""
239
240
request: libcamera.Request # Underlying libcamera request
241
config: CameraConfiguration # Configuration snapshot
242
stream_map: dict # Stream mapping information
243
244
def acquire(self):
245
"""Acquire reference to prevent request recycling."""
246
247
def release(self):
248
"""Release reference, allowing request recycling."""
249
250
def make_buffer(self, name: str = "main") -> bytes:
251
"""
252
Create buffer from stream data.
253
254
Parameters:
255
- name: str, stream name
256
257
Returns:
258
bytes: Raw buffer data
259
"""
260
261
def make_array(self, name: str = "main") -> np.ndarray:
262
"""
263
Create numpy array from stream data.
264
265
Parameters:
266
- name: str, stream name
267
268
Returns:
269
np.ndarray: Image array with appropriate shape
270
"""
271
272
def make_image(
273
self,
274
name: str = "main",
275
width: int = None,
276
height: int = None
277
) -> PIL.Image.Image:
278
"""
279
Create PIL Image from stream data.
280
281
Parameters:
282
- name: str, stream name
283
- width: int, override width
284
- height: int, override height
285
286
Returns:
287
PIL.Image.Image: PIL Image object
288
"""
289
290
def save(
291
self,
292
name: str,
293
file_output: str,
294
format: str = None,
295
exif_data: dict = None
296
):
297
"""
298
Save stream data to file.
299
300
Parameters:
301
- name: str, stream name
302
- file_output: str, output file path
303
- format: str, output format
304
- exif_data: dict, EXIF metadata
305
"""
306
307
def save_dng(self, file_output: str, name: str = "raw"):
308
"""
309
Save raw stream as DNG file.
310
311
Parameters:
312
- file_output: str, output DNG file path
313
- name: str, raw stream name
314
"""
315
316
def get_metadata(self) -> dict:
317
"""
318
Get request metadata.
319
320
Returns:
321
dict: Camera metadata for this request
322
"""
323
```
324
325
## Usage Examples
326
327
### Basic File Capture
328
329
```python
330
from picamera2 import Picamera2
331
332
picam2 = Picamera2()
333
picam2.configure(picam2.create_still_configuration())
334
picam2.start()
335
336
# Simple file capture
337
picam2.capture_file("image.jpg")
338
339
# Multiple format capture
340
picam2.capture_file("image.png", format="PNG")
341
picam2.capture_file("image.tiff", format="TIFF")
342
343
picam2.close()
344
```
345
346
### Array Processing
347
348
```python
349
from picamera2 import Picamera2
350
import numpy as np
351
import cv2
352
353
picam2 = Picamera2()
354
config = picam2.create_preview_configuration(
355
main={"format": "RGB888", "size": (640, 480)}
356
)
357
picam2.configure(config)
358
picam2.start()
359
360
# Capture as numpy array
361
array = picam2.capture_array()
362
print(f"Array shape: {array.shape}, dtype: {array.dtype}")
363
364
# Process with OpenCV
365
gray = cv2.cvtColor(array, cv2.COLOR_RGB2GRAY)
366
edges = cv2.Canny(gray, 100, 200)
367
368
# Save processed result
369
cv2.imwrite("edges.jpg", edges)
370
371
picam2.close()
372
```
373
374
### Multi-Stream Capture
375
376
```python
377
from picamera2 import Picamera2
378
379
picam2 = Picamera2()
380
config = picam2.create_video_configuration(
381
main={"size": (1920, 1080), "format": "YUV420"},
382
lores={"size": (640, 480), "format": "YUV420"}
383
)
384
picam2.configure(config)
385
picam2.start()
386
387
# Capture both streams simultaneously
388
arrays = picam2.capture_arrays(["main", "lores"])
389
print(f"Main: {arrays['main'].shape}")
390
print(f"Lores: {arrays['lores'].shape}")
391
392
# Process each stream differently
393
high_res = arrays["main"]
394
low_res = arrays["lores"]
395
396
picam2.close()
397
```
398
399
### Advanced Request Processing
400
401
```python
402
from picamera2 import Picamera2
403
404
picam2 = Picamera2()
405
config = picam2.create_still_configuration()
406
picam2.configure(config)
407
picam2.start()
408
409
# Capture complete request
410
request = picam2.capture_request()
411
412
# Access metadata
413
metadata = request.get_metadata()
414
print(f"Exposure time: {metadata.get('ExposureTime', 'Unknown')}")
415
print(f"Analog gain: {metadata.get('AnalogueGain', 'Unknown')}")
416
417
# Process multiple representations
418
array = request.make_array("main")
419
image = request.make_image("main")
420
421
# Save with metadata
422
request.save("main", "output.jpg", format="JPEG")
423
424
# Important: release request when done
425
request.release()
426
427
picam2.close()
428
```
429
430
### Asynchronous Capture
431
432
```python
433
from picamera2 import Picamera2
434
import time
435
436
def capture_complete(job):
437
print(f"Capture completed: {job.result()}")
438
439
picam2 = Picamera2()
440
picam2.configure(picam2.create_preview_configuration())
441
picam2.start()
442
443
# Start non-blocking capture
444
job = picam2.capture_file("async_image.jpg", wait=False,
445
signal_function=capture_complete)
446
447
# Do other work while capture proceeds
448
print("Doing other work...")
449
time.sleep(0.1)
450
451
# Wait for completion if needed
452
if not job.finished:
453
job.wait()
454
455
picam2.close()
456
```
457
458
### Burst Capture
459
460
```python
461
from picamera2 import Picamera2
462
import time
463
464
picam2 = Picamera2()
465
picam2.configure(picam2.create_still_configuration())
466
picam2.start()
467
468
# Rapid burst capture
469
for i in range(10):
470
filename = f"burst_{i:03d}.jpg"
471
picam2.capture_file(filename)
472
time.sleep(0.1) # Small delay between captures
473
474
# Or use convenience method
475
picam2.start_and_capture_files("sequence_{:03d}.jpg",
476
delay=0.5, num_files=5)
477
478
picam2.close()
479
```