IDS peak ICV v1.3.0
Loading...
Searching...
No Matches
DefaultPipeline.cs
Go to the documentation of this file.
9using DebayerConversionPolicy = IDSImaging.Peak.ICV.Pipeline.Types.DebayerConversionPolicy;
12using BackendStatus = IDSImaging.Peak.ICV.Backend.Types.peak_icv_status;
14
16
197public class DefaultPipeline : PipelineBase, IDisposable
198{
199 private const ProcessingPolicy _defaultProcessingPolicy = ProcessingPolicy.Fast;
200
201 private readonly DownsamplingModule _binning = new(DownsamplingMode.BinningAverage, "Binning");
202 private readonly ColorMatrixTransformationModule _colorCorrection = new();
203 private readonly DebayerModule _debayer = new();
204 private readonly DownsamplingModule _decimation = new(DownsamplingMode.Decimation, "Decimation");
205 private readonly PixelFormatConversionModule _finalConversion = new();
206 private readonly GainModule _gain = new();
207 private readonly HotpixelCorrectionModule _hotpixel = new();
208 private readonly MonoConversionModule _monoConversion = new();
209 private readonly SharpeningModule _sharpening = new();
210 private readonly ToneCurveCorrectionModule _toneCurveCorrection = new();
211 private readonly TransformationModule _transformation = new();
212 private readonly UnpackModule _unpack = new();
213
214 private IAutoFeature? _autoFeatureModule;
215
216 private bool _disposed;
217 private ProcessingPolicy _processingPolicy = _defaultProcessingPolicy;
218
226 {
227 _monoConversion.IsEnabled = false;
228 PixelFormat format = _finalConversion.OutputPixelFormat;
229 var bitDepth = new PixelFormatInfo(format).StorageBitsPerChannel;
230 _unpack.ProcessingPolicy = _processingPolicy;
231 _unpack.TargetBitDepth = bitDepth;
232
233 _debayer.ProcessingPolicy = _processingPolicy;
234 _debayer.TargetBitDepth = bitDepth;
235
236 Hotpixel = new HotpixelCorrectionFeature(_hotpixel);
237
238 Rotation = new RotationFeature(_transformation);
239 Mirror = new MirrorFeature(_transformation);
240
241 Gain = new GainFeature(_gain);
242
243 Binning = new BinningFeature(_binning);
244 Decimation = new DecimationFeature(_decimation);
245
246 ColorCorrection = new ColorCorrectionFeature(_colorCorrection);
247 Saturation = new SaturationFeature(_colorCorrection);
248 ChromaticAdaption = new ChromaticAdaptionFeature(_colorCorrection);
249
250 Gamma = new GammaFeature(_toneCurveCorrection);
251 DigitalBlack = new DigitalBlackFeature(_toneCurveCorrection);
252
253 Sharpening = new SharpeningFeature(_sharpening);
254 }
255
256 private static int Version => 1;
257
261 public override string TypeId => "DefaultPipeline";
262
286 {
287 get => _processingPolicy;
288 set => UpdateProcessingPolicy(value);
289 }
290
295 {
296 get => _finalConversion.OutputPixelFormat;
297 set => UpdateOutputPixelFormat(value);
298 }
299
308
316 public BinningFeature Binning { get; }
317
326
334 public MirrorFeature Mirror { get; }
335
343 public RotationFeature Rotation { get; }
344
352 public GainFeature Gain { get; }
353
361
370
379
388
396 public GammaFeature Gamma { get; }
397
406
419 {
420 get => _autoFeatureModule;
421 set
422 {
423 _autoFeatureModule?.SetGainModule(null);
424 _autoFeatureModule = value;
425
426 _colorCorrection.SetAutoFeatureModule(_autoFeatureModule);
427 _autoFeatureModule?.SetGainModule(_gain);
428 }
429 }
430
434 public void Dispose()
435 {
436 Dispose(true);
437 GC.SuppressFinalize(this);
438 }
439
444 {
445 Dispose(false);
446 }
447
454 private void Dispose(bool disposing)
455 {
456 if (_disposed)
457 {
458 return;
459 }
460
461 _autoFeatureModule?.SetGainModule(null);
462
463 if (disposing)
464 {
465 // Do not reorder, otherwise we dispose the autofeature module
466 _autoFeatureModule = null;
467
468 // dispose managed objects
469 foreach (IModule? module in GetModules())
470 {
471 var mod = module as IDisposable;
472 mod?.Dispose();
473 }
474 }
475
476 _disposed = true;
477 }
478
485 protected override IReadOnlyList<IModule> GetModules()
486 {
487 if (_autoFeatureModule == null)
488 {
489 return new List<IModule>
490 {
491 _unpack, _hotpixel, _binning, _decimation, _transformation, _gain, _debayer, _colorCorrection,
492 _monoConversion,
493 _sharpening, _toneCurveCorrection, _finalConversion
494 };
495 }
496
497 return new List<IModule>
498 {
499 _unpack, _hotpixel, _binning, _decimation, _transformation, _gain, _debayer, _colorCorrection,
500 _autoFeatureModule,
501 _monoConversion, _sharpening, _toneCurveCorrection, _finalConversion
502 };
503 }
504
511 private IReadOnlyList<IFeature> GetFeatures()
512 {
513 return new List<IFeature>
514 {
517 };
518 }
519
547 public override string ExportSettingsToString()
548 {
549 using var archive = new Archive();
550
551 IReadOnlyList<IModule> moduleList = GetModules();
552 var modules = new List<IArchive>(moduleList.Count);
553
554 foreach (IModule? module in moduleList)
555 {
556 IArchive moduleArchive = archive.CreateArchive();
557 moduleArchive.SetString("Type", module.TypeId);
558
559 IArchive moduleDataArchive = moduleArchive.CreateArchive();
560 module.Serialize(moduleDataArchive);
561 moduleArchive.SetArchive("Data", moduleDataArchive);
562 modules.Add(moduleArchive);
563 }
564
565 archive.SetArchiveArray("Modules", modules);
566 archive.SetInt64("Version", Version);
567 archive.SetString("Type", TypeId);
568 archive.SetString("Creation", GetCurrentIsoUtcTime());
569
570 var stream = new MemoryStream();
571 var serializer = new Serializer();
572 serializer.Write(archive, stream);
573
574 return Utils.FromUtf8(stream.ToArray());
575 }
576
612 public override void ImportSettingsFromString(string settings)
613 {
614 var stream = new MemoryStream(Utils.ToUtf8(settings));
615
616 var deserializer = new Deserializer();
617 IArchive archive = deserializer.Read(stream);
618 using var dispose = archive as IDisposable;
619
620 var version = archive.GetInt64("Version");
621 if (version < 1)
622 {
623 throw new IcvNotSupportedException(
624 $"The 'Version' entry {version} in the settings string is invalid! Must be at least 1.");
625 }
626
627 var pipelineType = archive.GetString("Type");
628 if (pipelineType != TypeId)
629 {
630 throw new IcvNotPossibleException(
631 $"The settings for {pipelineType} are not compatible with this pipeline ({TypeId}).");
632 }
633
634 IReadOnlyList<IModule> modules = GetModules();
635
636 var archiveMap = new Dictionary<string, IArchive>();
637 IReadOnlyList<IArchive> moduleArchives = archive.GetArchiveArray("Modules");
638
639 foreach (IArchive? moduleArchive in moduleArchives)
640 {
641 using var disposeModuleArchive = moduleArchive as IDisposable;
642 var moduleType = moduleArchive.GetString("Type");
643 IArchive data = moduleArchive.GetArchive("Data");
644 archiveMap.Add(moduleType, data);
645 }
646
647 try
648 {
649 foreach (IModule? module in modules)
650 {
651 if (!archiveMap.TryGetValue(module.TypeId, out IArchive? foundArchive))
652 {
653 throw new IcvCorruptedException($"The settings for module {module.TypeId} are missing!");
654 }
655
656 module.Deserialize(foundArchive);
657 }
658 }
659 finally
660 {
661 foreach (IArchive? moduleArchive in archiveMap.Values)
662 {
663 using var disposeModuleArchive = moduleArchive as IDisposable;
664 }
665 }
666 }
667
679 public override void ResetToDefault()
680 {
681 foreach (IModule? module in GetModules())
682 {
683 module.ResetToDefault();
684 module.IsEnabled = true;
685 }
686
687 foreach (IFeature? feature in GetFeatures())
688 {
689 feature.ResetToDefault();
690 feature.IsEnabled = true;
691 }
692
693 _monoConversion.IsEnabled = false;
694 ProcessingPolicy = _defaultProcessingPolicy;
695 }
696
697 internal IModule? TryGetModuleById(string typeId)
698 {
699 return GetModules()
700 .FirstOrDefault(m => m != null && m.TypeId == typeId);
701 }
702
728 public Image Process(Image image)
729 {
730 Image current = image;
731 foreach (IModule? mod in GetModules())
732 {
733 try
734 {
735 try
736 {
737 var next = (Image) mod.Process(current);
738
739 if (!ReferenceEquals(next, current))
740 {
741 // Dispose replaced intermediate image
742 if (!ReferenceEquals(current, image))
743 {
744 current.Dispose();
745 }
746 }
747
748 current = next;
749 }
750 catch (IcvException e)
751 {
752 BackendStatus errorCode = e.ErrorCode;
753 var what = e.Message;
754 var moduleType = mod.TypeId;
755
756 var errorText = $"[{moduleType}] {what}";
757 switch (errorCode)
758 {
759 case BackendStatus.PEAK_ICV_STATUS_LIBRARY_NOT_INITIALIZED:
760 case BackendStatus.PEAK_ICV_STATUS_DYNAMIC_DEPENDENCY_MISSING:
761 throw new IcvInvalidConfigurationException(errorText, errorCode);
762 case BackendStatus.PEAK_ICV_STATUS_INVALID_HANDLE:
763 case BackendStatus.PEAK_ICV_STATUS_INVALID_BUFFER_SIZE:
764 case BackendStatus.PEAK_ICV_STATUS_MISMATCH:
765 case BackendStatus.PEAK_ICV_STATUS_NULL_POINTER:
766 case BackendStatus.PEAK_ICV_STATUS_NOT_SUPPORTED:
767 case BackendStatus.PEAK_ICV_STATUS_NOT_POSSIBLE:
768 throw new IcvNotSupportedException(errorText);
769 case BackendStatus.PEAK_ICV_STATUS_CORRUPTED:
770 throw new IcvCorruptedException(errorText);
771 case BackendStatus.PEAK_ICV_STATUS_OUT_OF_RANGE:
772 throw new IcvOutOfRangeException(errorText);
773 case BackendStatus.PEAK_ICV_STATUS_INTERNAL_ERROR:
774 throw new IcvException(errorText, errorCode);
775 default:
776 throw new IcvException("Generic Error!", errorCode);
777 }
778 }
779 }
780 catch
781 {
782 // Dispose intermediate image if needed
783 if (!ReferenceEquals(current, image))
784 {
785 current.Dispose();
786 }
787
788 throw;
789 }
790 }
791
792 return image.Data == current.Data ? current.Copy() : current;
793 }
794
814 public override object Process(object input)
815 {
816 if (input is not Image image)
817 {
818 throw new IcvNotSupportedException(
819 $"Casting from {input.GetType().Name} to the given type {typeof(Image).Name} is not supported!");
820 }
821
822 return Process(image);
823 }
824
847 public Image Process(IImageView imageView)
848 {
849 using var image = new Image(imageView);
850 return Process(image);
851 }
852
869 public void ReleaseBuffers()
870 {
871 _unpack.ReleaseBuffers();
872 _debayer.ReleaseBuffers();
873 _monoConversion.ReleaseBuffers();
874 _finalConversion.ReleaseBuffers();
875 }
876
877
878 private static string GetCurrentIsoUtcTime()
879 {
880 DateTime utcNow = DateTime.UtcNow;
881 var isoTimestamp = utcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'");
882 return isoTimestamp;
883 }
884
885 private void UpdateProcessingPolicy(ProcessingPolicy policy)
886 {
887 _processingPolicy = policy;
888
889 _unpack.ProcessingPolicy = _processingPolicy;
890 _debayer.ProcessingPolicy = _processingPolicy;
891 }
892
893 private void UpdateOutputPixelFormat(PixelFormat format)
894 {
895 var info = new PixelFormatInfo(format);
896
897 var isBayerFormat = info.IsSingleChannel && info.HasChannel(Channel.Bayer);
898 var isMonoFormat = info.IsSingleChannel && info.HasIntensityChannel;
899
900 if (isBayerFormat)
901 {
902 _debayer.ConversionPolicy = DebayerConversionPolicy.Bypass;
903 }
904 else if (isMonoFormat)
905 {
906 _debayer.ConversionPolicy = DebayerConversionPolicy.BayerOnly;
907 _debayer.ChannelLayout = DebayerChannelLayout.RGB;
908 }
909 else
910 {
911 _debayer.ConversionPolicy = DebayerConversionPolicy.BayerAndMono;
912
913 if (info.HasChannel(Channel.Red) && info.HasChannel(Channel.Green)
914 && info.HasChannel(Channel.Blue))
915 {
916 _debayer.ConversionPolicy = DebayerConversionPolicy.BayerAndMono;
917 switch (format)
918 {
919 case PixelFormat.RGB8:
920 case PixelFormat.RGB10:
921 case PixelFormat.RGB12:
922 _debayer.ChannelLayout = DebayerChannelLayout.RGB;
923 break;
924 case PixelFormat.RGBa8:
925 case PixelFormat.RGBa10:
926 case PixelFormat.RGBa12:
927 _debayer.ChannelLayout = DebayerChannelLayout.RGBA;
928 break;
929 case PixelFormat.BGR8:
930 case PixelFormat.BGR10:
931 case PixelFormat.BGR12:
932 _debayer.ChannelLayout = DebayerChannelLayout.BGR;
933 break;
934 case PixelFormat.BGRa8:
935 case PixelFormat.BGRa10:
936 case PixelFormat.BGRa12:
937 _debayer.ChannelLayout = DebayerChannelLayout.BGRA;
938 break;
939 }
940 }
941 }
942
943 _monoConversion.IsEnabled = isMonoFormat;
944
945 _finalConversion.OutputPixelFormat = format;
946
947 var bitDepth = info.StorageBitsPerChannel;
948 _unpack.TargetBitDepth = bitDepth;
949 _debayer.TargetBitDepth = bitDepth;
950 }
951}
IDSImaging.Peak.ICV.Backend.Types.peak_icv_status BackendStatus
IDSImaging.Peak.ICV.Backend.Utils Utils
IDSImaging.Peak.ICV.Pipeline.Types.DebayerChannelLayout DebayerChannelLayout
IDSImaging.Peak.ICV.Pipeline.Types.ProcessingPolicy ProcessingPolicy
IDSImaging.Peak.ICV.Pipeline.Types.DebayerConversionPolicy DebayerConversionPolicy
Base class for implementing a custom pipeline.
Provides information and utility functions for pixel formats. The PixelFormatInfo class offers method...
uint StorageBitsPerChannel
The number of bits used per channel for storage.
Occurs when reading from a file or stream that is incomplete, damaged, or in an unexpected format.
Definition Exception.cs:75
Base class for all exceptions thrown by the library.
Definition Exception.cs:15
Occurs when a required dependency is missing, the library is not initialized, or a misconfiguration a...
Definition Exception.cs:49
Occurs when an operation cannot be performed due to logical constraints (e.g., camera calibration wit...
Definition Exception.cs:102
Occurs when a requested operation is not implemented or supported (e.g., exporting to an unsupported ...
Definition Exception.cs:62
Occurs when a provided value falls outside the allowed valid range.
Definition Exception.cs:128
Image processing pipeline for sequential transformation of raw image frames.
SharpeningFeature Sharpening
Provides access to the sharpening feature for image detail enhancement.
BinningFeature Binning
Provides access to the binning feature for resolution reduction and noise improvement.
IAutoFeature? AutoFeatureModule
Auto feature module for automatic image adjustments.
DecimationFeature Decimation
Provides access to the decimation feature for resolution reduction by pixel skipping.
Image Process(IImageView imageView)
Applies the pipeline to an image view and returns the result as a new image.
Image Process(Image image)
Applies the pipeline to the given image and returns the result as a new image.
GammaFeature Gamma
Provides access to the gamma feature for brightness and contrast adjustments.
void ReleaseBuffers()
Frees unused internal buffers.
ColorCorrectionFeature ColorCorrection
Provides access to the color correction feature for color space transformations.
override void ResetToDefault()
Resets all modules in the pipeline to their default state. Also resets their enabled state.
SaturationFeature Saturation
Provides access to the saturation feature for color intensity adjustments.
override object Process(object input)
Applies the pipeline to the given image and returns the result as a new image.
void Dispose()
Releases all resources used by the DefaultPipeline.
DigitalBlackFeature DigitalBlack
Provides access to the digital black feature for sensor offset correction.
override string TypeId
The pipeline type identifier as a string, primarily used for serialization.
override string ExportSettingsToString()
Converts the current pipeline settings into a string format.
PixelFormat OutputPixelFormat
The current output pixel format as a PixelFormat enum.
HotpixelCorrectionFeature Hotpixel
Provides access to the hot pixel correction feature for defective pixel repair.
ChromaticAdaptionFeature ChromaticAdaption
Provides access to the chromatic adaption feature for adjusting to lighting conditions.
DefaultPipeline()
Creates a DefaultPipeline with default module settings.
MirrorFeature Mirror
Provides access to the mirror feature for image mirroring operations.
GainFeature Gain
Provides access to the gain feature for brightness and white balance adjustments.
override void ImportSettingsFromString(string settings)
Restores pipeline settings from a previously serialized string.
RotationFeature Rotation
Provides access to the rotation feature for image rotation operations.
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 Types.ColorCorrectionMatrix to the image.
Decimation is used to decrease the image size.
Digital black applies digital black correction to an image.
The GainFeature applies gain to the 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 Types.ColorCorrectionMatrix.
Sharpening applies a sharpening filter to enhance image detail.
Color matrix transformation is an image pipeline module that applies a Types.ColorCorrectionMatrix to...
Debayer is an image pipeline module that converts Bayer RAW images into standard color formats.
Downsampling is used to decrease the image size.
Image pipeline module for applying gain to the image.
Definition GainModule.cs:21
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.
Tone curve correction is an image pipeline module that applies digital black correction and inverse g...
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...
Deserializer for reading serialized data and converting it into an IArchive object.
Serializer for writing IArchive objects to an output stream.
Definition Serializer.cs:28
Constructs an Image from an IImageView Instance.
Definition Image.cs:18
Image Copy()
Creates a deep copy of the current Image.
Definition Image.cs:336
Channel
Represents the various data channels in image or spatial data formats. /// This enumeration defines s...
Definition Channel.cs:13
PixelFormat
Each enumerator represents a specific pixel layout and bit-depth, used for interpreting raw image dat...
DownsamplingMode
Mode parameter for the downsampling algorithm.
Interface for modules that provide auto-feature functionality.
void SetGainModule(IGain? gainModule)
Called by the pipeline to set the gain module for the auto-feature module.
Interface for a module used within a pipeline.
Definition IModule.cs:19
object Process(object input)
Processes input data and returns the result.
string TypeId
The unique type identifier for this module implementation.
Definition IModule.cs:32
void ResetToDefault()
Resets the module to its default state.
Represents a hierarchical, strongly-typed key-value archive.
Definition IArchive.cs:79
IArchive GetArchive(string key)
Retrieves a nested archive by key.
IArchive CreateArchive()
Creates a new, empty archive instance of the same concrete type.
IReadOnlyList< IArchive > GetArchiveArray(string key)
Retrieves an array of nested archives by key.
long GetInt64(string key)
Retrieves a 64-bit integer value by key.
void SetArchive(string key, IArchive value)
Stores a nested archive under the specified key.
string GetString(string key)
Retrieves a string value by key.
void SetString(string key, string value)
Stores a string value under the specified key.
void Serialize(IArchive archive)
Serializes the current object into the provided archive.
void Deserialize(IArchive archive)
Deserializes the object's state from the provided archive.
Interface for viewing image pixel data from arbitrary sources.
Definition IImageView.cs:21
Abstract base class for all image processing pipeline features.
Definition IFeature.cs:64
void ResetToDefault()
Restores the feature's default values.