Controls¶
Base types¶
High-level camera control API.
This API provides constructs for building high-level camera controls. The control interface handles format conversions and validation of values automatically. The API allows for hierarchical composition of controls for building organised control structures.
- class quarklib.controls.IControl(cam)¶
Bases:
Generic[T]Interface for camera controls.
Provides methods for reading/writing/resetting the value as well as a few other convenience methods.
- Parameters:
cam (qamlib.Camera) – Camera used for connection.
- name: str¶
- shape: tuple | dict¶
- cam: qamlib.Camera¶
- abstract read()¶
Read the control value.
- Returns:
The current value.
- Return type:
T
- write(value, validation_strategy=ValidationStrategy.Error)¶
Write a new value to the control.
- Parameters:
value (T) – Value to write.
validation_strategy (ValidationStrategy) – Validate the value before writing. The default is to raise a ValueError on invalid values.
- reset()¶
Reset the control to its default value.
- property formatter: Any¶
Return the formatter of the control.
- class quarklib.controls.DriverControl(cam)¶
Bases:
ABC,IControl[T],Generic[T,C]Represents an actual control in the V4L2 driver.
This kind of control automatically converts the raw values in the driver to and from a user specified format (e.g. float, enum, bool). Values are validated against the specified control format.
- Parameters:
cam (qamlib.Camera) – Camera object used for reading/writing the control.
- default_value: T | None = None¶
- control_name: str¶
- id: int¶
- requires_event_handler: bool = False¶
- control_callback(event)¶
Update the control state given an event.
- Parameters:
event (qamlib.ControlEvent)
- property formatter: AbstractFormatter[C]¶
Return the formatter associated with this control.
- class quarklib.controls.ScalarControl(cam)¶
Bases:
DriverControl[C,C]A control that represents a single value.
- Parameters:
cam (qamlib.Camera)
- shape: tuple | dict = (1,)¶
- read()¶
Read a scalar value from the control.
- Return type:
C
- write(value, validation_strategy=ValidationStrategy.Error)¶
Write a scalar value to the control.
- Parameters:
value (C)
validation_strategy (ValidationStrategy)
- reset()¶
Reset the control to its default value.
- control_callback(event)¶
Update the control’s formatter.
- Parameters:
event (qamlib.ControlEvent)
- class quarklib.controls.ArrayControl(cam)¶
Bases:
DriverControl[ndarray[Any,dtype[TA]],TA]Control that represents an array of values.
Array controls support the Numpy slicing syntax. Example:
>>> cam = qamlib.Camera() >>> ctl = ArrayControl( ... "lut_green", ... cam, ... cam.list_controls(), ... FloatFormatter(3, 13), ... ) >>> ctl[:25] = 2 >>> print(ctl[:]) >>> print(ctl.read()) # equivalent
- Parameters:
cam (qamlib.Camera)
- shape: tuple[int, ...]¶
- read()¶
Read the control and ensure the output is correctly shaped.
- Return type:
ndarray[Any, dtype[TA]]
- write(value, validation_strategy=ValidationStrategy.Error)¶
Write a new value to the control.
- Parameters:
value (ndarray[Any, dtype[TA]]) – Value to write.
validation_strategy (ValidationStrategy) – Validate the value before writing. The default is to raise a ValueError on invalid values.
- reset()¶
Reset the control to its default value.
- class quarklib.controls.GroupControl(cam)¶
Bases:
IControl[T]An abstract control for grouping other controls.
This control does not have a driver equivalent. Instead, it is used to organize actual controls and to provide a simplified interface to multiple controls. It therefore contains several child controls.
Groups allow reading/writing to either the entire group or to individual children. Each subtype defines its own method for accessing the children as a group.
Writing to individual children is supported through attributes. The
quarklib.camera.builders.GroupBuilderhelper class adds the children as attributes when creating object instances. This is achieved through subclassing such that eachGroupControlinstance has its own type.- Parameters:
cam (qamlib.Camera) – Camera object used for reading/writing the control.
- reset()¶
Reset each of the child controls of the group.
- property formatter: dict[str, AbstractFormatter[C] | dict]¶
Return a dictionary of the formatters of each of this control’s children.
- class quarklib.controls.DictGroupControl(cam)¶
Bases:
GroupControl[dict[str,T]]Read/write children as dictionaries.
When reading the group value, a dictionary containing all the children and their values is returned. When writing, the keys in the input dictionary determine which values will be written.
- Parameters:
cam (qamlib.Camera)
- read()¶
Read all child controls of the group.
The values are returned as a dictionary with child names as keys.
- Return type:
dict[str, T]
- write(value, validation_strategy=ValidationStrategy.Error)¶
Write multiple children simultaneously using a dictionary.
- Parameters:
value (dict[str, T]) – A dictionary of child names mapped to values to write. The dictionary may contain all or some of the children.
validation_strategy (ValidationStrategy) – Validate the value before writing. The default is to raise a ValueError on invalid values.
- class quarklib.controls.GroupArrayControl(cam)¶
Bases:
GroupControl[ndarray[Any,dtype[TA]]]Allow multiple controls to be used as a single array.
The control works by stacking read values into a single array and automatically splitting a written array into appropriate slices that are then written to each child control. For scalar children, the formed array is 1d. For 1d and 2d array controls, the formed array is a 2d array stacked horizontally.
For example, an array group with three scalar children results in a 1x3 output shape. A group with two array children, with shapes 4x4 and 4x1 respectively, results in a 4x5 output shape.
The array group can be sliced like a regular numpy array. Both reading and writing using slices is allowed. Slicing across control boundaries is also supported. For example, the color conversion matrix consists of a 4x4 matrix and a 4x1 matrix that can be grouped into a single 4x5 matrix using an array group. Slicing can be performed on this group without considering the control boundaries. The slightly different format conversions are also handled implicitly.
>>> from qamlib import Camera >>> from quarklib.controls.builders import GroupControlDefinition, ControlDefinition >>> color_def = GroupControlDefinition.array( ... "ccm", ... children=[ ... ControlDefinition.float_array("matrix", "color_conversion_matrix", ... Q_3_12), ... ControlDefinition.float_array("offset", "color_conversion_offset", ... Q_0_14), ... ], ... ), >>> cam = Camera() >>> with cam: >>> color = color_def.build_controls(cam) >>> color[2:3, 3:5] = np.ones((1, 2))
- Parameters:
cam (qamlib.Camera)
- read()¶
Read children and stack the results horizontally into a single array.
- Returns:
The stacked array of values.
- Return type:
ndarray[Any, dtype[TA]]
- write(value, validation_strategy=ValidationStrategy.Error)¶
Write a value to all children using a single array.
The array value is split according to the shape of each child and each slice is written to the appropriate control. It essentially mirrors the
read()method.- Parameters:
value (ndarray[Any, dtype[TA]]) – Array to be written.
validation_strategy (ValidationStrategy) – Validate the value before writing. The default is to raise a ValueError on invalid values.
- class quarklib.controls.GroupSplitControl(cam)¶
Bases:
GroupControl[list[T]]Write the same value to multiple controls.
This group makes it easy to demonstrate the intent to replicate the same value across multiple controls. A single call to write will write the same value to all children.
The control requires that all children have the same shape and value types.
- Parameters:
cam (qamlib.Camera)
- write(value, validation_strategy=ValidationStrategy.Error)¶
Write the same value to all children.
- Parameters:
value (T | list[T])
validation_strategy (ValidationStrategy)
- read()¶
Read all child controls.
This method still reads each child separately, since their values are not guaranteed to be the same.
- Return type:
list[T]
Formatters¶
Defines formatter types to be used in camera controls.
- class quarklib.controls.formatters.ValidationStrategy(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)¶
Bases:
EnumValidation strategies.
Determines how validation is handled by a formatter.
- Error = 'Error'¶
Raise a ValueError if the provided value is outside the valid set.
- ConvertClamp = 'ConvertClamp'¶
Attempt to convert the provided value to the correct type and clamp it to the closest value in the valid set.
- class quarklib.controls.formatters.Interval(lower, upper, step)¶
Bases:
Generic[T]Represents a half-open interval.
- Parameters:
lower (T) – Lower bound (inclusive).
upper (T) – Upper bound (inclusive).
step (T) – Interval step.
- class quarklib.controls.formatters.AbstractFormatter(**kwargs)¶
Bases:
ABC,Generic[T]The base class for all formatters.
A formatter is a type that can convert to and from a raw integer value.
- to_raw(value, validation_strategy=ValidationStrategy.Error)¶
Convert a value to integer with validation.
The validation procedure is implemented by each subclass and should prevent invalid values from being successfully converted. In other words, returned values should always represent valid values.
- Parameters:
value (T) – The input value.
validation_strategy (ValidationStrategy) – How to handle validation. The default is to raise a ValueError on invalid values.
- Raises:
ValueError – If validate is True and there is a validation error.
- Returns:
The raw integer value.
- Return type:
int
- abstract from_raw(raw)¶
Convert a raw integer to a user value.
This method does not check the validity of the input since all written values have already been verified.
- Parameters:
raw (int)
- Return type:
T
- abstract property raw_valid_set: Interval | set¶
Returns the range of valid raw values.
The returned value can either be a range describing an interval of valid values or a set of valid values.
- abstract property valid_set: Interval | set¶
Returns the range of valid user values.
The returned value can either be a range describing an interval of valid values or a set of valid values.
- update_info(event)¶
Update formatter info based on the received event.
- Parameters:
event (qamlib.ControlEvent)
- validate_value(value)¶
Validate a user value.
The default implementation checks if the value is in the set of valid values.
- Parameters:
value (T) – User value to validate.
- Raises:
ValueError – Raised if the value is invalid.
- abstract clamp_value(value)¶
Attempt to convert the given value to a valid element of the valid set.
- Parameters:
value (Any)
- Return type:
T
- class quarklib.controls.formatters.BoolFormatter(**kwargs)¶
Bases:
AbstractFormatter[bool]Formatter of boolean values.
- from_raw(raw)¶
Convert from integer to bool.
- Parameters:
raw (int)
- Return type:
bool
- validate_value(value)¶
Values are valid if they have type bool.
- Parameters:
value (bool)
- clamp_value(value)¶
Convert the value to bool.
- Parameters:
value (Any)
- Return type:
bool
- class quarklib.controls.formatters.IntFormatter(min, max, dtype=<class 'numpy.int32'>, **kwargs)¶
Bases:
AbstractFormatter[int]Formatter of integers.
This formatter doesn’t modify the value itself since it can be written directly to the V4L2 control. Instead, it only performs validation.
- Parameters:
min (int)
max (int)
dtype (Callable[[Any], integer])
- from_raw(raw)¶
Return the raw value which is the same as the user value.
- Parameters:
raw (int)
- Return type:
int
- clamp_value(value)¶
Attempt to convert the value to an integer in the valid set.
- Parameters:
value (Any)
- Return type:
int
- update_info(event)¶
Set the min/max values for the control based on the values in event.
- Parameters:
event (qamlib.ControlEvent)
- class quarklib.controls.formatters.MappingFormatter(min, max, forward_map, backward_map, **kwargs)¶
Bases:
AbstractFormatter[float]Custom mapping formatter.
- Parameters:
forward_map (Callable[[int], float])
backward_map (Callable[[float], int])
- from_raw(raw)¶
Return the raw value which is the same as the user value.
- Parameters:
raw (int)
- Return type:
float
- clamp_value(value)¶
Attempt to convert the value to an integer in the valid set.
- Parameters:
value (Any)
- Return type:
int
- update_info(event)¶
Set the min/max values for the control based on the values in event.
- Parameters:
event (qamlib.ControlEvent)
- class quarklib.controls.formatters.FloatFormatter(int_bits=0, frac_bits=0, signed=False, **kwargs)¶
Bases:
AbstractFormatter[float]Formatter for floating point values.
This formatter converts to/from fixed point numbers that are used for V4L2 controls. The formatter specifies the fixed-point format and always rounds to the nearest representable value when converting from floating point.
The validation uses only an interval between min and max values and thus does not check if incoming values can be represented exactly as the fixed point format.
- from_raw(raw)¶
Convert from fixed point value to floating point value.
- Parameters:
raw (int)
- Return type:
float
- clamp_value(value)¶
Attempt to convert the value to a float in the valid set.
- Parameters:
value (Any)
- Return type:
float
- property precision: float¶
The distance between two consecutive numbers of the fixed point format.
- class quarklib.controls.formatters.MenuFormatter(items, **kwargs)¶
Bases:
AbstractFormatter[str]Formatter for menu values (enumerable types).
The formatter uses the string values as user values and their corresponding integer indices as raw values.
- from_raw(raw)¶
Get the menu item for the input index.
- Parameters:
raw (int)
- Return type:
str
- validate_value(value)¶
Check if the provided string is contained in the valid set.
- Parameters:
value (str)
- clamp_value(value)¶
Attempt to convert the value to a str.
Find the closes valid menu string using difflib.get_close_matches.
- Parameters:
value (Any)
- Return type:
str
Builders¶
Defines helpers for building camera controls.
- class quarklib.controls.builders.IControlDefinition(*args, **kwargs)¶
Bases:
ProtocolHelper classes for building
IControlobjects.- name: str¶
- doc: str¶
- optional: bool¶
- class quarklib.controls.builders.ControlDefinition(name, formatter, control, control_name=None, formatter_args=None, default_value=None, optional=False, requires_event_handler=False, doc='')¶
Bases:
IControlDefinitionBuilds
DriverControltype controls.The class contains a number of helper methods for simplifying the building of common control types.
The builder creates a new type with the name of the control when building.
- Parameters:
name (str) – Name of the control.
formatter (type[AbstractFormatter]) – Control formatter type.
control (type[DriverControl]) – Control type.
control_name (str | None) – Actual control name.
formatter_args (dict | None) – Keyword arguments for the formatter constructor.
default_value (Any) – Default control value.
optional (bool) – Whether the control is expected to always be present.
requires_event_handler (bool) – True if the control should always receive update events.
doc (str) – Documentation string inserted into the created type.
- classmethod float_array(name, control_name=None, formatter_args=None, default_value=None, optional=False, requires_event_handler=False, doc='')¶
Create a floating point array control.
- Parameters:
name (str) – Control name.
control_name (str | None) – Actual control name.
formatter_args (dict | None) – Keyword arguments for the formatter constructor.
default_value (ndarray[Any, dtype[floating]] | None) – Default control value.
optional (bool) – Whether the control is expected to always be present.
requires_event_handler (bool) – True if the control should always receive update events.
doc (str) – Documentation string inserted into the created type.
- Returns:
The constructed control.
- classmethod float_scalar(name, control_name=None, formatter_args=None, optional=False, requires_event_handler=False, doc='')¶
Create a floating point scalar control.
- Parameters:
name (str) – Control name.
control_name (str | None) – Actual control name.
formatter_args (dict | None) – Keyword arguments for the formatter constructor.
optional (bool) – Whether the control is expected to always be present.
requires_event_handler (bool) – Whether the control should always receive update events.
doc (str) – Documentation string inserted into the created type.
- Returns:
The constructed controller.
- classmethod mapped_scalar(name, control_name=None, formatter_args=None, optional=False, requires_event_handler=False, doc='')¶
Create a floating point scalar control.
- Parameters:
name (str) – Control name.
control_name (str | None) – Actual control name.
formatter_args (dict | None) – Keyword arguments for the formatter constructor.
optional (bool) – Whether the control is expected to always be present.
requires_event_handler (bool) – Whether the control should always receive update events.
doc (str) – Documentation string inserted into the created type.
- Returns:
The constructed controller.
- classmethod boolean(name, control_name=None, optional=False, requires_event_handler=False, doc='')¶
Create a boolean scalar control.
- Parameters:
name (str) – Control name.
control_name (str | None) – Actual control name.
optional (bool) – Whether the control is expected to always be present.
requires_event_handler (bool) – True if the control should always receive update events.
doc (str) – Documentation string inserted into the created type.
- Returns:
The constructed controller.
- classmethod int_array(name, control_name=None, formatter_args=None, default_value=None, optional=False, requires_event_handler=False, doc='')¶
Create an integer array control.
- Parameters:
name (str) – Control name.
control_name (str | None) – Actual control name.
formatter_args (dict | None) – Keyword arguments for the formatter constructor.
default_value (ndarray[Any, dtype[integer]] | None) – Default control value.
optional (bool) – Whether the control is expected to always be present.
requires_event_handler (bool) – Whether the control should always receive update events.
doc (str) – Documentation string inserted into the created type.
- Returns:
The constructed controller.
- classmethod int_scalar(name, control_name=None, formatter_args=None, optional=False, requires_event_handler=False, doc='')¶
Create an integer scalar control.
- Parameters:
name (str) – Control name.
control_name (str | None) – Actual control name.
formatter_args (dict | None) – Keyword arguments for the formatter constructor.
optional (bool) – Whether the control is expected to always be present.
requires_event_handler (bool) – Whether the control should always receive update events.
doc (str) – Documentation string inserted into the created type.
- Returns:
The constructed control.
Create a menu scalar control.
- Parameters:
name (str) – Control name.
control_name (str | None) – Actual control name.
optional (bool) – Whether the control is expected to always be present.
requires_event_handler (bool) – Whether the control should always receive update events.
doc (str) – Documentation string inserted into the created type.
- Returns:
The constructed control.
- class quarklib.controls.builders.GroupControlDefinition(name, kind, children, optional=False, doc='')¶
Bases:
IControlDefinitionBuilds
GroupControltype controls.This builder builds child controls recursively, thus allowing for a single build call to construct a large hierarchy of camera controls.
When building groups, the specific
GroupControlsubclass is subclassed again to create a new type that includes the specified children as attributes.- Parameters:
name (str) – Name of the control.
kind (type[IControl]) – Group kind to construct.
children (list[IControlDefinition]) – Child controls. Can be either groups or driver controls.
optional (bool) – Whether the control is expected to always be present.
doc (str) – Documentation string inserted into the created type.
- classmethod basic(name, children, optional=False, doc='')¶
Build a regular group control.
- Parameters:
name (str) – Control name.
children (list[IControlDefinition]) – Control children.
optional (bool) – Whether the control is expected to always be present.
doc (str) – Optional type documentation.
- Returns:
The constructed control.
- classmethod array(name, children, optional=False, doc='')¶
Build an array group.
- Parameters:
name (str) – Control name.
children (list[IControlDefinition]) – Control children.
optional (bool) – Whether the control is expected to always be present.
doc (str) – Optional type documentation.
- Returns:
The constructed control.
- classmethod split(name, children, optional=False, doc='')¶
Build a split group.
- Parameters:
name (str) – Control name..
children (list[IControlDefinition]) – Control children.
optional (bool) – Whether the control is expected to always be present.
doc (str) – Optional type documentation.
- Returns:
The constructed control.
- build_types(info, parent)¶
Build the control and all its children.
Creates a new class based on the specified base class and with the specified parameters. Some attributes are inferred from the info dictionary.
All child control types are associated with the parent control’s class.
- Parameters:
info (dict[str, dict])
parent (type)
- Return type:
type[GroupControl]
- build_controls(cam, parent=None)¶
Build control from camera and extracted info dict.
- Parameters:
cam (qamlib.Camera)
parent (type | None)
- Returns:
The built control object.
- Return type:
Definitions¶
Contains the base control definitions used in this library.
- quarklib.controls.qtec_definitions.LUT = <quarklib.controls.builders.GroupControlDefinition object>¶
Control definition for Lut
Description: Lookup Table Controls
Children:
Mono: Lookup table for grayscale formats.
Rgb: Combined lookup tables for RGB.
- quarklib.controls.qtec_definitions.COLOR_CONVERSION = <quarklib.controls.builders.GroupControlDefinition object>¶
Control definition for ColorConversion
Description: Color Conversion Controls
Children:
Enable:
SaturationValue:
Ccm: Affine color conversion transform.
- quarklib.controls.qtec_definitions.DIGITAL_GAIN = <quarklib.controls.builders.GroupControlDefinition object>¶
Control definition for DigitalGain
Description: Digital Gain Controls, usually used for white balance.
Children:
Red:
Green:
Blue:
- quarklib.controls.qtec_definitions.FLIP = <quarklib.controls.builders.GroupControlDefinition object>¶
Control definition for Flip
Description: Flip Controls.
Children:
Horizontal: Flip image horizontally.
Vertical: Flip image vertically.
- quarklib.controls.qtec_definitions.BINNING = <quarklib.controls.builders.GroupControlDefinition object>¶
Control definition for Binning
Description: Camera binning controls.
Children:
Horizontal:
Vertical:
- quarklib.controls.qtec_definitions.TRIGGER = <quarklib.controls.builders.GroupControlDefinition object>¶
Control definition for Trigger
Description: Trigger related controls.
Children:
Mode:
InvertPolarity:
ExternalDelay:
- quarklib.controls.qtec_definitions.FLASH = <quarklib.controls.builders.GroupControlDefinition object>¶
Control definition for Flash
Description: Flash related controls.
Children:
InvertPolarity:
Disable:
- quarklib.controls.qtec_definitions.GAIN_MAP = <quarklib.controls.builders.GroupControlDefinition object>¶
Control definition for GainMap
Description: Xform gain map controls.
Children:
Enable:
Scale:
Offset:
Map: Map data array.
- quarklib.controls.qtec_definitions.PATTERN_GENERATOR = <quarklib.controls.builders.ControlDefinition object>¶
Set generated pattern (for IMX sensors).