IDS peak ICV v1.1.0
Loading...
Searching...
No Matches
default_pipeline.py
Go to the documentation of this file.
1from io import StringIO
2from typing import Union, cast, Sequence
3
4from ids_peak_common.datatypes.iimageview import IImageView
5from ids_peak_common.datatypes.pixelformat import PixelFormat, Channel
8from ids_peak_common.pipeline.pipeline_base import PipelineBase
9from ids_peak_common.serialization import IArchive
10
11from ids_peak_icv.datatypes.image import Image
12from ids_peak_icv.exceptions import (InternalErrorException, CorruptedException, NotPossibleException,
13 NotSupportedException)
14from ids_peak_icv.pipeline._internal import SharpeningModule
15from ids_peak_icv.pipeline._internal.color_matrix_transformation_module import ColorMatrixTransformationModule
16from ids_peak_icv.pipeline._internal.debayer_module import (DebayerModule, DebayerConversionPolicy,
17 DebayerChannelLayout)
18from ids_peak_icv.pipeline._internal.downsampling_module import DownsamplingModule, DownsamplingMode
20from ids_peak_icv.pipeline._internal.hotpixel_correction_module import HotpixelCorrectionModule
21from ids_peak_icv.pipeline._internal.mono_conversion_module import MonoConversionModule
22from ids_peak_icv.pipeline._internal.pixelformat_conversion_module import PixelFormatConversionModule
23from ids_peak_icv.pipeline._internal.tone_curve_correction_module import ToneCurveCorrectionModule
24from ids_peak_icv.pipeline._internal.transformation_module import TransformationModule
26from ids_peak_icv.pipeline.features import (MirrorFeature, RotationFeature,
27 BinningFeature, DecimationFeature, GainFeature, ColorCorrectionFeature,
28 DigitalBlackFeature, GammaFeature, HotpixelCorrectionFeature,
29 SaturationFeature, SharpeningFeature)
30from ids_peak_icv.pipeline.processing_policy import ProcessingPolicy
31from ids_peak_icv.serialization.archive import Archive
32from ids_peak_icv.serialization.deserializer import Deserializer
33from ids_peak_icv.serialization.serializer import Serializer
34
35
37 """!
38 @brief
39 Image processing pipeline for sequential transformation of raw image frames.
40
41 The `Pipeline` class performs a series of configurable image processing steps on raw or pre-processed image data.
42 It is designed to support a complete transformation workflow, from raw sensor input to final output format,
43 with each stage modular and optionally enabled or configured.
44
45 **Processing Steps**
46 1. Unpack (Always Active) – Automatically unpacks packed sensor data formats. This stage is internal and cannot be configured.
47
48 2. Hot Pixel Correction – Identifies and corrects defective pixels (hot pixels).
49
50 3. Binning – Reduces resolution and improves signal-to-noise ratio by combining adjacent pixels.
51
52 4. Decimation – Downscales the image by skipping pixels in a defined pattern.
53
54 5. Mirror – Optionally mirrors the image left-right and/or up-down.
55
56 6. Rotation – Rotates the image by 90, 180, or 270 degrees.
57
58 7. Gain – Applies digital master gain to control image brightness, or digital color gains to adjust white balance.
59
60 8. Debayer (Configured Internally) - Converts Bayer pattern raw data to RGB format and Expands monochrome images
61 to RGB when a color output format is requested. This behavior is automatically determined based on the
62 input and output pixel formats.
63
64 9. ColorCorrection – Applies a color correction matrix.
65
66 10. Auto Features – Optionally applies dynamic adjustments for example auto brightness or auto white balance.
67 To enable Auto Features, an external module must be provided via::
68
69 auto_feature_module = AutoFeatureModule(remote_device_node_map)
70 pipeline.auto_feature_module = auto_feature_module
71
72 This module is part of the **Auto Feature Library (AFL)**.
73
74 11. Mono conversion (Configured Internally) – Converts RGB images to monochrome when a monochrome output format is requested.
75
76 12. Sharpening – Enhances image detail using edge-based sharpening filters.
77
78 13. Gamma – Applies gamma correction to adjust brightness and contrast.
79
80 14. Pixel Format Conversion (Configured Internally) – Converts the processed image to the desired output pixel format.
81
82 **Smart Pixel Format Configuration Inference**
83
84 The pipeline includes built-in logic to automatically configure certain internal stages based on the input and
85 output formats. For example:
86
87 - If a Bayer image is provided and the output format is RGB, DebayerModule "debayering" is automatically applied.
88 - If a monochrome image is input and the output format is RGB, the Debayer Module takes over the mono-to-RGB expansion.
89 - If the output format is monochrome, Mono conversion is enabled.
90 - If a Bayer pixel format is set as output format, the following features or modules are not processing:
91 Debayer, Mono conversion, Sharpening and Gamma.
92 - The Pixel Format Conversion module is responsible for converting to the specified output format.
93 If necessary, the bit depth is reduced during this step.
94
95 Use the following method to set the desired final pixel format::
96
97 pipeline.output_pixel_format(PixelFormat.RGB_8)
98
99 @note There might be cases where some modules, even though they are enabled, do not apply their configuration,
100 if the pixel format is not supported. For more information, have a look at the specific pipeline modules "process"
101 methods.
102
103 **Configuration**
104
105 The pipeline can be configured in two ways:
106
107 Module Access: Each configurable processing module can be accessed directly, allowing individual configuration::
108
109 pipeline.gain.master = 1.2f
110 pipeline.gamma.value = 2.2f
111
112 Settings File: Load or save all configuration settings::
113
114 pipeline.import_settings_from_file("config.json")
115 pipeline.export_settings_to_file("config.json")
116
117 This modular and extensible design enables flexible integration into a variety of image processing applications,
118 from camera pipelines to offline image editing.
119
120 @since ids_peak_icv 1.0
121 @ingroup ids_peak_icv_python_pipeline
122 """
123
124 def __init__(self) -> None:
125 """!
126 @brief
127 Initializes all internal modules to their default configuration.
128
129 @since ids_peak_icv 1.0
130 """
131 self._processing_policy: ProcessingPolicy = ProcessingPolicy.BALANCED
134 self._binning_module = DownsamplingModule(DownsamplingMode.BinningAverage, "Binning")
135 self._decimation_module = DownsamplingModule(DownsamplingMode.Decimation, "Decimation")
137 mono_conversion_module = MonoConversionModule()
138 mono_conversion_module.enabled = False
139 self._mono_conversion_module = mono_conversion_module
141
146
156
160
161 self._auto_feature_module: None | IAutoFeature = None
162
163 @property
164 def version(self) -> int:
165 """!
166 @brief
167 The pipeline version as an integer.
168
169 @since ids_peak_icv 1.0
170 """
171 return 1
172
173 @property
174 def type(self) -> str:
175 """!
176 @brief
177 The pipeline type identifier as a string, primarily used for serialization.
178
179 @since ids_peak_icv 1.0
180 """
181 return "DefaultPipeline"
182
183 def process(self, image: Union[Image, IImageView]) -> Image:
184 """!
185 @brief
186 Applies the pipeline to the given image and returns the result as a new image.
187
188 @param image: Input image to be processed.
189
190 @return Processed image result.
191
192 @since ids_peak_icv 1.0
193 """
194 if isinstance(image, IImageView):
195 return cast(Image, super().process(Image.create_from_image_view(image)))
196 else:
197 return cast(Image, super().process(image))
198
200 """!
201 @brief
202 Converts the current pipeline settings into a string format.
203
204 Serializes all relevant configuration parameters of the pipeline into a single string,
205 which can be stored or transferred for later use.
206
207 The export includes:
208 - Pipeline version
209 - Pipeline type
210 - Creation timestamp (ISO UTC)
211 - All module settings (type + serialized data)
212
213 @return A string representation of the pipeline's current configuration state.
214
215 @since ids_peak_icv 1.0
216 """
217 from datetime import datetime, timezone
218
219 archive = Archive({
220 "Version": self.versionversion,
221 "Type": self.typetype,
222 "Creation": datetime.now(timezone.utc).isoformat()
223 })
224
225 modules = []
226
228 data_archive = Archive()
229 module.serialize(data_archive)
230 module_archive = Archive({
231 "Type": module.type,
232 "Data": data_archive
233 })
234 modules.append(module_archive)
235
236 archive.set("Modules", cast(list[IArchive], modules))
237
238 serializer = Serializer()
239 buffer = StringIO()
240 serializer.write(archive, buffer)
241
242 return buffer.getvalue()
243
244 def import_settings_from_string(self, settings: str) -> None:
245 """!
246 @brief
247 Restores pipeline settings from a previously serialized string.
248
249 Parses the provided string and applies the contained configuration values to
250 update the internal state of the pipeline accordingly.
251
252 This includes:
253 - Validation of version (must be >= 1).
254 - Validation of pipeline type (must match this pipeline).
255 - Restoring each module's settings by invoking its `deserialize` method.
256
257 @param settings: A string containing the serialized pipeline configuration.
258
259 @exception CorruptedException: If the version or type is invalid.
260 @exception NotPossibleException: If required module settings are missing.
261
262 @since ids_peak_icv 1.0
263 """
264
265 deserializer = Deserializer()
266
267 buffer = StringIO(settings)
268 archive = deserializer.read(buffer)
269
270 pipeline_type = archive.get("Type", str)
271 if pipeline_type != self.typetype:
273 f"The settings for {pipeline_type} are not compatible with this pipeline ({self.type})."
274 )
275
276 version = archive.get("Version", int)
277 if version < self.versionversion:
279 "The given version in the settings exceeds the pipeline version. "
280 f"Given settings version: {version}, pipeline version: {self.version}. "
281 "The module version has to be >= the given pipeline settings version.")
282
283 module_archives = {m.get("Type", str): m.get_archive("Data") for m in archive.get("Modules", list)}
284
286 module_type = module.type
287 if module_type not in module_archives:
288 raise CorruptedException(
289 f"The settings for module '{module_type}' are missing!"
290 )
291 module.deserialize(module_archives[module_type])
292
293 def reset_to_default(self) -> None:
294 """!
295 @brief
296 Resets all modules in the pipeline to their default state. Also resets their enabled state.
297
298 @since ids_peak_icv 1.0
299 """
301 module.reset_to_default()
302 module.enabled = True
303
304 self._mono_conversion_module.enabled = False
305
306 @property
307 def processing_policy(self) -> ProcessingPolicy:
308 """!
309 @brief
310 The currently used processing policy.
311
312 @since ids_peak_icv 1.0
313 """
314 return self._processing_policy
315
316 @processing_policy.setter
317 def processing_policy(self, policy: ProcessingPolicy) -> None:
318 """!
319 @brief
320 Defines the processing policy for the pipeline.
321
322 @param policy: Desired processing policy.
323
324 @since ids_peak_icv 1.0
325 """
326 self._processing_policy = policy
327 self._unpack_module.processing_policy = policy
328 self._debayer_module.processing_policy = policy
329
330 @property
331 def output_pixel_format(self) -> PixelFormat:
332 """!
333 @brief
334 The current output pixel format as a `PixelFormat` enum.
335
336 @since ids_peak_icv 1.0
337 """
338 return self._final_conversion_module.output_pixel_format
339
340 @output_pixel_format.setter
341 def output_pixel_format(self, output_pixel_format: PixelFormat) -> None:
342 """!
343 @brief
344 Defines the desired pixel format for processed images.
345
346 The pipeline will convert images to this format during processing.
347
348 @warning
349 When set to a Bayer format,
350 the *ColorCorrection*, *Gamma* and *Sharpening* features
351 will not process the image because they do not support Bayer formats.
352 This may result in unexpected image quality if these features are enabled.
353
354 @param output_pixel_format: The new pixel format as a `PixelFormat` enum.
355
356 @since ids_peak_icv 1.0
357 """
358 is_bayer_format = output_pixel_format.is_single_channel and output_pixel_format.has_channel(Channel.BAYER)
359 is_mono_format = output_pixel_format.is_single_channel and output_pixel_format.has_intensity_channel
360
361 if is_bayer_format:
362 self._debayer_module.conversion_policy = DebayerConversionPolicy.BYPASS
363
364 elif is_mono_format:
365 self._debayer_module.conversion_policy = DebayerConversionPolicy.BAYER_ONLY
366 self._debayer_module.channel_layout = DebayerChannelLayout.RGB
367
368 else:
369 self._debayer_module.conversion_policy = DebayerConversionPolicy.BAYER_AND_MONO
370
371 if self._has_rgb_channels(output_pixel_format):
372 self._debayer_module.conversion_policy = DebayerConversionPolicy.BAYER_AND_MONO
374 output_pixel_format)
375
376 self._mono_conversion_module.enabled = is_mono_format
377 self._final_conversion_module.output_pixel_format = output_pixel_format
378
379 bit_depth = output_pixel_format.storage_bits_per_channel
380
381 self._unpack_module.processing_policy = self._processing_policy
382 self._unpack_module.target_bit_depth = bit_depth
383
384 self._debayer_module.processing_policy = self._processing_policy
385 self._debayer_module.target_bit_depth = bit_depth
386
387 # ------------------------------------------------------------------------------------------------------------------
388 # Features
389 # ------------------------------------------------------------------------------------------------------------------
390
391 @property
392 def gamma(self) -> GammaFeature:
393 """!
394 @brief
395 Provides access to the gamma feature for brightness and contrast adjustments.
396
397 The gamma feature applies inverse gamma correction to adjust image luminance,
398 preparing images for linear domain processing or display.
399
400 @return A reference to the gamma feature.
401
402 @since ids_peak_icv 1.0
403 """
404 return self._gamma_feature
405
406 @property
407 def digital_black(self) -> DigitalBlackFeature:
408 """!
409 @brief
410 Provides access to the digital black feature for sensor offset correction.
411
412 The digital black feature compensates for sensor digital black offsets by subtracting a configurable
413 black level and normalizing the result.
414
415 @return A reference to the digital black feature.
416
417 @since ids_peak_icv 1.0
418 """
419 return self._digital_black_feature
420
421 @property
422 def gain(self) -> GainFeature:
423 """!
424 @brief
425 Provides access to the gain feature for brightness and white balance adjustments.
426
427 The gain feature allows adjustment of master gain (overall brightness) and individual
428 color channel gains (red, green, blue) for white balance correction.
429
430 @return A reference to the gain feature.
431
432 @since ids_peak_icv 1.0
433 """
434 return self._gain_feature
435
436 @property
437 def color_correction(self) -> ColorCorrectionFeature:
438 """!
439 @brief
440 Provides access to the color correction feature for color space transformations.
441
442 The color correction feature applies a 3x3 transformation matrix to perform color balancing.
443
444 @return A reference to the color correction feature.
445
446 @since ids_peak_icv 1.0
447 """
448 return self._color_correction_feature
449
450 @property
451 def saturation(self) -> SaturationFeature:
452 """!
453 @brief
454 Provides access to the saturation feature for color intensity adjustments.
455
456 The saturation feature allows adjustment of color saturation levels, making colors more vivid
457 (higher saturation) or more muted (lower saturation).
458
459 @return A reference to the saturation feature.
460
461 @since ids_peak_icv 1.0
462 """
463 return self._saturation_feature
464
465 @property
466 def sharpening(self) -> SharpeningFeature:
467 """!
468 @brief
469 Provides access to the sharpening feature for image detail enhancement.
470
471 The sharpening feature applies edge-based sharpening filters to enhance image detail
472 and improve perceived image sharpness.
473
474 @return A reference to the sharpening feature.
475
476 @since ids_peak_icv 1.0
477 """
478 return self._sharpening_feature
479
480 @property
481 def hotpixel_correction(self) -> HotpixelCorrectionFeature:
482 """!
483 @brief
484 Provides access to the hot pixel correction feature for defective pixel repair.
485
486 The hot pixel correction feature identifies and corrects defective pixels (hot pixels)
487 in camera images by replacing them with interpolated values from neighboring pixels.
488
489 @return A reference to the hotpixel correction feature.
490
491 @since ids_peak_icv 1.0
492 """
494
495 @property
496 def mirror(self) -> MirrorFeature:
497 """!
498 @brief
499 Provides access to the mirror feature for image mirroring operations.
500
501 The mirror feature allows horizontal (left-right) and vertical (up-down) mirroring
502 of images during pipeline processing.
503
504 @return A reference to the mirror feature.
505
506 @since ids_peak_icv 1.0
507 """
508 return self._mirror_feature
509
510 @property
511 def rotation(self) -> RotationFeature:
512 """!
513 @brief
514 Provides access to the rotation feature for image rotation operations.
515
516 The rotation feature allows rotating images in 90-degree increments (0°, 90°, 180°, 270°)
517 during pipeline processing.
518
519 @return A reference to the rotation feature.
520
521 @since ids_peak_icv 1.0
522 """
523 return self._rotation_feature
524
525 @property
526 def binning(self) -> BinningFeature:
527 """!
528 @brief
529 Provides access to the binning feature for resolution reduction and noise improvement.
530
531 The binning feature reduces image resolution by combining adjacent pixels through
532 averaging or summation, improving signal-to-noise ratio at the cost of resolution.
533
534 @return A reference to the BinningFeature.
535
536 @since ids_peak_icv 1.0
537 """
538 return self._binning_feature
539
540 @property
541 def decimation(self) -> DecimationFeature:
542 """!
543 @brief
544 Provides access to the decimation feature for resolution reduction by pixel skipping.
545
546 The decimation feature reduces image resolution by skipping pixels in a defined pattern,
547 providing a faster alternative to binning for resolution reduction.
548
549 A reference to the DecimationFeature.
550
551 @return A reference to the DecimationFeature.
552
553 @since ids_peak_icv 1.0
554 """
555 return self._decimation_feature
556
557 # ------------------------------------------------------------------------------------------------------------------
558 # Auto Features
559 # ------------------------------------------------------------------------------------------------------------------
560
561 @property
562 def autofeature_module(self) -> IAutoFeature | None:
563 """!
564 @brief
565 The used auto feature module.
566 """
568
569 @autofeature_module.setter
570 def autofeature_module(self, auto_feature_module: IAutoFeature | None) -> None:
571 """!
572 @brief
573 Sets an auto feature module for automatic image adjustments.
574
575 These adjustments can include features such as
576 image brightness, white balance, and focus,
577 depending on the capabilities of the provided module.
578
579 @note
580 If there is no auto feature module specified,
581 this step will be skipped during processing.
582
583 @param auto_feature_module: The auto feature module.
584 """
585 if self._auto_feature_module:
586 self._auto_feature_module.set_gain_module(None)
587 self._auto_feature_module = auto_feature_module
588 self._color_matrix_transformation_module._set_autofeature_module(auto_feature_module)
589 if self._auto_feature_module:
590 self._auto_feature_module.set_gain_module(self._gain_module)
591
592 # ------------------------------------------------------------------------------------------------------------------
593 # Internal
594 # ------------------------------------------------------------------------------------------------------------------
595
596 @property
597 def _modules(self) -> tuple[IModule, ...]:
598 """!
599 @brief
600 Retrieves the sequence of processing modules for the pipeline in execution order.
601
602 @return Sequence of pipeline modules.
603
604 @since ids_peak_icv 1.0
605 """
606
610 (self._auto_feature_module,) if self._auto_feature_module is not None else ()
613
614 def _channel_layout_from_output_pixelformat(self, output_pixel_format: PixelFormat) -> DebayerChannelLayout:
615 if output_pixel_format in [PixelFormat.RGB_8, PixelFormat.RGB_10, PixelFormat.RGB_12,
616 PixelFormat.RGB_10_PACKED_32]:
617 return DebayerChannelLayout.RGB
618
619 if output_pixel_format in [PixelFormat.RGBA_8, PixelFormat.RGBA_10, PixelFormat.RGBA_12]:
620 return DebayerChannelLayout.RGBA
621
622 if output_pixel_format in [PixelFormat.BGR_8, PixelFormat.BGR_10, PixelFormat.BGR_12,
623 PixelFormat.BGR_10_PACKED_32]:
624 return DebayerChannelLayout.BGR
625
626 if output_pixel_format in [PixelFormat.BGRA_8, PixelFormat.BGRA_10, PixelFormat.BGRA_12]:
627 return DebayerChannelLayout.BGRA
628
630 f"There is not conversion to a debayer channel layout implemented for the given pixel format. "
631 f"Given pixel format: {output_pixel_format}")
632
633 def _has_rgb_channels(self, pixel_format: PixelFormat) -> bool:
634 return (pixel_format.has_channel(Channel.RED) and
635 pixel_format.has_channel(Channel.GREEN) and
636 pixel_format.has_channel(Channel.BLUE))
str type(self)
Returns the type identifier of the pipeline.
Definition ipipeline.py:86
Sequence[IModule] _modules(self)
Retrieves the sequence of all modules in the pipeline, in execution order.
Definition ipipeline.py:99
Base class for implementing a custom pipeline.
Thrown when input data or a file is malformed, unreadable, or otherwise corrupted.
Thrown on unexpected internal system errors.
Definition exceptions.py:39
Thrown when an operation cannot be performed due to logical constraints.
Definition exceptions.py:85
Thrown when a requested operation is not implemented or supported.
Definition exceptions.py:71
Color matrix transformation is an image pipeline module that applies a color correction matrix to an ...
Debayer is an image pipeline module that converts Bayer RAW images into standard color formats.
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.
Pixel format conversion module that transforms images to a specified output pixel 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...
Transformation is an image pipeline module that provides mirror and rotation functionality.
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.
None reset_to_default(self)
Resets all modules in the pipeline to their default state.
None autofeature_module(self, IAutoFeature|None auto_feature_module)
Sets an auto feature module for automatic image adjustments.
bool _has_rgb_channels(self, PixelFormat pixel_format)
DigitalBlackFeature digital_black(self)
Provides access to the digital black feature for sensor offset correction.
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.
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.
BinningFeature binning(self)
Provides access to the binning feature for resolution reduction and noise improvement.
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.
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.
HotpixelCorrectionFeature hotpixel_correction(self)
Provides access to the hot pixel correction feature for defective pixel repair.
RotationFeature rotation(self)
Provides access to the rotation feature for image rotation operations.
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.
Color correction applies a 3x3 color correction matrix to the image.
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 simple key-value store with type checking, similar to a dict.
Definition archive.py:11
A deserializer that reads serialized data and reconstructs IArchive objects.
A serializer that converts IArchive objects into a textual representation.
Definition serializer.py:12