2from typing
import Union, cast, Sequence
4from ids_peak_common.datatypes.iimageview
import IImageView
5from ids_peak_common.datatypes.pixelformat
import PixelFormat, Channel
6from ids_peak_common.pipeline.modules.imodule
import IModule
7from ids_peak_common.pipeline.modules.iautofeature_module
import IAutoFeature
8from ids_peak_common.pipeline.pipeline_base
import PipelineBase
9from ids_peak_common.serialization
import IArchive
13 NotSupportedException)
26from ids_peak_icv.pipeline.features
import IFeature
27from ids_peak_icv.pipeline.features
import (MirrorFeature, RotationFeature,
28 BinningFeature, DecimationFeature, GainFeature, ColorCorrectionFeature,
29 DigitalBlackFeature, GammaFeature, HotpixelCorrectionFeature,
30 SaturationFeature, SharpeningFeature, ChromaticAdaptionFeature)
40 Image processing pipeline for sequential transformation of raw image frames.
42 The `Pipeline` class performs a series of configurable image processing steps on
43 raw or pre-processed image data. It is designed to support a complete transformation
44 workflow, from raw sensor input to final output format, with each stage modular
45 and optionally enabled or configured.
49 1. Unpack (Always Active) –
50 Automatically unpacks packed sensor data formats.
51 This stage is internal and cannot be configured.
53 2. Hot Pixel Correction –
54 Identifies and corrects defective pixels (hot pixels).
57 Reduces resolution and improves signal-to-noise ratio by combining adjacent pixels.
60 Downscales the image by skipping pixels in a defined pattern.
63 Optionally mirrors the image left-right and/or up-down.
66 Rotates the image by 90, 180, or 270 degrees.
69 Applies digital master gain to control image brightness,
70 or digital color gains to adjust white balance.
72 8. Debayer (Configured Internally) -
73 Converts Bayer pattern raw data to RGB format and
74 expands monochrome images to RGB when a color output format is requested.
75 This behavior is automatically determined based on the input and output pixel formats.
78 Applies a color correction matrix, saturation and chromatic adaption.
81 Analyzes the image for the following dynamic adjustments:
85 - Auto Focus (if supported by the device)
87 To enable Auto Features, an external module must be provided via::
89 auto_feature_module = AutoFeatureModule(remote_device_node_map)
90 pipeline.auto_feature_module = auto_feature_module
92 This module is part of the **Auto Feature Library (AFL)**.
94 11. Mono conversion (Configured Internally) –
95 Converts RGB images to monochrome when a monochrome output format is requested.
98 Enhances image detail using edge-based sharpening filters.
101 Applies gamma correction to adjust brightness and contrast.
103 14. Pixel Format Conversion (Configured Internally) –
104 Converts the processed image to the desired output pixel format.
106 **Smart Pixel Format Configuration Inference**
108 The pipeline includes built-in logic to automatically configure certain internal stages based on the input and
109 output formats. For example:
111 - If a Bayer image is provided and the output format is RGB, debayering is automatically applied.
112 - If a monochrome image is input and the output format is RGB, the DebayerModule takes over the mono-to-RGB expansion.
113 - If the output format is monochrome, mono conversion is enabled.
114 - If a Bayer pixel format is set as output format, the following features or modules are not processing:
117 - MonoConversionModule,
118 - SharpeningFeature and
121 - The PixelFormatConversionModule is responsible
122 for converting to the specified output format.
123 If necessary, the bit depth is reduced during this step.
125 Use the following method to set the desired final pixel format::
127 pipeline.output_pixel_format = PixelFormat.RGB_8
129 @note There might be cases where some modules, even though they are enabled,
130 do not apply their configuration, if the pixel format is not supported.
131 Further information can be found in the documentation of the individual
132 "process" methods for each module.
136 The pipeline can be configured in two ways:
138 Module Access: Each configurable processing module can be accessed directly,
139 allowing individual configuration::
141 pipeline.gain.master = 1.2
142 pipeline.gamma.value = 2.2
144 Settings File: Load or save all configuration settings::
146 pipeline.import_settings_from_file("config.json")
147 pipeline.export_settings_to_file("config.json")
149 This modular and extensible design enables flexible integration into a variety
150 of image processing applications, from camera pipelines to offline image editing.
152 @since ids_peak_icv 1.0
153 @ingroup ids_peak_icv_python_pipeline
159 Initializes all internal modules to their default configuration.
161 @since ids_peak_icv 1.0
170 mono_conversion_module.enabled =
False
200 The pipeline version as an integer.
202 @since ids_peak_icv 1.0
210 The pipeline type identifier as a string, primarily used for serialization.
212 @since ids_peak_icv 1.0
214 return "DefaultPipeline"
216 def process(self, image: Union[Image, IImageView]) -> Image:
219 Applies the pipeline to the given image and returns the result as a new image.
221 The returned image is always a new instance.
222 If no processing is applied, it will be a deep copy of the input.
224 @warning The input image may be modified during execution due to in-place operations.
225 If you need to preserve the original image,
226 create a copy before calling this function.
228 @note This operation disregards any specified image regions
229 and processes the entire image.
231 @param image: Input image to be processed.
233 @return A new image containing the processed input or a deep copy of the input.
235 @since ids_peak_icv 1.0
237 if isinstance(image, IImageView):
238 result = cast(Image, super().
process(Image.create_from_image_view(image)))
240 result = cast(Image, super().
process(image))
242 result = DefaultPipeline._copy_image_buffer_if_same_buffer(image, result)
248 input_data = original_image.to_numpy_array(copy=
False)
249 input_address = input_data.ctypes.data
251 output_data = processed_image.to_numpy_array(copy=
False)
252 output_address = output_data.ctypes.data
253 if input_address == output_address:
254 return processed_image.convert_pixel_format(processed_image.pixel_format)
256 return cast(Image, processed_image)
261 Converts the current pipeline settings into a string format.
263 Serializes all relevant configuration parameters of the pipeline into
264 a single string, which can be stored or transferred for later use.
269 - Creation timestamp (ISO UTC)
270 - All module settings (type + serialized data)
272 @return A string representation of the pipeline's current configuration state.
274 @since ids_peak_icv 1.0
276 from datetime
import datetime, timezone
281 "Creation": datetime.now(timezone.utc).isoformat()
288 module.serialize(data_archive)
293 modules.append(module_archive)
295 archive.set(
"Modules", cast(list[IArchive], modules))
299 serializer.write(archive, buffer)
301 return buffer.getvalue()
306 Restores pipeline settings from a previously serialized string.
308 Parses the provided string and applies the contained configuration values
309 to update the internal state of the pipeline accordingly.
312 - Validation of version (must be >= 1).
313 - Validation of pipeline type (must match this pipeline).
314 - Restoring each module's settings by invoking its `deserialize` method.
316 @param settings: A string containing the serialized pipeline configuration.
318 @exception NotPossibleException: If the type is invalid.
319 @exception NotSupportedException: If the version is invalid.
320 @exception CorruptedException: If required module settings are missing.
322 @since ids_peak_icv 1.0
327 buffer = StringIO(settings)
328 archive = deserializer.read(buffer)
330 pipeline_type = archive.get(
"Type", str)
331 if pipeline_type != self.
type:
333 f
"The settings for {pipeline_type} are not compatible with this pipeline ({self.type})."
336 version = archive.get(
"Version", int)
339 "The given version in the settings exceeds the pipeline version. "
340 f
"Given settings version: {version}, pipeline version: {self.version}. "
341 "The module version has to be >= the given pipeline settings version.")
343 module_archives = {m.get(
"Type", str): m.get_archive(
"Data")
for m
in archive.get(
"Modules", list)}
346 module_type = module.type
347 if module_type
not in module_archives:
349 f
"The settings for module '{module_type}' are missing!"
351 module.deserialize(module_archives[module_type])
356 Resets all modules in the pipeline to their default state.
357 Also resets their enabled state.
359 In addition, this also resets the pipelines internal properties to default:
360 - ProcessingPolicy to ProcessingPolicy.Fast
362 @since ids_peak_icv 1.0
365 module.reset_to_default()
366 module.enabled =
True
369 feature.reset_to_default()
370 feature.enabled =
True
376 def processing_policy(self) -> ProcessingPolicy:
379 The currently used processing policy.
381 @since ids_peak_icv 1.0
385 @processing_policy.setter
386 def processing_policy(self, policy: ProcessingPolicy) ->
None:
389 Defines the processing policy for the pipeline.
391 This policy determines the trade-off between processing speed and
392 image quality throughout the entire pipeline.
394 - **Fast**: Prioritizes processing speed, which may reduce image quality.
395 - **Balanced**: Balances processing speed and image quality for typical use cases.
396 - **Enhanced**: Prioritizes improved image quality at the cost of reduced processing speed.
398 @param policy: Desired processing policy.
400 @since ids_peak_icv 1.0
410 The current output pixel format as a `PixelFormat` enum.
412 @since ids_peak_icv 1.0
416 @output_pixel_format.setter
420 Defines the desired pixel format for processed images.
422 The pipeline will convert images to this format during processing.
425 When set to a Bayer format,
426 the *ColorCorrection*, *Gamma* and *Sharpening* features
427 will not process the image because they do not support Bayer formats.
428 This may result in unexpected image quality if these features are enabled.
430 @param output_pixel_format: The new pixel format as a `PixelFormat` enum.
432 @since ids_peak_icv 1.0
434 is_bayer_format = output_pixel_format.is_single_channel
and output_pixel_format.has_channel(Channel.BAYER)
435 is_mono_format = output_pixel_format.is_single_channel
and output_pixel_format.has_intensity_channel
438 self.
_debayer_module.conversion_policy = DebayerConversionPolicy.BYPASS
441 self.
_debayer_module.conversion_policy = DebayerConversionPolicy.BAYER_ONLY
445 self.
_debayer_module.conversion_policy = DebayerConversionPolicy.BAYER_AND_MONO
448 self.
_debayer_module.conversion_policy = DebayerConversionPolicy.BAYER_AND_MONO
455 bit_depth = output_pixel_format.storage_bits_per_channel
471 Provides access to the mirror feature for image mirroring operations.
473 The mirror feature allows horizontal (left-right) and vertical (up-down) mirroring
474 of images during pipeline processing.
476 @return A reference to the mirror feature.
478 @since ids_peak_icv 1.0
486 Provides access to the rotation feature for image rotation operations.
488 The rotation feature allows rotating images in 90-degree increments (0°, 90°, 180°, 270°)
489 during pipeline processing.
491 @return A reference to the rotation feature.
493 @since ids_peak_icv 1.0
501 Provides access to the gain feature for brightness and white balance adjustments.
503 The gain feature allows adjustment of master gain (overall brightness) and individual
504 color channel gains (red, green, blue) for white balance correction.
506 @return A reference to the gain feature.
508 @since ids_peak_icv 1.0
516 Provides access to the color correction feature for color space transformations.
518 The color correction feature applies a 3x3 transformation matrix to perform color
521 @return A reference to the color correction feature.
523 @since ids_peak_icv 1.0
531 Provides access to the saturation feature for color intensity adjustments.
533 The saturation feature allows adjustment of color saturation levels, making colors
534 more vivid (higher saturation) or more muted (lower saturation).
536 @return A reference to the saturation feature.
538 @since ids_peak_icv 1.0
546 Provides access to the gamma feature for brightness and contrast adjustments.
548 The gamma feature applies inverse gamma correction to adjust image luminance,
549 preparing images for linear domain processing or display.
551 @return A reference to the gamma feature.
553 @since ids_peak_icv 1.0
561 Provides access to the digital black feature for sensor offset correction.
563 The digital black feature compensates for sensor digital black offsets by subtracting
564 a configurable black level and normalizing the result.
566 @return A reference to the digital black feature.
568 @since ids_peak_icv 1.0
576 Provides access to the sharpening feature for image detail enhancement.
578 The sharpening feature applies edge-based sharpening filters to enhance image detail
579 and improve perceived image sharpness.
581 @return A reference to the sharpening feature.
583 @since ids_peak_icv 1.0
591 Provides access to the hot pixel correction feature for defective pixel repair.
593 The hot pixel correction feature identifies and corrects defective pixels (hot pixels)
594 in camera images by replacing them with interpolated values from neighboring pixels.
596 @return A reference to the hotpixel correction feature.
598 @since ids_peak_icv 1.0
606 Provides access to the binning feature for resolution reduction and noise improvement.
608 The binning feature reduces image resolution by combining adjacent pixels through
609 averaging or summation, improving signal-to-noise ratio at the cost of resolution.
611 @return A reference to the BinningFeature.
613 @since ids_peak_icv 1.0
621 Provides access to the decimation feature for resolution reduction by pixel skipping.
623 The decimation feature reduces image resolution by skipping pixels in a defined pattern,
624 providing a faster alternative to binning for resolution reduction.
626 A reference to the DecimationFeature.
628 @return A reference to the DecimationFeature.
630 @since ids_peak_icv 1.0
638 Provides access to the chromatic adaption feature for adjusting to lighting conditions.
640 The chromatic adaption feature adjusts the image's colors based on the known or estimated
641 correlated color temperature of the light source, maintaining consistent color perception.
643 @return A reference to the chromatic adaption feature.
645 @since ids_peak_icv 1.3
657 The used auto feature module.
661 @autofeature_module.setter
665 Sets an auto feature module for automatic image adjustments.
667 These adjustments can include features such as
668 image brightness, white balance, and focus,
669 depending on the capabilities of the provided module.
672 If there is no auto feature module specified,
673 this step will be skipped during processing.
675 @param auto_feature_module: The auto feature module.
692 Retrieves the sequence of processing modules for the pipeline in execution order.
694 @return Sequence of pipeline modules.
696 @since ids_peak_icv 1.0
714 if output_pixel_format
in [PixelFormat.RGB_8, PixelFormat.RGB_10, PixelFormat.RGB_12,
715 PixelFormat.RGB_10_PACKED_32]:
716 return DebayerChannelLayout.RGB
718 if output_pixel_format
in [PixelFormat.RGBA_8, PixelFormat.RGBA_10, PixelFormat.RGBA_12]:
719 return DebayerChannelLayout.RGBA
721 if output_pixel_format
in [PixelFormat.BGR_8, PixelFormat.BGR_10, PixelFormat.BGR_12,
722 PixelFormat.BGR_10_PACKED_32]:
723 return DebayerChannelLayout.BGR
725 if output_pixel_format
in [PixelFormat.BGRA_8, PixelFormat.BGRA_10, PixelFormat.BGRA_12]:
726 return DebayerChannelLayout.BGRA
729 f
"There is not conversion to a debayer channel layout implemented for the given pixel format. "
730 f
"Given pixel format: {output_pixel_format}")
733 return (pixel_format.has_channel(Channel.RED)
and
734 pixel_format.has_channel(Channel.GREEN)
and
735 pixel_format.has_channel(Channel.BLUE))
Occurs when reading from a file or stream that is incomplete, damaged, or in an unexpected format.
Occurs when a failure happens during processing due to an unhandled internal routine condition.
Occurs when an operation cannot be performed due to logical constraints (e.g., camera calibration wit...
Occurs when a requested operation is not implemented or supported (e.g., exporting to an unsupported ...
Debayer is an image pipeline module that converts Bayer RAW images into standard color formats.
Downsampling is used to decrease the image size.
Gain is an image pipeline module that applies gain correction to an image.
Hotpixel correction is an image pipeline module for detecting and correcting hot pixels in camera ima...
Mono conversion is an image pipeline module that converts images to a monochrome format.
Sharpening is an image pipeline module that applies a sharpening filter to enhance image detail.
A pipeline module for applying tone curve corrections such as gamma adjustment and digital black offs...
Unpack is an image pipeline module that converts packed pixel formats into corresponding unpacked Bay...
Image processing pipeline for sequential transformation of raw image frames.
int version(self)
The pipeline version as an integer.
_tone_curve_correction_module
None reset_to_default(self)
Resets all modules in the pipeline to their default state.
bool _has_rgb_channels(self, PixelFormat pixel_format)
_hotpixel_correction_feature
DigitalBlackFeature digital_black(self)
Provides access to the digital black feature for sensor offset correction.
_hotpixel_correction_module
ColorCorrectionFeature color_correction(self)
Provides access to the color correction feature for color space transformations.
IAutoFeature|None autofeature_module(self)
The used auto feature module.
None import_settings_from_string(self, str settings)
Restores pipeline settings from a previously serialized string.
Image _copy_image_buffer_if_same_buffer(Image|IImageView original_image, Image processed_image)
GammaFeature gamma(self)
Provides access to the gamma feature for brightness and contrast adjustments.
str type(self)
The pipeline type identifier as a string, primarily used for serialization.
_color_correction_feature
BinningFeature binning(self)
Provides access to the binning feature for resolution reduction and noise improvement.
ProcessingPolicy _processing_policy
tuple[IModule,...] _modules(self)
Retrieves the sequence of processing modules for the pipeline in execution order.
SaturationFeature saturation(self)
Provides access to the saturation feature for color intensity adjustments.
ChromaticAdaptionFeature chromatic_adaption(self)
Provides access to the chromatic adaption feature for adjusting to lighting conditions.
str export_settings_to_string(self)
Converts the current pipeline settings into a string format.
PixelFormat output_pixel_format(self)
The current output pixel format as a PixelFormat enum.
Image process(self, Union[Image, IImageView] image)
Applies the pipeline to the given image and returns the result as a new image.
None __init__(self)
Initializes all internal modules to their default configuration.
DebayerChannelLayout _channel_layout_from_output_pixelformat(self, PixelFormat output_pixel_format)
SharpeningFeature sharpening(self)
Provides access to the sharpening feature for image detail enhancement.
DecimationFeature decimation(self)
Provides access to the decimation feature for resolution reduction by pixel skipping.
_color_matrix_transformation_module
HotpixelCorrectionFeature hotpixel_correction(self)
Provides access to the hot pixel correction feature for defective pixel repair.
_chromatic_adaption_feature
RotationFeature rotation(self)
Provides access to the rotation feature for image rotation operations.
None|IAutoFeature _auto_feature_module
MirrorFeature mirror(self)
Provides access to the mirror feature for image mirroring operations.
GainFeature gain(self)
Provides access to the gain feature for brightness and white balance adjustments.
tuple[IFeature,...] _features(self)
Binning is used to decrease the image size.
Adjusts to changes in lighting conditions to maintain consistent color perception despite variations ...
Color correction applies a 3x3 color correction matrix to the image.
Decimation is used to decrease the image size.
Digital black applies digital black correction to an image.
Gain is an image pipeline feature that applies gain correction to an image.
Gamma applies an inverse gamma transformation to an image.
HotpixelCorrection detects and corrects hot pixels in camera images.
Mirror provides functionality to flip the image left-right or up-down.
Rotation provides fixed-angle rotation functionality.
Adjusts the saturation of an image by modifying a 3x3 color correction matrix.
Provides access to sharpening settings within an image processing pipeline.
A key-value store with type checking, based on a dict.
Deserializer for reading serialized data and converting it into an IArchive object.
Serializer for writing IArchive objects to an output stream.