Python bindings for Intel RealSense SDK 2.0 providing access to depth and color cameras for computer vision applications.
—
Device option management with support for camera parameters, processing settings, and hardware features. Provides range validation, real-time adjustment capabilities, and comprehensive device configuration.
Base interface for device and filter option management.
class options:
def supports(option) -> bool:
"""
Check if option is supported.
Args:
option (option): Option to check
Returns:
bool: True if option is supported
"""
def is_option_read_only(option) -> bool:
"""
Check if option is read-only.
Args:
option (option): Option to check
Returns:
bool: True if option is read-only
"""
def get_option_description(option) -> str:
"""
Get human-readable option description.
Args:
option (option): Option to describe
Returns:
str: Option description
"""
def get_option_value_description(option, value) -> str:
"""
Get description for specific option value.
Args:
option (option): Option type
value (float): Option value
Returns:
str: Value description
"""
def get_supported_options() -> options_list:
"""
Get list of all supported options.
Returns:
options_list: Collection of supported options
"""
def get_option(option) -> float:
"""
Get current option value.
Args:
option (option): Option to retrieve
Returns:
float: Current option value
Raises:
rs.error: If option not supported
"""
def get_option_value(option) -> option_value:
"""
Get typed option value.
Args:
option (option): Option to retrieve
Returns:
option_value: Typed option value
"""
def set_option(option, value):
"""
Set option value.
Args:
option (option): Option to set
value (float): New option value
Raises:
rs.error: If option not supported or value invalid
"""
def set_option_value(option, value):
"""
Set option using JSON-compatible value.
Args:
option (option): Option to set
value: New value (Python object)
"""
def get_option_range(option) -> option_range:
"""
Get valid range for option.
Args:
option (option): Option to query
Returns:
option_range: Valid value range
"""
def on_options_changed(callback):
"""
Set callback for option change notifications.
Args:
callback: Function called when options change
"""Data structures for option management and validation.
class option_range:
min: float # Minimum valid value
max: float # Maximum valid value
step: float # Step size for discrete values
default: float # Default value
class option_value:
id: option # Option identifier
type: option_type # Value type (int, float, string, bool)
value: object # Python value (None if invalid)
class options_list:
def __len__() -> int:
"""Number of options in list."""
def __getitem__(index) -> option_value:
"""Get option by index."""
def __iter__():
"""Iterate over options."""Spatial region configuration for processing focus.
class region_of_interest:
min_x: int # Left boundary
min_y: int # Top boundary
max_x: int # Right boundary
max_y: int # Bottom boundary# Exposure control
rs.option.exposure # Exposure time in microseconds
rs.option.auto_exposure # Auto exposure enable/disable
rs.option.gain # Analog gain value
rs.option.white_balance # White balance temperature
rs.option.enable_auto_white_balance # Auto white balance enable/disable
# Image quality
rs.option.brightness # Image brightness
rs.option.contrast # Image contrast
rs.option.saturation # Color saturation
rs.option.hue # Color hue
rs.option.sharpness # Image sharpness
rs.option.gamma # Gamma correction
# Advanced controls
rs.option.backlight_compensation # Backlight compensation
rs.option.power_line_frequency # Power line frequency filter
rs.option.low_light_compensation # Low light compensation# Depth accuracy
rs.option.accuracy # Depth accuracy preset
rs.option.motion_range # Motion vs accuracy tradeoff
rs.option.filter_option # Depth filter strength
rs.option.confidence_threshold # Confidence threshold
# Depth range
rs.option.min_distance # Minimum depth distance
rs.option.max_distance # Maximum depth distance
# Laser control
rs.option.laser_power # Laser projector power
rs.option.projector_temperature # Projector temperature
rs.option.output_trigger # External trigger output
rs.option.depth_units # Depth measurement units# Stereo matching
rs.option.stereo_baseline # Stereo baseline distance
rs.option.inter_cam_sync_mode # Inter-camera synchronization
rs.option.emitter_enabled # IR emitter enable/disable
rs.option.global_time_enabled # Global timestamp enable# Spatial filtering
rs.option.filter_magnitude # Filter effect magnitude
rs.option.filter_smooth_alpha # Smoothing alpha factor
rs.option.filter_smooth_delta # Edge-preserving delta threshold
# Temporal filtering
rs.option.holes_fill # Hole filling method
rs.option.filter_option # General filter option
# Decimation
rs.option.filter_magnitude # Decimation factor (reused)import pyrealsense2 as rs
# Get device and sensor
ctx = rs.context()
device = ctx.query_devices()[0]
sensor = device.first_color_sensor() # or first_depth_sensor()
print(f"Device: {device.get_info(rs.camera_info.name)}")
print(f"Sensor: {sensor.get_info(rs.camera_info.name)}")
# List all supported options
options_list = sensor.get_supported_options()
print(f"\nSupported options ({len(options_list)}):")
for option_value in options_list:
option = option_value.id
current_value = option_value.value
print(f" {option.name}: {current_value}")
# Get option details
if sensor.supports(option):
try:
description = sensor.get_option_description(option)
range_info = sensor.get_option_range(option)
is_readonly = sensor.is_option_read_only(option)
print(f" Description: {description}")
print(f" Range: {range_info.min} - {range_info.max} (step: {range_info.step})")
print(f" Default: {range_info.default}")
print(f" Read-only: {is_readonly}")
except rs.error as e:
print(f" Error getting details: {e}")import pyrealsense2 as rs
ctx = rs.context()
device = ctx.query_devices()[0]
color_sensor = device.first_color_sensor()
print("Configuring camera settings...")
# Set manual exposure
if color_sensor.supports(rs.option.exposure):
# Disable auto exposure first
if color_sensor.supports(rs.option.auto_exposure):
color_sensor.set_option(rs.option.auto_exposure, False)
print("Disabled auto exposure")
# Set manual exposure value
exposure_range = color_sensor.get_option_range(rs.option.exposure)
target_exposure = min(10000, exposure_range.max) # 10ms or max available
color_sensor.set_option(rs.option.exposure, target_exposure)
print(f"Set exposure to {target_exposure} microseconds")
# Set manual white balance
if color_sensor.supports(rs.option.white_balance):
if color_sensor.supports(rs.option.enable_auto_white_balance):
color_sensor.set_option(rs.option.enable_auto_white_balance, False)
print("Disabled auto white balance")
# Set white balance temperature
wb_range = color_sensor.get_option_range(rs.option.white_balance)
color_sensor.set_option(rs.option.white_balance, 4600) # Daylight ~4600K
print("Set white balance to 4600K")
# Adjust image quality settings
quality_options = [
(rs.option.brightness, 0), # Neutral brightness
(rs.option.contrast, 50), # Moderate contrast
(rs.option.saturation, 64), # Default saturation
(rs.option.sharpness, 50) # Moderate sharpening
]
for option, value in quality_options:
if color_sensor.supports(option):
color_sensor.set_option(option, value)
print(f"Set {option.name} to {value}")
print("Camera configuration completed")import pyrealsense2 as rs
ctx = rs.context()
device = ctx.query_devices()[0]
depth_sensor = device.first_depth_sensor()
print("Configuring depth sensor...")
# Configure depth accuracy and range
depth_options = [
(rs.option.min_distance, 0.1), # 10cm minimum
(rs.option.max_distance, 5.0), # 5m maximum
(rs.option.confidence_threshold, 2), # Medium confidence
]
for option, value in depth_options:
if depth_sensor.supports(option):
try:
# Check if value is in valid range
range_info = depth_sensor.get_option_range(option)
if range_info.min <= value <= range_info.max:
depth_sensor.set_option(option, value)
print(f"Set {option.name} to {value}")
else:
print(f"Value {value} out of range for {option.name} "
f"({range_info.min}-{range_info.max})")
except rs.error as e:
print(f"Error setting {option.name}: {e}")
# Configure laser power if available
if depth_sensor.supports(rs.option.laser_power):
laser_range = depth_sensor.get_option_range(rs.option.laser_power)
# Set to 75% of maximum power
laser_power = laser_range.min + (laser_range.max - laser_range.min) * 0.75
depth_sensor.set_option(rs.option.laser_power, laser_power)
print(f"Set laser power to {laser_power:.1f}")
# Configure emitter if available
if depth_sensor.supports(rs.option.emitter_enabled):
depth_sensor.set_option(rs.option.emitter_enabled, True)
print("Enabled IR emitter")
print("Depth sensor configuration completed")import pyrealsense2 as rs
# Create filters
decimation = rs.decimation_filter()
spatial = rs.spatial_filter()
temporal = rs.temporal_filter()
hole_filling = rs.hole_filling_filter()
print("Configuring filter options...")
# Configure decimation filter
if decimation.supports(rs.option.filter_magnitude):
decimation.set_option(rs.option.filter_magnitude, 2.0)
print("Set decimation magnitude to 2.0")
# Configure spatial filter for aggressive noise reduction
spatial_config = [
(rs.option.filter_magnitude, 4.0), # Strong filtering
(rs.option.filter_smooth_alpha, 0.7), # High smoothing
(rs.option.filter_smooth_delta, 15.0), # Edge preservation
(rs.option.holes_fill, 3.0) # Fill holes
]
for option, value in spatial_config:
if spatial.supports(option):
spatial.set_option(option, value)
print(f"Set spatial {option.name} to {value}")
# Configure temporal filter
temporal_config = [
(rs.option.filter_smooth_alpha, 0.3), # Moderate smoothing
(rs.option.filter_smooth_delta, 40.0), # Edge preservation
(rs.option.holes_fill, 4) # Persistence control
]
for option, value in temporal_config:
if temporal.supports(option):
temporal.set_option(option, value)
print(f"Set temporal {option.name} to {value}")
# Configure hole filling method
if hole_filling.supports(rs.option.holes_fill):
hole_filling.set_option(rs.option.holes_fill, 2) # nearest_from_around
print("Set hole filling to nearest_from_around")
print("Filter configuration completed")
# Apply filters to demonstrate configured settings
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
pipeline.start(config)
try:
frames = pipeline.wait_for_frames()
depth_frame = frames.get_depth_frame()
if depth_frame:
# Apply configured filter chain
filtered = decimation.process(depth_frame)
filtered = spatial.process(filtered)
filtered = temporal.process(filtered)
filtered = hole_filling.process(filtered)
original_size = f"{depth_frame.get_width()}x{depth_frame.get_height()}"
filtered_size = f"{filtered.get_width()}x{filtered.get_height()}"
print(f"Applied filters: {original_size} -> {filtered_size}")
finally:
pipeline.stop()import pyrealsense2 as rs
import json
class DeviceConfigurator:
def __init__(self, device):
self.device = device
self.sensors = device.query_sensors()
def save_configuration(self, filename):
"""Save current device configuration to JSON file."""
config = {}
for i, sensor in enumerate(self.sensors):
sensor_name = f"sensor_{i}"
if sensor.supports(rs.camera_info.name):
sensor_name = sensor.get_info(rs.camera_info.name).replace(" ", "_")
sensor_config = {}
options_list = sensor.get_supported_options()
for option_value in options_list:
option = option_value.id
if sensor.supports(option):
try:
current_value = sensor.get_option(option)
sensor_config[option.name] = {
'value': current_value,
'type': option_value.type.name
}
except rs.error:
pass # Skip options that can't be read
config[sensor_name] = sensor_config
with open(filename, 'w') as f:
json.dump(config, f, indent=2)
print(f"Configuration saved to {filename}")
def load_configuration(self, filename):
"""Load device configuration from JSON file."""
try:
with open(filename, 'r') as f:
config = json.load(f)
for sensor_name, sensor_config in config.items():
# Find matching sensor
sensor = self._find_sensor_by_name(sensor_name)
if not sensor:
print(f"Sensor {sensor_name} not found, skipping")
continue
print(f"Configuring {sensor_name}...")
for option_name, option_info in sensor_config.items():
try:
# Find option enum by name
option = self._find_option_by_name(option_name)
if option and sensor.supports(option):
value = option_info['value']
sensor.set_option(option, value)
print(f" Set {option_name} to {value}")
else:
print(f" Option {option_name} not supported")
except Exception as e:
print(f" Error setting {option_name}: {e}")
print("Configuration loaded successfully")
except FileNotFoundError:
print(f"Configuration file {filename} not found")
except Exception as e:
print(f"Error loading configuration: {e}")
def _find_sensor_by_name(self, sensor_name):
"""Find sensor by name."""
for sensor in self.sensors:
if sensor.supports(rs.camera_info.name):
name = sensor.get_info(rs.camera_info.name).replace(" ", "_")
if name == sensor_name:
return sensor
return None
def _find_option_by_name(self, option_name):
"""Find option enum by name."""
# This is a simplified approach - in practice you'd have a mapping
for option in rs.option:
if option.name == option_name:
return option
return None
def print_current_configuration(self):
"""Print current device configuration."""
print(f"Device: {self.device.get_info(rs.camera_info.name)}")
for i, sensor in enumerate(self.sensors):
sensor_name = f"Sensor {i}"
if sensor.supports(rs.camera_info.name):
sensor_name = sensor.get_info(rs.camera_info.name)
print(f"\n{sensor_name}:")
options_list = sensor.get_supported_options()
for option_value in options_list:
option = option_value.id
current_value = option_value.value
if sensor.supports(option):
try:
range_info = sensor.get_option_range(option)
print(f" {option.name}: {current_value} "
f"(range: {range_info.min}-{range_info.max})")
except rs.error:
print(f" {option.name}: {current_value}")
# Usage example
ctx = rs.context()
device = ctx.query_devices()[0]
configurator = DeviceConfigurator(device)
# Print current configuration
configurator.print_current_configuration()
# Save configuration
configurator.save_configuration("device_config.json")
# Modify some settings
color_sensor = device.first_color_sensor()
if color_sensor.supports(rs.option.brightness):
color_sensor.set_option(rs.option.brightness, 10)
# Load original configuration
configurator.load_configuration("device_config.json")import pyrealsense2 as rs
import time
class OptionMonitor:
def __init__(self, sensor):
self.sensor = sensor
self.monitored_options = []
self.last_values = {}
def add_option(self, option):
"""Add option to monitoring list."""
if self.sensor.supports(option):
self.monitored_options.append(option)
self.last_values[option] = self.sensor.get_option(option)
print(f"Monitoring {option.name}")
else:
print(f"Option {option.name} not supported")
def check_changes(self):
"""Check for option value changes."""
changes = []
for option in self.monitored_options:
try:
current_value = self.sensor.get_option(option)
last_value = self.last_values[option]
if abs(current_value - last_value) > 0.001: # Threshold for change
changes.append((option, last_value, current_value))
self.last_values[option] = current_value
except rs.error:
pass # Skip if option can't be read
return changes
def print_changes(self, changes):
"""Print option changes."""
if changes:
print("Option changes detected:")
for option, old_value, new_value in changes:
print(f" {option.name}: {old_value:.3f} -> {new_value:.3f}")
# Example usage
ctx = rs.context()
device = ctx.query_devices()[0]
color_sensor = device.first_color_sensor()
monitor = OptionMonitor(color_sensor)
# Monitor key options
options_to_monitor = [
rs.option.exposure,
rs.option.gain,
rs.option.white_balance,
rs.option.brightness,
rs.option.contrast
]
for option in options_to_monitor:
monitor.add_option(option)
print("Starting option monitoring (modify camera settings to see changes)...")
# Monitor for changes
for i in range(100): # Monitor for ~10 seconds
changes = monitor.check_changes()
monitor.print_changes(changes)
# Simulate some changes every 30 iterations
if i % 30 == 0 and i > 0:
if color_sensor.supports(rs.option.brightness):
new_brightness = (i // 30) * 10 # Cycle through values
color_sensor.set_option(rs.option.brightness, new_brightness)
print(f"Changed brightness to {new_brightness}")
time.sleep(0.1)Install with Tessl CLI
npx tessl i tessl/pypi-pyrealsense2