0
# Configuration & Options
1
2
Device option management with support for camera parameters, processing settings, and hardware features. Provides range validation, real-time adjustment capabilities, and comprehensive device configuration.
3
4
## Capabilities
5
6
### Options Interface
7
8
Base interface for device and filter option management.
9
10
```python { .api }
11
class options:
12
def supports(option) -> bool:
13
"""
14
Check if option is supported.
15
16
Args:
17
option (option): Option to check
18
19
Returns:
20
bool: True if option is supported
21
"""
22
23
def is_option_read_only(option) -> bool:
24
"""
25
Check if option is read-only.
26
27
Args:
28
option (option): Option to check
29
30
Returns:
31
bool: True if option is read-only
32
"""
33
34
def get_option_description(option) -> str:
35
"""
36
Get human-readable option description.
37
38
Args:
39
option (option): Option to describe
40
41
Returns:
42
str: Option description
43
"""
44
45
def get_option_value_description(option, value) -> str:
46
"""
47
Get description for specific option value.
48
49
Args:
50
option (option): Option type
51
value (float): Option value
52
53
Returns:
54
str: Value description
55
"""
56
57
def get_supported_options() -> options_list:
58
"""
59
Get list of all supported options.
60
61
Returns:
62
options_list: Collection of supported options
63
"""
64
65
def get_option(option) -> float:
66
"""
67
Get current option value.
68
69
Args:
70
option (option): Option to retrieve
71
72
Returns:
73
float: Current option value
74
75
Raises:
76
rs.error: If option not supported
77
"""
78
79
def get_option_value(option) -> option_value:
80
"""
81
Get typed option value.
82
83
Args:
84
option (option): Option to retrieve
85
86
Returns:
87
option_value: Typed option value
88
"""
89
90
def set_option(option, value):
91
"""
92
Set option value.
93
94
Args:
95
option (option): Option to set
96
value (float): New option value
97
98
Raises:
99
rs.error: If option not supported or value invalid
100
"""
101
102
def set_option_value(option, value):
103
"""
104
Set option using JSON-compatible value.
105
106
Args:
107
option (option): Option to set
108
value: New value (Python object)
109
"""
110
111
def get_option_range(option) -> option_range:
112
"""
113
Get valid range for option.
114
115
Args:
116
option (option): Option to query
117
118
Returns:
119
option_range: Valid value range
120
"""
121
122
def on_options_changed(callback):
123
"""
124
Set callback for option change notifications.
125
126
Args:
127
callback: Function called when options change
128
"""
129
```
130
131
### Option Data Types
132
133
Data structures for option management and validation.
134
135
```python { .api }
136
class option_range:
137
min: float # Minimum valid value
138
max: float # Maximum valid value
139
step: float # Step size for discrete values
140
default: float # Default value
141
142
class option_value:
143
id: option # Option identifier
144
type: option_type # Value type (int, float, string, bool)
145
value: object # Python value (None if invalid)
146
147
class options_list:
148
def __len__() -> int:
149
"""Number of options in list."""
150
151
def __getitem__(index) -> option_value:
152
"""Get option by index."""
153
154
def __iter__():
155
"""Iterate over options."""
156
```
157
158
### Region of Interest
159
160
Spatial region configuration for processing focus.
161
162
```python { .api }
163
class region_of_interest:
164
min_x: int # Left boundary
165
min_y: int # Top boundary
166
max_x: int # Right boundary
167
max_y: int # Bottom boundary
168
```
169
170
## Common Device Options
171
172
### Camera Control Options
173
174
```python { .api }
175
# Exposure control
176
rs.option.exposure # Exposure time in microseconds
177
rs.option.auto_exposure # Auto exposure enable/disable
178
rs.option.gain # Analog gain value
179
rs.option.white_balance # White balance temperature
180
rs.option.enable_auto_white_balance # Auto white balance enable/disable
181
182
# Image quality
183
rs.option.brightness # Image brightness
184
rs.option.contrast # Image contrast
185
rs.option.saturation # Color saturation
186
rs.option.hue # Color hue
187
rs.option.sharpness # Image sharpness
188
rs.option.gamma # Gamma correction
189
190
# Advanced controls
191
rs.option.backlight_compensation # Backlight compensation
192
rs.option.power_line_frequency # Power line frequency filter
193
rs.option.low_light_compensation # Low light compensation
194
```
195
196
### Depth Processing Options
197
198
```python { .api }
199
# Depth accuracy
200
rs.option.accuracy # Depth accuracy preset
201
rs.option.motion_range # Motion vs accuracy tradeoff
202
rs.option.filter_option # Depth filter strength
203
rs.option.confidence_threshold # Confidence threshold
204
205
# Depth range
206
rs.option.min_distance # Minimum depth distance
207
rs.option.max_distance # Maximum depth distance
208
209
# Laser control
210
rs.option.laser_power # Laser projector power
211
rs.option.projector_temperature # Projector temperature
212
rs.option.output_trigger # External trigger output
213
rs.option.depth_units # Depth measurement units
214
```
215
216
### Stereo Processing Options
217
218
```python { .api }
219
# Stereo matching
220
rs.option.stereo_baseline # Stereo baseline distance
221
rs.option.inter_cam_sync_mode # Inter-camera synchronization
222
rs.option.emitter_enabled # IR emitter enable/disable
223
rs.option.global_time_enabled # Global timestamp enable
224
```
225
226
### Filter Options
227
228
```python { .api }
229
# Spatial filtering
230
rs.option.filter_magnitude # Filter effect magnitude
231
rs.option.filter_smooth_alpha # Smoothing alpha factor
232
rs.option.filter_smooth_delta # Edge-preserving delta threshold
233
234
# Temporal filtering
235
rs.option.holes_fill # Hole filling method
236
rs.option.filter_option # General filter option
237
238
# Decimation
239
rs.option.filter_magnitude # Decimation factor (reused)
240
```
241
242
## Usage Examples
243
244
### Basic Option Management
245
246
```python
247
import pyrealsense2 as rs
248
249
# Get device and sensor
250
ctx = rs.context()
251
device = ctx.query_devices()[0]
252
sensor = device.first_color_sensor() # or first_depth_sensor()
253
254
print(f"Device: {device.get_info(rs.camera_info.name)}")
255
print(f"Sensor: {sensor.get_info(rs.camera_info.name)}")
256
257
# List all supported options
258
options_list = sensor.get_supported_options()
259
print(f"\nSupported options ({len(options_list)}):")
260
261
for option_value in options_list:
262
option = option_value.id
263
current_value = option_value.value
264
265
print(f" {option.name}: {current_value}")
266
267
# Get option details
268
if sensor.supports(option):
269
try:
270
description = sensor.get_option_description(option)
271
range_info = sensor.get_option_range(option)
272
is_readonly = sensor.is_option_read_only(option)
273
274
print(f" Description: {description}")
275
print(f" Range: {range_info.min} - {range_info.max} (step: {range_info.step})")
276
print(f" Default: {range_info.default}")
277
print(f" Read-only: {is_readonly}")
278
279
except rs.error as e:
280
print(f" Error getting details: {e}")
281
```
282
283
### Camera Settings Configuration
284
285
```python
286
import pyrealsense2 as rs
287
288
ctx = rs.context()
289
device = ctx.query_devices()[0]
290
color_sensor = device.first_color_sensor()
291
292
print("Configuring camera settings...")
293
294
# Set manual exposure
295
if color_sensor.supports(rs.option.exposure):
296
# Disable auto exposure first
297
if color_sensor.supports(rs.option.auto_exposure):
298
color_sensor.set_option(rs.option.auto_exposure, False)
299
print("Disabled auto exposure")
300
301
# Set manual exposure value
302
exposure_range = color_sensor.get_option_range(rs.option.exposure)
303
target_exposure = min(10000, exposure_range.max) # 10ms or max available
304
color_sensor.set_option(rs.option.exposure, target_exposure)
305
print(f"Set exposure to {target_exposure} microseconds")
306
307
# Set manual white balance
308
if color_sensor.supports(rs.option.white_balance):
309
if color_sensor.supports(rs.option.enable_auto_white_balance):
310
color_sensor.set_option(rs.option.enable_auto_white_balance, False)
311
print("Disabled auto white balance")
312
313
# Set white balance temperature
314
wb_range = color_sensor.get_option_range(rs.option.white_balance)
315
color_sensor.set_option(rs.option.white_balance, 4600) # Daylight ~4600K
316
print("Set white balance to 4600K")
317
318
# Adjust image quality settings
319
quality_options = [
320
(rs.option.brightness, 0), # Neutral brightness
321
(rs.option.contrast, 50), # Moderate contrast
322
(rs.option.saturation, 64), # Default saturation
323
(rs.option.sharpness, 50) # Moderate sharpening
324
]
325
326
for option, value in quality_options:
327
if color_sensor.supports(option):
328
color_sensor.set_option(option, value)
329
print(f"Set {option.name} to {value}")
330
331
print("Camera configuration completed")
332
```
333
334
### Depth Sensor Configuration
335
336
```python
337
import pyrealsense2 as rs
338
339
ctx = rs.context()
340
device = ctx.query_devices()[0]
341
depth_sensor = device.first_depth_sensor()
342
343
print("Configuring depth sensor...")
344
345
# Configure depth accuracy and range
346
depth_options = [
347
(rs.option.min_distance, 0.1), # 10cm minimum
348
(rs.option.max_distance, 5.0), # 5m maximum
349
(rs.option.confidence_threshold, 2), # Medium confidence
350
]
351
352
for option, value in depth_options:
353
if depth_sensor.supports(option):
354
try:
355
# Check if value is in valid range
356
range_info = depth_sensor.get_option_range(option)
357
if range_info.min <= value <= range_info.max:
358
depth_sensor.set_option(option, value)
359
print(f"Set {option.name} to {value}")
360
else:
361
print(f"Value {value} out of range for {option.name} "
362
f"({range_info.min}-{range_info.max})")
363
except rs.error as e:
364
print(f"Error setting {option.name}: {e}")
365
366
# Configure laser power if available
367
if depth_sensor.supports(rs.option.laser_power):
368
laser_range = depth_sensor.get_option_range(rs.option.laser_power)
369
# Set to 75% of maximum power
370
laser_power = laser_range.min + (laser_range.max - laser_range.min) * 0.75
371
depth_sensor.set_option(rs.option.laser_power, laser_power)
372
print(f"Set laser power to {laser_power:.1f}")
373
374
# Configure emitter if available
375
if depth_sensor.supports(rs.option.emitter_enabled):
376
depth_sensor.set_option(rs.option.emitter_enabled, True)
377
print("Enabled IR emitter")
378
379
print("Depth sensor configuration completed")
380
```
381
382
### Filter Option Configuration
383
384
```python
385
import pyrealsense2 as rs
386
387
# Create filters
388
decimation = rs.decimation_filter()
389
spatial = rs.spatial_filter()
390
temporal = rs.temporal_filter()
391
hole_filling = rs.hole_filling_filter()
392
393
print("Configuring filter options...")
394
395
# Configure decimation filter
396
if decimation.supports(rs.option.filter_magnitude):
397
decimation.set_option(rs.option.filter_magnitude, 2.0)
398
print("Set decimation magnitude to 2.0")
399
400
# Configure spatial filter for aggressive noise reduction
401
spatial_config = [
402
(rs.option.filter_magnitude, 4.0), # Strong filtering
403
(rs.option.filter_smooth_alpha, 0.7), # High smoothing
404
(rs.option.filter_smooth_delta, 15.0), # Edge preservation
405
(rs.option.holes_fill, 3.0) # Fill holes
406
]
407
408
for option, value in spatial_config:
409
if spatial.supports(option):
410
spatial.set_option(option, value)
411
print(f"Set spatial {option.name} to {value}")
412
413
# Configure temporal filter
414
temporal_config = [
415
(rs.option.filter_smooth_alpha, 0.3), # Moderate smoothing
416
(rs.option.filter_smooth_delta, 40.0), # Edge preservation
417
(rs.option.holes_fill, 4) # Persistence control
418
]
419
420
for option, value in temporal_config:
421
if temporal.supports(option):
422
temporal.set_option(option, value)
423
print(f"Set temporal {option.name} to {value}")
424
425
# Configure hole filling method
426
if hole_filling.supports(rs.option.holes_fill):
427
hole_filling.set_option(rs.option.holes_fill, 2) # nearest_from_around
428
print("Set hole filling to nearest_from_around")
429
430
print("Filter configuration completed")
431
432
# Apply filters to demonstrate configured settings
433
pipeline = rs.pipeline()
434
config = rs.config()
435
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
436
437
pipeline.start(config)
438
439
try:
440
frames = pipeline.wait_for_frames()
441
depth_frame = frames.get_depth_frame()
442
443
if depth_frame:
444
# Apply configured filter chain
445
filtered = decimation.process(depth_frame)
446
filtered = spatial.process(filtered)
447
filtered = temporal.process(filtered)
448
filtered = hole_filling.process(filtered)
449
450
original_size = f"{depth_frame.get_width()}x{depth_frame.get_height()}"
451
filtered_size = f"{filtered.get_width()}x{filtered.get_height()}"
452
453
print(f"Applied filters: {original_size} -> {filtered_size}")
454
455
finally:
456
pipeline.stop()
457
```
458
459
### Advanced Option Management
460
461
```python
462
import pyrealsense2 as rs
463
import json
464
465
class DeviceConfigurator:
466
def __init__(self, device):
467
self.device = device
468
self.sensors = device.query_sensors()
469
470
def save_configuration(self, filename):
471
"""Save current device configuration to JSON file."""
472
config = {}
473
474
for i, sensor in enumerate(self.sensors):
475
sensor_name = f"sensor_{i}"
476
if sensor.supports(rs.camera_info.name):
477
sensor_name = sensor.get_info(rs.camera_info.name).replace(" ", "_")
478
479
sensor_config = {}
480
options_list = sensor.get_supported_options()
481
482
for option_value in options_list:
483
option = option_value.id
484
if sensor.supports(option):
485
try:
486
current_value = sensor.get_option(option)
487
sensor_config[option.name] = {
488
'value': current_value,
489
'type': option_value.type.name
490
}
491
except rs.error:
492
pass # Skip options that can't be read
493
494
config[sensor_name] = sensor_config
495
496
with open(filename, 'w') as f:
497
json.dump(config, f, indent=2)
498
499
print(f"Configuration saved to {filename}")
500
501
def load_configuration(self, filename):
502
"""Load device configuration from JSON file."""
503
try:
504
with open(filename, 'r') as f:
505
config = json.load(f)
506
507
for sensor_name, sensor_config in config.items():
508
# Find matching sensor
509
sensor = self._find_sensor_by_name(sensor_name)
510
if not sensor:
511
print(f"Sensor {sensor_name} not found, skipping")
512
continue
513
514
print(f"Configuring {sensor_name}...")
515
516
for option_name, option_info in sensor_config.items():
517
try:
518
# Find option enum by name
519
option = self._find_option_by_name(option_name)
520
if option and sensor.supports(option):
521
value = option_info['value']
522
sensor.set_option(option, value)
523
print(f" Set {option_name} to {value}")
524
else:
525
print(f" Option {option_name} not supported")
526
except Exception as e:
527
print(f" Error setting {option_name}: {e}")
528
529
print("Configuration loaded successfully")
530
531
except FileNotFoundError:
532
print(f"Configuration file {filename} not found")
533
except Exception as e:
534
print(f"Error loading configuration: {e}")
535
536
def _find_sensor_by_name(self, sensor_name):
537
"""Find sensor by name."""
538
for sensor in self.sensors:
539
if sensor.supports(rs.camera_info.name):
540
name = sensor.get_info(rs.camera_info.name).replace(" ", "_")
541
if name == sensor_name:
542
return sensor
543
return None
544
545
def _find_option_by_name(self, option_name):
546
"""Find option enum by name."""
547
# This is a simplified approach - in practice you'd have a mapping
548
for option in rs.option:
549
if option.name == option_name:
550
return option
551
return None
552
553
def print_current_configuration(self):
554
"""Print current device configuration."""
555
print(f"Device: {self.device.get_info(rs.camera_info.name)}")
556
557
for i, sensor in enumerate(self.sensors):
558
sensor_name = f"Sensor {i}"
559
if sensor.supports(rs.camera_info.name):
560
sensor_name = sensor.get_info(rs.camera_info.name)
561
562
print(f"\n{sensor_name}:")
563
564
options_list = sensor.get_supported_options()
565
for option_value in options_list:
566
option = option_value.id
567
current_value = option_value.value
568
569
if sensor.supports(option):
570
try:
571
range_info = sensor.get_option_range(option)
572
print(f" {option.name}: {current_value} "
573
f"(range: {range_info.min}-{range_info.max})")
574
except rs.error:
575
print(f" {option.name}: {current_value}")
576
577
# Usage example
578
ctx = rs.context()
579
device = ctx.query_devices()[0]
580
581
configurator = DeviceConfigurator(device)
582
583
# Print current configuration
584
configurator.print_current_configuration()
585
586
# Save configuration
587
configurator.save_configuration("device_config.json")
588
589
# Modify some settings
590
color_sensor = device.first_color_sensor()
591
if color_sensor.supports(rs.option.brightness):
592
color_sensor.set_option(rs.option.brightness, 10)
593
594
# Load original configuration
595
configurator.load_configuration("device_config.json")
596
```
597
598
### Option Change Monitoring
599
600
```python
601
import pyrealsense2 as rs
602
import time
603
604
class OptionMonitor:
605
def __init__(self, sensor):
606
self.sensor = sensor
607
self.monitored_options = []
608
self.last_values = {}
609
610
def add_option(self, option):
611
"""Add option to monitoring list."""
612
if self.sensor.supports(option):
613
self.monitored_options.append(option)
614
self.last_values[option] = self.sensor.get_option(option)
615
print(f"Monitoring {option.name}")
616
else:
617
print(f"Option {option.name} not supported")
618
619
def check_changes(self):
620
"""Check for option value changes."""
621
changes = []
622
623
for option in self.monitored_options:
624
try:
625
current_value = self.sensor.get_option(option)
626
last_value = self.last_values[option]
627
628
if abs(current_value - last_value) > 0.001: # Threshold for change
629
changes.append((option, last_value, current_value))
630
self.last_values[option] = current_value
631
632
except rs.error:
633
pass # Skip if option can't be read
634
635
return changes
636
637
def print_changes(self, changes):
638
"""Print option changes."""
639
if changes:
640
print("Option changes detected:")
641
for option, old_value, new_value in changes:
642
print(f" {option.name}: {old_value:.3f} -> {new_value:.3f}")
643
644
# Example usage
645
ctx = rs.context()
646
device = ctx.query_devices()[0]
647
color_sensor = device.first_color_sensor()
648
649
monitor = OptionMonitor(color_sensor)
650
651
# Monitor key options
652
options_to_monitor = [
653
rs.option.exposure,
654
rs.option.gain,
655
rs.option.white_balance,
656
rs.option.brightness,
657
rs.option.contrast
658
]
659
660
for option in options_to_monitor:
661
monitor.add_option(option)
662
663
print("Starting option monitoring (modify camera settings to see changes)...")
664
665
# Monitor for changes
666
for i in range(100): # Monitor for ~10 seconds
667
changes = monitor.check_changes()
668
monitor.print_changes(changes)
669
670
# Simulate some changes every 30 iterations
671
if i % 30 == 0 and i > 0:
672
if color_sensor.supports(rs.option.brightness):
673
new_brightness = (i // 30) * 10 # Cycle through values
674
color_sensor.set_option(rs.option.brightness, new_brightness)
675
print(f"Changed brightness to {new_brightness}")
676
677
time.sleep(0.1)
678
```
679
680
## Option Categories
681
682
### Camera Control
683
- Exposure, gain, white balance
684
- Image quality (brightness, contrast, saturation)
685
- Auto-control enables/disables
686
687
### Depth Processing
688
- Accuracy vs performance tradeoffs
689
- Depth range limits
690
- Confidence thresholds
691
692
### Hardware Control
693
- Laser power and emitter control
694
- Temperature monitoring
695
- Synchronization settings
696
697
### Filter Configuration
698
- Noise reduction parameters
699
- Edge preservation settings
700
- Hole filling methods
701
702
### Advanced Features
703
- Region of interest
704
- External triggers
705
- Power management