MeVisLab Toolbox Reference
Loading...
Searching...
No Matches
mlKernel.h
Go to the documentation of this file.
1/*************************************************************************************
2**
3** Copyright 2007, MeVis Medical Solutions AG
4**
5** The user may use this file in accordance with the license agreement provided with
6** the Software or, alternatively, in accordance with the terms contained in a
7** written agreement between the user and MeVis Medical Solutions AG.
8**
9** For further information use the contact form at https://www.mevislab.de/contact
10**
11**************************************************************************************/
12
13#ifndef ML_KERNEL_H
14#define ML_KERNEL_H
15
16
18
19// ML-includes
20#include "mlInitSystemKernel.h"
21#include <mlMemory.h>
22#include <cerrno>
23
25
26//-------------------------------------------------------------------------------------------
72//-------------------------------------------------------------------------------------------
73template <typename KDATATYPE> class TKernel
74{
75
76public:
77 //--------------------------------------------------------------------------------------------------------
101 //--------------------------------------------------------------------------------------------------------
125
127 inline TKernel();
128
130 inline TKernel(const TKernel& kern);
131
133 inline virtual ~TKernel();
134
137
139 void reset();
140
142 inline size_t getTabSize() const;
143
150 inline const ImageVector* getCoordTab(size_t dim = 0) const;
151
156 inline const KDATATYPE* getValueTab(size_t dim = 0) const;
157
160
164
168
172
176
179
188 inline const ImageVector& getExtent() const;
189
194 inline const ImageVector& getNegativeExtent() const;
195
197 inline const ImageVector& getPositiveExtent() const;
198
201 static inline MLint coordToIndex(MLint x, MLint y, MLint z, MLint c, MLint t, MLint u, const ImageVector& size);
202
204 static inline MLint coordToIndex(const ImageVector& p, const ImageVector& size);
205
208
211
214
217 MLint findIndex(const ImageVector& pos) const;
218
225 void setPartialKernel(size_t numElems, ImageVector* const coords, KDATATYPE* const values = nullptr);
226
248 std::string getKernel(bool asLines = false, MLint fieldWidth = 0, MLint precision = 10) const;
249
276 std::string setKernel(const std::string& kernString);
277
286 void setKernel(const ImageVector& ext, const KDATATYPE* const values = nullptr, bool* const mask = nullptr);
287
295 template <typename KDATATYPE2> void setKernel(const ImageVector& ext, const KDATATYPE2* const xaxis,
296 const KDATATYPE2* const yaxis, const KDATATYPE2* const zaxis,
297 const KDATATYPE2* const caxis, const KDATATYPE2* const taxis,
298 const KDATATYPE2* const uaxis, bool normalize)
299 {
300 // Clear current separability members.
301 _invalidateSeparableInfos();
302
303 MLint b = 0;
304
305 // Check for valid parameters. Return empty kernel otherwise.
306 if (!xaxis || !yaxis || !zaxis || !caxis || !taxis || !uaxis) {
307 _clearTables();
308 _calculateRealKernelExt();
309 return;
310 }
311
312 // Pointer to matrix which contains the products of the corresponding axis-values
314 static_cast<KDATATYPE*>(Memory::allocateMemory(sizeof(KDATATYPE) * ext.compMul(), ML_FATAL_MEMORY_ERROR));
315
316 for (MLint u = 0; u < ext.u; ++u) {
317 for (MLint t = 0; t < ext.t; ++t) {
318 for (MLint c = 0; c < ext.c; ++c) {
319 for (MLint z = 0; z < ext.z; ++z) {
320 for (MLint y = 0; y < ext.y; ++y) {
321 for (MLint x = 0; x < ext.x; ++x) {
322 valuematrix[b++] =
323 static_cast<KDATATYPE>(xaxis[x] * yaxis[y] * zaxis[z] * caxis[c] * taxis[t] * uaxis[u]);
324 }
325 }
326 }
327 }
328 }
329 }
330
331 setKernel(ext, valuematrix);
332
333 Memory::freeMemory(valuematrix);
334 valuematrix = nullptr;
335
336 // If desired then normalize all kernel elements so that their sum becomes 1.
337 if (normalize) {
338 manipulateKernelElements(KERN_NORMALIZE, 0);
339 }
340 }
341
348 void setSeparableKernel(const std::vector<typename std::vector<KDATATYPE>>& separableRows);
349
355
358
364
368 void mirror(int dimension = -1);
369
373
378 static std::vector<KDATATYPE> get1DGauss(size_t numSamples, bool normalize = true);
379
382
383
384 //-------------------------------------------------------------------------------------------
385 //
388 //
389 // If the kernel is interpreted as a separable kernel then the first six rows
390 // of the first slice of the kernel matrix are taken.
391 // These six rows are interpreted as the six 1-dimensional axis in x,y,z,c,t, and u
392 // dimensions which are used as 1-D filter kernels for a 6D separable filtering.
393 //
394 //
395 // For example:
396 //
397 // | 1 3 5 6 4 |
398 // | 2 7 2 |
399 // | 4 1 9 5 |
400 // | |
401 // | 3 8 3 |
402 // | |
403 //
404 // describes a separable kernel with the following axes extent:
405 // X=5, Y=3, Z=4, C=0, T=3, U=0.
406 // An extent of 0 (for example C and U dimension) is used to describe
407 // that filtering with a 1-D kernel in that dimension is not applied.
408 //
409 //-------------------------------------------------------------------------------------------
414 inline void setSeparable(bool isSeparableVal);
415
418 inline bool isSeparable() const;
419
424
431
438 size_t getSeparableDimIndex(size_t dim = 0) const;
439
442 const std::vector<ImageVector>& getSeparableCoordTab() const;
443
445
446protected:
447 //-------------------------------------------------------------------------------------------
448 //
449 // Protected methods.
450 //
451 //-------------------------------------------------------------------------------------------
452
454 void _init();
455
458
462 void _addCoordinate(const ImageVector& pos, KDATATYPE value, bool update);
463
469
476
479
480
481private:
482 //-------------------------------------------------------------------------------------------
483 //
484 // Member variables.
485 //
486 //-------------------------------------------------------------------------------------------
487
490 ImageVector _ext;
491
493 ImageVector _negExt;
494
496 ImageVector _posExt;
497
500 size_t _tabSize;
501
503 KDATATYPE* _valueTab;
504
506 ImageVector* _coordTab;
507
508
511
514 bool _isSeparable;
515
519
521 mutable bool _areSeparabilityInfosUpToDate;
522
524 mutable ImageVector _separableDimEntries;
525
528 mutable ImageVector _separableOneDimExt;
529
532 mutable ImageVector _separableExt;
533
535 mutable ImageVector _separableNegExt;
536
538 mutable ImageVector _separablePosExt;
539
541 mutable std::vector<ImageVector> _separableCoordTab;
543}; // class TKernel
544
545
546//------------------------------------------------------------------------
547// IMPLEMENTATION PART: No user specific things below.
548//------------------------------------------------------------------------
549
550
551//-------------------------------------------------------------------------------------------
553//-------------------------------------------------------------------------------------------
554template <typename KDATATYPE> TKernel<KDATATYPE>::TKernel()
555{
556 _init();
557}
558
559//-------------------------------------------------------------------------------------------
561//-------------------------------------------------------------------------------------------
562template <typename KDATATYPE> TKernel<KDATATYPE>::TKernel(const TKernel& kern)
563{
564 _init();
565 operator=(kern);
566}
567
568//-------------------------------------------------------------------------------------------
570//-------------------------------------------------------------------------------------------
571template <typename KDATATYPE> TKernel<KDATATYPE>::~TKernel()
572{
573 _clearTables();
574}
575
576//-------------------------------------------------------------------------------------------
577// Assignment operator. Sets current instance to contents of \c kern.
578//-------------------------------------------------------------------------------------------
579template <typename KDATATYPE> const TKernel<KDATATYPE>& TKernel<KDATATYPE>::operator=(const TKernel& kern)
580{
581 // Assign kernel to this if it's not this.
582 if (&kern != this) {
583 // Clean up current kernel table.
584 _clearTables();
585
586 // Set new kernel table size, the kernel voxels and the kernel values.
587 setPartialKernel(kern._tabSize, kern._coordTab, kern._valueTab);
588
589 // Copy mutable members for separable kernel support.
590 _isSeparable = kern._isSeparable;
591 _areSeparabilityInfosUpToDate = kern._areSeparabilityInfosUpToDate;
592 _separableDimEntries = kern._separableDimEntries;
593 _separableOneDimExt = kern._separableOneDimExt;
594 _separableExt = kern._separableExt;
595 _separableNegExt = kern._separableNegExt;
596 _separablePosExt = kern._separablePosExt;
597 _separableCoordTab = kern._separableCoordTab;
598 }
599
600 // Return copy.
601 return *this;
602}
603
604//-------------------------------------------------------------------------------------------
605// Reset kernel to construction state.
606//-------------------------------------------------------------------------------------------
607template <typename KDATATYPE> void TKernel<KDATATYPE>::reset()
608{
609 // Remove dynamic structures.
610 _clearTables();
611
612 // Call constructor initialization. We can do that here, because
613 // all internal tables have been cleared.
614 _init();
615}
616
617//-------------------------------------------------------------------------------------------
618// Returns the current number of kernel elements.
619//-------------------------------------------------------------------------------------------
620template <typename KDATATYPE> size_t TKernel<KDATATYPE>::getTabSize() const
621{
622 if (_isSeparable) {
623 _validateSeparabilityInfos();
624 return getSeparableCoordTab().size();
625 }
626 else {
627 return _tabSize;
628 }
629}
630
631//-------------------------------------------------------------------------------------------
632// Gets a table of coordinates pointing to all kernel elements
633// which are currently defined.
634// The size of the returned table is given by getTabSize().
635// In the case of separable filtering it returns those which are
636// valid for the current pass of separable kernel filtering.
637// It is a subset of the array given by \c getSeparableCoordTab().
638//-------------------------------------------------------------------------------------------
639template <typename KDATATYPE> const ImageVector* TKernel<KDATATYPE>::getCoordTab(size_t dim) const
640{
641 return _isSeparable ? &(getSeparableCoordTab()[getSeparableDimIndex(dim)]) : _coordTab;
642}
643
644//-------------------------------------------------------------------------------------------
645// Gets the table of kernel element values which are currently defined.
646// The size of the returned table is given by getTabSize().
647// In the case of separable filtering the subset of kernel elements
648// for the pass \c dim can be requested.
649//-------------------------------------------------------------------------------------------
650template <typename KDATATYPE> const KDATATYPE* TKernel<KDATATYPE>::getValueTab(size_t dim) const
651{
652 return _isSeparable ? (_valueTab + getSeparableDimIndex(dim)) : _valueTab;
653}
654
655//-------------------------------------------------------------------------------------------
656// Return the sum of all kernel element values
657//-------------------------------------------------------------------------------------------
658template <typename KDATATYPE> KDATATYPE TKernel<KDATATYPE>::getValueTabSum() const
659{
660 // Scan all elements of the value table and sum them up.
661 KDATATYPE v = 0;
662 for (size_t i = 0; i < _tabSize; i++) {
663 v += _valueTab[i];
664 }
665 return v;
666}
667
668//-------------------------------------------------------------------------------------------
669// Return the minimum value of all kernel element values
670// If kernel value table is empty then 0 is returned.
671//-------------------------------------------------------------------------------------------
672template <typename KDATATYPE> KDATATYPE TKernel<KDATATYPE>::getMinValue() const
673{
674 // Scan all elements of the value table and search the minimum.
675 KDATATYPE v = (_tabSize == 0) ? static_cast<KDATATYPE>(0) : _valueTab[0];
676 for (size_t i = 1; i < _tabSize; i++) {
677 if (_valueTab[i] < v) {
678 v = _valueTab[i];
679 }
680 }
681 return v;
682}
683
684//-------------------------------------------------------------------------------------------
685// Return the maximum value of all kernel element values
686// If kernel value table is empty then 1 is returned.
687//-------------------------------------------------------------------------------------------
688template <typename KDATATYPE> KDATATYPE TKernel<KDATATYPE>::getMaxValue() const
689{
690 // Scan all elements of the value table and search the minimum.
691 KDATATYPE v = (_tabSize == 0) ? static_cast<KDATATYPE>(1) : _valueTab[0];
692 for (size_t i = 1; i < _tabSize; i++) {
693 if (_valueTab[i] > v) {
694 v = _valueTab[i];
695 }
696 }
697 return v;
698}
699
700
701//-------------------------------------------------------------------------------------------
702// Return the sum of all negative kernel element values.
703// If kernel value table is empty then 0 is returned.
704//-------------------------------------------------------------------------------------------
705template <typename KDATATYPE> KDATATYPE TKernel<KDATATYPE>::getNegativeValueSum() const
706{
707 KDATATYPE v = 0;
708 for (size_t i = 0; i < _tabSize; i++) {
709 // Make checks for not "> 0" instead of "< 0" to avoid warnings on unsigned KDATATYPEs.
710 if (!(_valueTab[i] > 0)) {
711 v += _valueTab[i];
712 }
713 }
714 return v;
715}
716
717//-------------------------------------------------------------------------------------------
718// Return the sum of all positive kernel element values.
719// If kernel value table is empty then 0 is returned.
720//-------------------------------------------------------------------------------------------
721template <typename KDATATYPE> KDATATYPE TKernel<KDATATYPE>::getPositiveValueSum() const
722{
723 KDATATYPE v = 0;
724 for (size_t i = 0; i < _tabSize; i++) {
725 if (_valueTab[i] > 0) {
726 v += _valueTab[i];
727 }
728 }
729 return v;
730}
731
732
733//-------------------------------------------------------------------------------------------
734// Modify all kernel element values with the value \c v.
735//-------------------------------------------------------------------------------------------
736template <typename KDATATYPE> void TKernel<KDATATYPE>::manipulateKernelElements(KernModifier mode, KDATATYPE v)
737{
738 // Invalidate current information for separable kernels.
739 _invalidateSeparableInfos();
740
741 switch (mode) {
742 case KERN_SET:
743 {
744 // Set each kernel element to v.
745 for (size_t i = 0; i < _tabSize; i++) {
746 _valueTab[i] = v;
747 }
748 } break;
749
750 case KERN_MULT:
751 {
752 // Multiply each kernel element with v.
753 for (size_t i = 0; i < _tabSize; i++) {
754 _valueTab[i] *= v;
755 }
756 } break;
757
758 case KERN_ADD:
759 {
760 // Add v to each kernel element.
761 for (size_t i = 0; i < _tabSize; i++) {
762 _valueTab[i] += v;
763 }
764 } break;
765
766 case KERN_INVDIV:
767 {
768 // Set each kernel element to v / kernelElement. Zero kernel elements are left unchanged.
769 for (size_t i = 0; i < _tabSize; i++) {
770 if (!MLValueIs0WOM(_valueTab[i])) {
771 _valueTab[i] = v / _valueTab[i];
772 }
773 }
774 } break;
775
776 case KERN_INVSUB:
777 {
778 // Set each kernel element by v - kernelElement.
779 for (size_t i = 0; i < _tabSize; i++) {
780 _valueTab[i] = v - _valueTab[i];
781 }
782 } break;
783
784 case KERN_SQR:
785 {
786 // Compute all squares of _valueTab[i].
787 for (size_t i = 0; i < _tabSize; i++) {
788 _valueTab[i] *= _valueTab[i];
789 }
790 } break;
791
792 case KERN_SQRT:
793 {
794 // Compute all square roots of _valueTab[i]. Negative kernel elements
795 // are left unchanged.
796 for (size_t i = 0; i < _tabSize; i++) {
797 // We do not use >= because but two comparisons to avoid warnings
798 // in case of unsigned KDATATYPE.
799 if ((_valueTab[i] > 0) || (MLValueIs0WOM(_valueTab[i]))) {
800 // As documented in class description we cast in case of integer KDATATYPES.
801 _valueTab[i] = static_cast<KDATATYPE>(sqrt(static_cast<double>(_valueTab[i])));
802 }
803 }
804 } break;
805
806 case KERN_POW:
807 {
808 // Compute all _valueTab[i] raised to the power of v.
809 for (size_t i = 0; i < _tabSize; i++) {
810 // Linux man page says: Error on "The argument x is negative and y is not an integral value.
811 // This would result in a complex number." This then will set errno (EDOM).
812 // So we leave kernel elements unchanged in that case. We do not use >= because but
813 // two comparisons to avoid warnings in case of unsigned KDATATYPE.
814 if ((_valueTab[i] > static_cast<KDATATYPE>(0)) || MLValueIs0WOM(_valueTab[i])) {
815 // As documented in class description we cast in case of integer KDATATYPES.
816 errno = 0;
817 KDATATYPE buf = static_cast<KDATATYPE>(powl(_valueTab[i], v));
818 if (0 == errno) {
819 _valueTab[i] = buf;
820 }
821 }
822 }
823 } break;
824
825 case KERN_LOG:
826 {
827 // Compute logarithm of base v of all kernel elements.
828 // Do not apply operations on kernel elements which are not permitted,
829 // e.g. negative bases or negative values or base == 1. In that case
830 // leave kernel elements unchanged.
831 // For LOGv(K) we use log(K)/log(v) instead.
832 if ((v > 0) && (MLValuesDifferWOM(v, static_cast<KDATATYPE>(1)))) {
833 MLdouble invBase = 1.0 / log(static_cast<double>(v));
834 for (size_t i = 0; i < _tabSize; i++) {
835 KDATATYPE val = _valueTab[i];
836 // As documented in class description we cast in case of integer KDATATYPES.
837 if (val > 0) {
838 _valueTab[i] = static_cast<KDATATYPE>(log(static_cast<double>(val)) * invBase);
839 }
840 }
841 }
842 } break;
843
844 case KERN_NORMALIZE:
845 {
846 // Multiply all kernel element values with a value so that their sum is 1.
847 // If sum is zero then values are left unchanged.
848 KDATATYPE sum = getValueTabSum();
849 // As documented in class description we cast in case of integer KDATATYPES.
850 if (!MLValueIs0WOM(sum)) {
851 manipulateKernelElements(KERN_MULT, static_cast<KDATATYPE>(1. / sum));
852 }
853 } break;
854
855 case KERN_GAUSS:
856 {
857 // Set all kernel elements to binomial values and normalize.
858 setGauss(_ext);
859 } break;
860
861 case KERN_SPHERE:
862 {
863 // Throw away kernel corners to make it approximately spherical.
864 makeCircular();
865 } break;
866
867 case KERN_MIRROR:
868 {
869 // Apply mirroring operation.
870 mirror();
871 } break;
872
873 case KERN_MIRROR_X:
874 {
875 // Apply mirroring operation in x dimension.
876 mirror(0);
877 } break;
878
879 case KERN_MIRROR_Y:
880 {
881 // Apply mirroring operation in y dimension.
882 mirror(1);
883 } break;
884
885 case KERN_MIRROR_Z:
886 {
887 // Apply mirroring operation in z dimension.
888 mirror(2);
889 } break;
890
891 case KERN_MIRROR_C:
892 {
893 // Apply mirroring operation in c dimension.
894 mirror(3);
895 } break;
896
897 case KERN_MIRROR_T:
898 {
899 // Apply mirroring operation in t dimension.
900 mirror(4);
901 } break;
902
903 case KERN_MIRROR_U:
904 {
905 // Apply mirroring operation in u dimension.
906 mirror(5);
907 } break;
908
909 case NUM_KERN_MODIFYERS:
910 {
911 ML_PRINT_ERROR("TKernel<KDATATYPE>::manipulateKernelElements(mlKernModifier mode, KDATATYPE v)",
912 ML_PROGRAMMING_ERROR, "NUM_KERN_MODIFYERS is an invalid parameter. Ignoring kernel manipulation.");
913 } break;
914
915 default:
916 {
917 ML_PRINT_ERROR("TKernel<KDATATYPE>::manipulateKernelElements(mlKernModifier mode, KDATATYPE v)", ML_BAD_PARAMETER,
918 "Invalid parameter passed. Ignoring kernel manipulation.");
919 } break;
920 }
921}
922
923//-------------------------------------------------------------------------------------------
924// Returns the kernel extents in 6D. It defines the rectangular region in
925// which all coordinates returned by \c getCoordTab() are found.
926// Note that the returned region might be larger than required
927// e.g. after removing elements from kernel.
928// In the case of separable filtering it returns a vector where the
929// components 0,...,5 contain the extent of the region spanned by the
930// 6 separated 1-D kernels. Note that components for those dimensions
931// where no filtering takes place are set to 1.
932//-------------------------------------------------------------------------------------------
933template <typename KDATATYPE> const ImageVector& TKernel<KDATATYPE>::getExtent() const
934{
935 if (_isSeparable) {
936 _validateSeparabilityInfos();
937 return _separableExt;
938 }
939 else {
940 return _ext;
941 }
942}
943
944//-------------------------------------------------------------------------------------------
945// The extent of the kernel to both sides. The sum of both +1 is the extent of the kernel.
946// Using \c getNegativeExtent() as negative extent of an image and \c getPositiveExtent() as positive extent
947// increment for the image then the kernel can be placed correctly on all normal image
948// voxels without having voxel accesses out of range.
949//-------------------------------------------------------------------------------------------
950template <typename KDATATYPE> const ImageVector& TKernel<KDATATYPE>::getNegativeExtent() const
951{
952 if (_isSeparable) {
953 _validateSeparabilityInfos();
954 return _separableNegExt;
955 }
956 else {
957 return _negExt;
958 }
959}
960
961//-------------------------------------------------------------------------------------------
962// See \c getNegativeExtent().
963//-------------------------------------------------------------------------------------------
964template <typename KDATATYPE> const ImageVector& TKernel<KDATATYPE>::getPositiveExtent() const
965{
966 if (_isSeparable) {
967 _validateSeparabilityInfos();
968 return _separablePosExt;
969 }
970 else {
971 return _posExt;
972 }
973}
974
975//-------------------------------------------------------------------------------------------
976// Converts the coordinate (x,y,z,c,t,u) into the kernel to an index into an array
977// with 6D extents given by \c size.
978//-------------------------------------------------------------------------------------------
979template <typename KDATATYPE>
981{
982 return SubImage::coordToIndex(x, y, z, c, t, u, size);
983}
984
985//-------------------------------------------------------------------------------------------
986// Converts the coordinate \p into the kernel with extents \c size to an index.
987//-------------------------------------------------------------------------------------------
988template <typename KDATATYPE> MLint TKernel<KDATATYPE>::coordToIndex(const ImageVector& p, const ImageVector& size)
989{
990 return SubImage::coordToIndex(p, size);
991}
992
993//-------------------------------------------------------------------------------------------
994// Converts an index into an array with extents \c ext to a coordinate.
995//-------------------------------------------------------------------------------------------
997{
998 return SubImage::indexToCoord(idx, ext);
999}
1000
1001//-------------------------------------------------------------------------------------------
1003//-------------------------------------------------------------------------------------------
1005{
1006 return ImageVector(ext.x / 2, ext.y / 2, ext.z / 2, ext.c / 2, ext.t / 2, ext.u / 2);
1007}
1008
1009//-------------------------------------------------------------------------------------------
1011//-------------------------------------------------------------------------------------------
1013{
1014 return ImageVector(ext.x - ext.x / 2 - 1, ext.y - ext.y / 2 - 1, ext.z - ext.z / 2 - 1, ext.c - ext.c / 2 - 1,
1015 ext.t - ext.t / 2 - 1, ext.u - ext.u / 2 - 1);
1016}
1017
1018//-------------------------------------------------------------------------------------------
1019// Return index to kernel element if it exists; otherwise return -1.
1020// Note that this method needs to search; so it's not very efficient.
1021//-------------------------------------------------------------------------------------------
1022template <typename KDATATYPE> MLint TKernel<KDATATYPE>::findIndex(const ImageVector& pos) const
1023{
1024 // Search coordinate in _coordtab.
1025 for (size_t c = 0; c < _tabSize; c++) {
1026 if (_coordTab[c] == pos) {
1027 return c;
1028 }
1029 }
1030
1031 return -1;
1032}
1033
1034//-------------------------------------------------------------------------------------------
1035// Defines a set of local kernel coordinates and optionally a set
1036// of values which define the kernel elements.
1037// \c numElems defines the number of coordinates.
1038// If desired the corresponding set of kernel values can be passed in \c values.
1039// Otherwise all kernel values are set to (KDATATYPE)(1.0/(KDATATYPE)_tabSize).
1040// Note that \c coords and \c values have to contain \c numElems entries if passed.
1041//-------------------------------------------------------------------------------------------
1042template <typename KDATATYPE>
1044{
1045 // Clear all dynamic tables.
1046 _clearTables();
1047
1048 // Define the new number of kernel voxels.
1049 _tabSize = numElems;
1050
1051 // Recreate the coordinate and value tables
1052 if (_tabSize > 0) {
1053 _coordTab = new ImageVector[_tabSize];
1054
1055 _valueTab = new KDATATYPE[_tabSize];
1056
1057 // Copy all passed coordinates into the coordinate table.
1058 for (size_t c = 0; c < _tabSize; c++) {
1059 _coordTab[c] = coords[c];
1060 }
1061
1062 // If we have a user defined value table then copy it.
1063 // Otherwise fill table with values 1.0/static_cast<KDATATYPE>(_tabSize).
1064 if (values) {
1065 memcpy(_valueTab, values, _tabSize * sizeof(KDATATYPE));
1066 }
1067 else {
1068 // As documented in class description we cast in case of integer KDATATYPES.
1069 KDATATYPE v = static_cast<KDATATYPE>(1.0 / static_cast<KDATATYPE>(_tabSize));
1070 for (size_t d = 0; d < _tabSize; d++) {
1071 _valueTab[d] = v;
1072 }
1073 }
1074 }
1075
1076 // Calculate the real kernel size, i.e. the bounding box around all
1077 // used kernel elements.
1078 _calculateRealKernelExt();
1079}
1080
1081
1082//-------------------------------------------------------------------------------------------
1083// Returns the current kernel elements and values as string:
1084// The string needs has the following format:
1085//
1086// \code
1087//
1088// (x_0, y_0, z_0, c_0, t_0, u_0):v_0
1089// ...
1090// (x_n, y_n, z_n, c_n, t_n, u_n):v_n
1091//
1092// \endcode
1093//
1094// where the coordinates left from ':' specify the 6d coordinate
1095// of the kernel element; the value v_x right from ':' specifies the
1096// value of the kernel element.
1097// If asLines is true then a second string format is used:
1098//
1099// \code
1100//
1101// (*, y_0, z_0, c_0, t_0, u_0):x_0 ... x_n
1102// ...
1103// (*, y_n, z_n, c_n, t_n, u_n):y_n ... y_n
1104//
1105// \endcode
1106//
1107// So all kernel elements of a row are saved in a string line; so
1108// the x coordinates becomes invalid and is set as an asterisk.
1109// To have a minimum field width pass \c fieldWidth and the digits after
1110// the period if given by \c precision. Note that these settings are used
1111// only if asLines is true.
1112//-------------------------------------------------------------------------------------------
1113template <typename KDATATYPE>
1115{
1116 std::string str = "";
1117 char strLine[256] = "";
1118
1119 // Clamp field width to sensible values.
1120 if (fieldWidth > 128) {
1121 fieldWidth = 128;
1122 }
1123 if (fieldWidth < 0) {
1124 fieldWidth = 0;
1125 }
1126
1127 if (asLines) {
1128 // Print kernel as lines.
1129 for (MLint u = 0; u < getExtent().u; u++) {
1130 for (MLint t = 0; t < getExtent().t; t++) {
1131 for (MLint c = 0; c < getExtent().c; c++) {
1132 for (MLint z = 0; z < getExtent().z; z++) {
1133 for (MLint y = 0; y < getExtent().y; y++) {
1134 // Print line start into string.
1135 snprintf(strLine, 255, "(*,%lld,%lld,%lld,%lld,%lld):", y, z, c, t, u);
1136
1137 // To compensate line start differences if any component has more than
1138 // one digit do append spaces until string has at least 16 chars. So
1139 // two components may have more than one digit or one can have two more digits.
1140 while (strlen(strLine) < 16) {
1141 strcat(strLine, " ");
1142 }
1143
1144 // Add Line start to existing kernel string.
1145 str += strLine;
1146
1147 // Add all row elements of the kernel to the string.
1148 for (MLint x = 0; x < getExtent().x; x++) {
1149 // Does the element exist?
1150 MLint idx = findIndex(ImageVector(x, y, z, c, t, u));
1151 if (idx < 0) {
1152 // Kernel element does not exist.
1153 // Fill field with fieldWidth spaces and add ','. Then terminate string.
1154 // For the first field do not add a comma. So we have one more space then
1155 // in those cases where we have a comma in it. So we need to add one space
1156 // more in cases with comma.
1157 strLine[0] = x == 0 ? ' ' : ',';
1158 MLint w = x == 0 ? fieldWidth : fieldWidth + 1;
1159 for (MLint i = 1; i < w; i++) {
1160 strLine[i] = ' ';
1161 }
1162 strLine[w] = 0;
1163 }
1164 else {
1165 // Print comma and element if it's not the last one; otherwise print only the element.
1166 // integrate field width for float field of aligned size. Always cast
1167 // element values to double because string reading and parsing of extended
1168 // types would lead to further problems.
1169 // Hence we store only scalar values.
1170 char format[64];
1171 snprintf(format, 63, "%s%%%d.%dlf", "%s", static_cast<MLint32>(fieldWidth),
1172 static_cast<MLint32>(precision));
1173 snprintf(strLine, 255, format, 0 == x ? "" : ",", static_cast<MLdouble>(_valueTab[idx]));
1174 }
1175
1176 // Append (empty) element to the end of the line.
1177 str += strLine;
1178 }
1179 // Terminate line with '\n'
1180 str += '\n';
1181 }
1182 // Add an empty line between xy planes of the kernel.
1183 str += '\n';
1184 } // z
1185 } // c
1186 } // t
1187 } // u
1188 }
1189 else {
1190 // Print each kernel element into a string and append it to the entire kernel string.
1191 for (size_t c = 0; c < _tabSize; c++) {
1192 ImageVector coord = _coordTab[c];
1193 KDATATYPE value = _valueTab[c];
1194 snprintf(strLine, 255, "%s:%lf\n", coord.print("(", ",", ")").c_str(), static_cast<MLdouble>(value));
1195 str += strLine;
1196 }
1197 }
1198
1199 return str;
1200}
1201
1202
1203//-------------------------------------------------------------------------------------------
1204// Defines elements and values of the kernel matrix by a string.
1205// The string needs to have the following format:
1206//
1207// \code
1208//
1209// (x_0, y_0, z_0, c_0, t_0, u_0):v_0
1210// ...
1211// (x_n, y_n, z_n, c_n, t_n, u_n):v_n
1212//
1213// \endcode
1214//
1215// where the coordinates left from ':' specify the 6d coordinate
1216// of the kernel element; the value v_x right from ':' specifies the
1217// value of the kernel element. Only one coordinate entry is scanned per line.
1218// So big kernels with a few elements can be set easily. As long as lines with
1219// kernel elements are found elements are set in the kernel table.
1220// Return string is empty on successful scan. On errors it contains the number
1221// of error lines.
1222//
1223// A second way to specify more kernel elements at once is with the
1224// following string line format:
1225//
1226// \code
1227//
1228// (*, y_0, z_0, c_0, t_0, u_0):x_0, ... ,x_n
1229// ...
1230// (*, y_n, z_n, c_n, t_n, u_n):y_n, ... ,y_n
1231//
1232// \endcode
1233//
1234// So all kernel elements of a row are found in a string line. Note
1235// that the x coordinates becomes invalid and must set as an asterisk.
1236// Empty elements in the kernel can be left empty before between and
1237// after commas.
1238//-------------------------------------------------------------------------------------------
1239template <typename KDATATYPE> std::string TKernel<KDATATYPE>::setKernel(const std::string& kernString)
1240{
1241 // Initialize an error string to return error line numbers.
1242 std::string errStr = "";
1243 char* copy = nullptr;
1244
1245 // Make kernel empty.
1246 reset();
1247
1248 // Scan only if string contains enough characters to specify one kernel element.
1249 if (kernString.length() < 15) {
1250 // String too short to specify a valid kernel. Return 0 as error line.
1251 errStr = "0";
1252 return errStr;
1253 }
1254 else {
1255 // Get a modifiable copy of the string.
1256 std::string str = kernString;
1257
1258 // Assure that a line feed terminates the string.
1259 if (str[str.length() - 1] != '\n') {
1260 str += '\n';
1261 }
1262
1263 // Scan line by line until no valid line is found.
1264 MLint lineNumber = 0;
1265 while (str != "") {
1266 // Scan line for following format : "(x,y,z,c,t,u):v"
1267 MLint x = 0, y = 0, z = 0, c = 0, t = 0, u = 0, num = 0;
1268 MLdouble fValue = 0;
1269 num = sscanf(str.c_str(), "(%lld,%lld,%lld,%lld,%lld,%lld):%lf", &x, &y, &z, &c, &t, &u, &fValue);
1270 KDATATYPE value = static_cast<KDATATYPE>(fValue);
1271 if (num == 7) {
1272 // Okay, we found a valid line. Add values to kernel coordinate table.
1273 _addCoordinate(ImageVector(x, y, z, c, t, u), value, false);
1274 }
1275 else {
1276 // Line is invalid. Test for the line format.
1277 num = sscanf(str.c_str(), "(*,%lld,%lld,%lld,%lld,%lld):", &y, &z, &c, &t, &u);
1278 if (5 == num) {
1279 // Yes, the line format is ok. So search ":".
1280 const size_t cPos = str.find(':');
1281 if (cPos != std::string::npos) {
1282 // Yes, found. First part of line has already been scanned and so removed it.
1283 str.erase(0, cPos + 1);
1284
1285 // Flag to stop line scan and counter for number of scanned elements.
1286 bool go = true;
1287 MLint xCoord = 0;
1288
1289 // Scan until we reach at end of line or an error occurs.
1290 while (go && (str.length() != 0)) {
1291 const char ch = str[0];
1292
1293 // Kill space characters and continue.
1294 if (' ' == ch) {
1295 str.erase(0, 1);
1296 }
1297
1298 // Line end? Then finish line scan.
1299 else if ('\n' == ch) {
1300 // Terminate loop and leave '\n' because later it's searched.
1301 go = false;
1302 }
1303
1304 // Colon? Then increase element number count and kill colon.
1305 else if (',' == ch) {
1306 // Go forward to next kernel element in row and remove comma.
1307 ++xCoord;
1308 str.erase(0, 1);
1309 }
1310 else {
1311 // No space, no comma, so try to scan a number.
1312
1313 // First char where a number incompatible character is found.
1314 char* stopPos = nullptr;
1315
1316 // Copy string.
1317 copy = Memory::duplicateString(str.c_str(), ML_FATAL_MEMORY_ERROR);
1318 if (copy) {
1319 // Scan string for number.
1320 const MLdouble val = strtod(copy, &stopPos);
1321
1322 // More than 0 characters scanned successfully?
1323 if (stopPos != copy) {
1324 // Yes, a number at beginning. Add it at the right position in the kernel.
1325 _addCoordinate(ImageVector(xCoord, y, z, c, t, u), static_cast<KDATATYPE>(val), false);
1326
1327 // Remove number at start of string. Use pointer arithmetics to
1328 // determine number of scanned number characters.
1329 str.erase(0, stopPos - copy);
1330 }
1331 else {
1332 // No parsing possible, there must be an error. So terminate scan of this line.
1333 go = false;
1334
1335 // Add line number to error string.
1336 char err[30] = "";
1337 snprintf(err, 29, " %lld", lineNumber);
1338 errStr += err;
1339 }
1340 }
1341
1342 // Remove copy of line.
1343 if (copy) {
1344 Memory::freeMemory(copy);
1345 copy = nullptr;
1346 }
1347 } // else
1348 } // while
1349 } // if (cPos != std::string::npos)
1350 } // if (num == 5)
1351 } // else
1352
1353 // Last line?
1354 const size_t pos = str.find('\n');
1355 if (pos != std::string::npos) {
1356 // Not the last line, because scanned linefeed is not at end of string.
1357 // So remove line from string.
1358 str.erase(0, pos + 1);
1359 }
1360 else {
1361 // Last line. Make string empty to terminate loop.
1362 str = "";
1363 }
1364
1365 // Increase number of scanned lines.
1366 lineNumber++;
1367 } // while (str != "")
1368 } // else
1369
1370 // Update the real kernel size.
1371 _calculateRealKernelExt();
1372
1373 return errStr;
1374}
1375
1376
1377//-------------------------------------------------------------------------------------------
1378// Defines a complete kernel matrix whose extents are defined by \c ext.
1379// If desired the set of kernel values can be passed in \c values.
1380// Otherwise all kernel values are set to 1.0/(KDATATYPE)ext.compMul(), i.e.
1381// to the number of entries of the matrix.
1382// If desired a set of mask values can be specified. If \c mask[n] is true then
1383// tab[n] is included in the kernel; otherwise it's not part of the kernel.
1384// Internally the specified kernel matrix is handled as a table of kernel elements.
1385// Note that \c values and \c mask must have ext.compMul() elements if they are defined.
1386//-------------------------------------------------------------------------------------------
1387template <typename KDATATYPE>
1388void TKernel<KDATATYPE>::setKernel(const ImageVector& ext, const KDATATYPE* const values, bool* const mask)
1389{
1390 // Clear all dynamic tables.
1391 _clearTables();
1392
1393 // Compute maximum size of value and kernel table.
1394 size_t maxElems = ext.compMul();
1395
1396 // Do we have a mask ? Then count number of enabled kernel elements.
1397 _tabSize = 0;
1398 if (mask) {
1399 for (size_t c = 0; c < maxElems; c++) {
1400 if (mask[c]) {
1401 _tabSize++;
1402 }
1403 }
1404 }
1405 else {
1406 // No mask set. All kernel elements are used.
1407 _tabSize = maxElems;
1408 }
1409
1410 // Recreate the coordinate and value tables with the size of used elements.
1411 if (_tabSize > 0) {
1412 _coordTab = new ImageVector[_tabSize];
1413 _valueTab = new KDATATYPE[_tabSize];
1414 if (!_coordTab || !_valueTab) {
1415 _clearTables();
1417 "TKernel<KDATATYPE>::setKernel(...):", ML_NO_MEMORY,
1418 "Cannot create kernel filter tables, so tables are reset. This will probably cause other errors.");
1419 }
1420
1421 if (_coordTab && _valueTab) {
1422 // If we have a user defined value table then copy it.
1423 // Otherwise fill table with values 1.0/(KDATATYPE)_tabSize.
1424 if (values) {
1425 memcpy(_valueTab, values, _tabSize * sizeof(KDATATYPE));
1426 }
1427 else {
1428 // As documented in class description we cast in case of integer KDATATYPES.
1429 KDATATYPE v = static_cast<KDATATYPE>(1.0 / static_cast<KDATATYPE>(_tabSize));
1430 for (size_t d = 0; d < _tabSize; d++) {
1431 _valueTab[d] = v;
1432 }
1433 }
1434
1435 // Define all kernel coordinates if no mask exists or if the mask exists and the
1436 // entry for the current kernel voxel is true.
1437 size_t idx = 0;
1438 for (size_t e = 0; e < maxElems; e++) {
1439 if (!mask || (mask && mask[e])) {
1440 _coordTab[idx] = indexToCoord(e, ext);
1441 idx++;
1442 }
1443 }
1444
1445 if (idx != _tabSize) {
1447 "TKernel<KDATATYPE>::setKernel(...):", ML_CALCULATION_ERROR,
1448 "Internal error. Cannot create kernel filter tables. This will probably cause other errors.");
1449 _clearTables();
1450 }
1451 } // if (_coordTab && _valueTab)
1452 }
1453
1454 // Calculate the real kernel size, i.e. the bounding box around all
1455 // used kernel elements.
1456 _calculateRealKernelExt();
1457}
1458
1459
1460//-------------------------------------------------------------------------------------------
1461// Create kernel coordinate and value tables in separable table format, that means
1462// a 2-D kernel where each rows describes the elements of 1-D kernels.
1463// At most 6 rows make sense, because the maximum kernel dimension is 6.
1464// It is legal to leave out any axis by passing empty vectors to define lower
1465// dimensional separable kernels.
1466// The separability flag is set to true.
1467//-------------------------------------------------------------------------------------------
1468template <typename KDATATYPE>
1469void TKernel<KDATATYPE>::setSeparableKernel(const std::vector<typename std::vector<KDATATYPE>>& separableRows)
1470{
1471 setSeparable(true);
1472 _clearTables();
1473
1474 // Get number of rows, permit at most 6 for 6 dimensions.
1475 const size_t numRows = separableRows.size() > 6 ? 6 : separableRows.size();
1476
1477 // Sum up total number of entries in all rows.
1478 size_t numEntries = 0;
1479 for (size_t e = 0; e < numRows; ++e) {
1480 numEntries += separableRows[e].size();
1481 }
1482
1483 // Create a value table and a coordinate table.
1484 std::vector<KDATATYPE> valueTab;
1485 valueTab.reserve(numEntries);
1486 std::vector<ImageVector> coordTab;
1487 coordTab.reserve(numEntries);
1488
1489 // Compose coordinate table.
1490 for (size_t r = 0; r < numRows; ++r) {
1491
1492 // Get row and its number of elements.
1493 const std::vector<KDATATYPE>& row = separableRows[r];
1494 const size_t numRElements = row.size();
1495
1496 // Coordinate in the separable table, only x and y coordinates are set.
1497 // y defines the dimension, x defines the position in that dimension.
1499 entryCoord.y = r;
1500
1501 // Count entries with row.
1502 for (size_t re = 0; re < numRElements; ++re) {
1503 // Define x-coordinate of entry in table row.
1504 entryCoord.x = re;
1505 coordTab.push_back(entryCoord);
1506 valueTab.push_back(row[re]);
1507 }
1508 }
1509
1510 // Define the kernel table. The extent is 2-D, because it's the
1511 // separable table format.
1512 setPartialKernel(coordTab.size(), &(coordTab[0]), &(valueTab[0]));
1513
1514 // Make separable information up to date.
1515 _validateSeparabilityInfos();
1516}
1517
1518
1519//-------------------------------------------------------------------------------------------
1520// Resizes the kernel to a new state and tries to maintain the previous elements
1521// if possible. Note that new kernel size may differ from desired one if empty
1522// areas are at border of the resized kernel so that only a smaller real kernel remains.
1523// Regions which are created newly get kernel elements with value \c newVal.
1524//-------------------------------------------------------------------------------------------
1525template <typename KDATATYPE> void TKernel<KDATATYPE>::resizeKernel(const ImageVector& ext, KDATATYPE newVal)
1526{
1527 // Create a buffer kernel.
1529
1530 // Clear all dynamic tables.
1531 _clearTables();
1532
1533 // Scan new kernel extents.
1534 for (MLint u = 0; u < ext.u; u++) {
1535 for (MLint t = 0; t < ext.t; t++) {
1536 for (MLint c = 0; c < ext.c; c++) {
1537 for (MLint z = 0; z < ext.z; z++) {
1538 for (MLint y = 0; y < ext.y; y++) {
1539 for (MLint x = 0; x < ext.x; x++) {
1540 // Create vector from new coordinates.
1541 ImageVector addCoord(x, y, z, c, t, u);
1542
1543 // If new coordinate is within old kernel range the add it only if it exists.
1544 if ((u < getExtent().u) && (t < getExtent().t) && (c < getExtent().c) && (z < getExtent().z) &&
1545 (y < getExtent().y) && (x < getExtent().x))
1546 {
1547 // Within old extents. Is it defined?
1548 MLint idx = bufferKern.findIndex(addCoord);
1549 if (idx >= 0) {
1550 // Old coordinate existed. So add it to new kernel without extent updating.
1551 _addCoordinate(addCoord, bufferKern.getValueTab()[idx], false);
1552 }
1553 }
1554 else {
1555 // New coordinate is outside old range. Add newVal's in new area.
1556 _addCoordinate(addCoord, newVal, false);
1557 } // else
1558
1559 } // x
1560 }
1561 }
1562 }
1563 }
1564 } // u
1565
1566 // Calculate the real kernel size, i.e. the bounding box around all
1567 // used kernel elements.
1568 _calculateRealKernelExt();
1569}
1570
1571
1572//-------------------------------------------------------------------------------------------
1573// Fill all undefined kernel elements with \c newVal.
1574//-------------------------------------------------------------------------------------------
1576{
1577 // Invalidate current information for separable kernels.
1578 _invalidateSeparableInfos();
1579
1580 // Scan new kernel extents.
1581 for (MLint u = 0; u < getExtent().u; u++) {
1582 for (MLint t = 0; t < getExtent().t; t++) {
1583 for (MLint c = 0; c < getExtent().c; c++) {
1584 for (MLint z = 0; z < getExtent().z; z++) {
1585 for (MLint y = 0; y < getExtent().y; y++) {
1586 for (MLint x = 0; x < getExtent().x; x++) {
1587 // Create vector from new coordinates.
1588 ImageVector addCoord(x, y, z, c, t, u);
1589
1590 // Does the coordinate exist in kernel?
1591 if (findIndex(addCoord) < 0) {
1592 // Coordinate does not exits. So add it without extent updating.
1593 _addCoordinate(addCoord, newVal, false);
1594 } // if
1595
1596 } // x
1597 }
1598 }
1599 }
1600 }
1601 } // u
1602
1603 // Calculate the real kernel size, i.e. the bounding box around all
1604 // used kernel elements.
1605 _calculateRealKernelExt();
1606}
1607
1608
1609//-------------------------------------------------------------------------------------------
1610// Takes the current kernel, computes radii from the extents of the kernel
1611// and removes all kernel elements which are outside the ellipsoid defined by
1612// these radii.
1613// Note that filter properties of kernel changes by this operation.
1614//-------------------------------------------------------------------------------------------
1615template <typename KDATATYPE> void TKernel<KDATATYPE>::makeCircular()
1616{
1617 // Invalidate current information for separable kernels.
1618 _invalidateSeparableInfos();
1619
1620 // Compute theoretical center of kernel. Subtract 0.5 to shift
1621 // kernel center from voxel center to voxel origin. Examples in 3D:
1622 // E.g. : (1,1,1) sized kernels are addressed from 0 to 0 and so they have
1623 // their center at (0,0,0)\n
1624 // E.g. : (2,2,2) sized kernels are addressed from 0 to 1 and so they have
1625 // their center at (0.5, 0.5, 0.5).\n
1626 // E.g. : (3,3,3) sized kernels are addressed from 0 to 2 and so they have
1627 // their center at (1.0, 1.0, 1.0).\n
1628 MLdouble cx = static_cast<MLdouble>(_ext.x) / 2.0 - 0.5;
1629 MLdouble cy = static_cast<MLdouble>(_ext.y) / 2.0 - 0.5;
1630 MLdouble cz = static_cast<MLdouble>(_ext.z) / 2.0 - 0.5;
1631 MLdouble cc = static_cast<MLdouble>(_ext.c) / 2.0 - 0.5;
1632 MLdouble ct = static_cast<MLdouble>(_ext.t) / 2.0 - 0.5;
1633 MLdouble cu = static_cast<MLdouble>(_ext.u) / 2.0 - 0.5;
1634
1635 // Compute kernel radii.
1636 MLdouble rx = static_cast<MLdouble>(_ext.x) / 2.0;
1637 MLdouble ry = static_cast<MLdouble>(_ext.y) / 2.0;
1638 MLdouble rz = static_cast<MLdouble>(_ext.z) / 2.0;
1639 MLdouble rc = static_cast<MLdouble>(_ext.c) / 2.0;
1640 MLdouble rt = static_cast<MLdouble>(_ext.t) / 2.0;
1641 MLdouble ru = static_cast<MLdouble>(_ext.u) / 2.0;
1642
1643 // Save local tables and set default table states.
1644 ImageVector* coordTab = _coordTab;
1645 _coordTab = nullptr;
1646
1647 KDATATYPE* valueTab = _valueTab;
1648 _valueTab = nullptr;
1649
1650 size_t tabSize = _tabSize;
1651 _tabSize = 0;
1652
1653 // Compute distance for all kernel voxels and normalize them.
1654 // If the coordinate is within ellipsoid distance then
1655 // add it to the kernel elements, otherwise forget it.
1656 for (size_t e = 0; e < tabSize; e++) {
1657 ImageVector v = coordTab[e];
1658 MLdouble pu = (static_cast<MLdouble>(v.u) - cu) / ru;
1659 MLdouble pt = (static_cast<MLdouble>(v.t) - ct) / rt;
1660 MLdouble pc = (static_cast<MLdouble>(v.c) - cc) / rc;
1661 MLdouble pz = (static_cast<MLdouble>(v.z) - cz) / rz;
1662 MLdouble py = (static_cast<MLdouble>(v.y) - cy) / ry;
1663 MLdouble px = (static_cast<MLdouble>(v.x) - cx) / rx;
1664
1665 // Distance smaller or equal 1? Then we are within kernel radius and
1666 // we set kernel value 'true'; otherwise we set kernel value 'false'.
1667 if (sqrt(px * px + py * py + pz * pz + pc * pc + pt * pt + pu * pu) <= 1) {
1668 _addCoordinate(v, valueTab[e], false);
1669 }
1670 }
1671
1672 // Remove saved tables.
1673 delete[] coordTab;
1674 coordTab = nullptr;
1675 delete[] valueTab;
1676 valueTab = nullptr;
1677
1678 // Recalculate the kernelSize.
1679 _calculateRealKernelExt();
1680}
1681
1682
1683//-------------------------------------------------------------------------------------------
1684// Applies a point symmetric mirroring of all kernel elements.
1685// The dimension param specifies a mirroring dimension if in range [0,5],
1686// otherwise mirroring is applied in all dimensions. Default is -1.
1687//-------------------------------------------------------------------------------------------
1688template <typename KDATATYPE> void TKernel<KDATATYPE>::mirror(int dimension)
1689{
1690 // Invalidate current information for separable kernels.
1691 _invalidateSeparableInfos();
1692
1693 // Save local tables and set default table states.
1694 ImageVector* coordTabBuf = _coordTab;
1695 _coordTab = nullptr;
1696
1697 KDATATYPE* valueTabBuf = _valueTab;
1698 _valueTab = nullptr;
1699
1700 size_t tabSizeBuf = _tabSize;
1701 _tabSize = 0;
1702
1703 // Calculate maximum kernel positions in all dimensions, that is one
1704 // less than extent.
1705 ImageVector maxP(_ext - ImageVector(1));
1706
1707 if ((dimension < 0) || (dimension > 5)) {
1708 // Subtract each coordinate of kernel elements from the
1709 // maximum extent position in all 6 dimensions and
1710 // add it to the kernel elements (which have been made
1711 // empty above).
1712 for (size_t e = 0; e < tabSizeBuf; e++) {
1713 _addCoordinate(maxP - coordTabBuf[e], valueTabBuf[e], false);
1714 }
1715 }
1716 else {
1719 for (size_t e = 0; e < tabSizeBuf; e++) {
1720 // Take normal coordinate.
1721 mirVec = coordTabBuf[e];
1722
1723 // mirror the selected coordinate component.
1725
1726 // Add new coordinate with value to kernel.
1727 _addCoordinate(mirVec, valueTabBuf[e], false);
1728 }
1729 }
1730
1731 // Remove old saved tables.
1732 delete[] coordTabBuf;
1733 coordTabBuf = nullptr;
1734 delete[] valueTabBuf;
1735 valueTabBuf = nullptr;
1736
1737 // Recalculate the kernelSize.
1738 _calculateRealKernelExt();
1739}
1740
1741//-------------------------------------------------------------------------------
1742// Calculate binomial coefficients for (n)
1743// (k)
1744//-------------------------------------------------------------------------------
1746{
1747 MLint i = 0;
1748 MLldouble v = 1.0;
1749
1750 if (k > n) {
1751 v = 0;
1752 }
1753 else {
1754 if ((k != 0) && (k != n)) {
1755 for (i = 1; i < (n + 1); i++) {
1756 v *= i;
1757 }
1758 for (i = 1; i < (k + 1); i++) {
1759 v /= i;
1760 }
1761 for (i = 1; i < (n - k + 1); i++) {
1762 v /= i;
1763 }
1764 }
1765 }
1766
1767 return (v);
1768}
1769
1770//-------------------------------------------------------------------------------------------
1771// Returns a vector with \c numSample values binomial coefficients.
1772// If \c numSamples is passed as 0 then an empty vector is returned.
1773// if \c normalize is passed true (the default) then all values are
1774// normalized to the sum of absolute values 1.
1775//-------------------------------------------------------------------------------------------
1776template <typename KDATATYPE> std::vector<KDATATYPE> TKernel<KDATATYPE>::get1DGauss(size_t numSamples, bool normalize)
1777{
1778 // The return value;
1779 std::vector<KDATATYPE> v;
1780
1781 if (numSamples > 0) {
1782 v.reserve(numSamples);
1783
1784 // Fill the axis with binomial coefficients and sum up all values.
1785 KDATATYPE sum = 0;
1786 for (size_t u = 0; u < numSamples; ++u) {
1787 // Calculate the entry, write it into the array and sum its absolute value up.
1788 // As documented in class description we cast in case of integer KDATATYPES.
1789 KDATATYPE val = static_cast<KDATATYPE>(binomialcoeff(numSamples - 1, u));
1790 v.push_back(val);
1791 sum += static_cast<KDATATYPE>(mlAbs(val));
1792 }
1793
1794 // If normalization is desired then divide all elements by the sum.
1795 if (normalize && (sum > 0)) {
1796 for (size_t u = 0; u < numSamples; u++) {
1797 v[u] /= sum;
1798 }
1799 }
1800 }
1801
1802 // Return the vector.
1803 return v;
1804}
1805
1806//-------------------------------------------------------------------------------------------
1807// Replaces the current kernel by a normalized gauss kernel.
1808//-------------------------------------------------------------------------------------------
1809template <typename KDATATYPE> void TKernel<KDATATYPE>::setGauss(const ImageVector& ext)
1810{
1811 // Invalidate current information for separable kernels.
1812 _invalidateSeparableInfos();
1813
1814 // Build gauss kernel by using separability property of gauss kernel.
1815 // So calculate a discrete binomial function for each axis.
1816 // The values of the kernel elements are products of the corresponding
1817 // values along the six binomial function axis.
1818 std::vector<KDATATYPE> vx = get1DGauss(ext.x, false);
1819 std::vector<KDATATYPE> vy = get1DGauss(ext.y, false);
1820 std::vector<KDATATYPE> vz = get1DGauss(ext.z, false);
1821 std::vector<KDATATYPE> vc = get1DGauss(ext.c, false);
1822 std::vector<KDATATYPE> vt = get1DGauss(ext.t, false);
1823 std::vector<KDATATYPE> vu = get1DGauss(ext.u, false);
1824
1825 // Build kernel by using the setKernel method for separable kernels.
1826 // Normalize kernel values after building the product to remain in normal grey value areas.
1827 setKernel(ext, &(vx[0]), &(vy[0]), &(vz[0]), &(vc[0]), &(vt[0]), &(vu[0]), true);
1828}
1829
1830
1831//-------------------------------------------------------------------------------------------
1832// Initialization. Should be called only by constructors.
1833//-------------------------------------------------------------------------------------------
1834template <typename KDATATYPE> void TKernel<KDATATYPE>::_init()
1835{
1836 _ext.set(0);
1837 _negExt.set(0);
1838 _posExt.set(0);
1839
1840 _tabSize = 0;
1841
1842 _valueTab = nullptr;
1843 _coordTab = nullptr;
1844
1845 // Separability information.
1846 _isSeparable = false;
1847 _areSeparabilityInfosUpToDate = false;
1848 _separableDimEntries.set(0);
1849 _separableOneDimExt.set(0);
1850 _separableExt.set(0);
1851 _separableNegExt.set(0);
1852 _separablePosExt.set(0);
1853 _separableCoordTab.clear();
1854}
1855
1856
1857//-------------------------------------------------------------------------------------------
1858// Clear all internal (dynamic) tables.
1859//-------------------------------------------------------------------------------------------
1860template <typename KDATATYPE> void TKernel<KDATATYPE>::_clearTables()
1861{
1862 // Set table size to 0.
1863 _tabSize = 0;
1864
1865 // Invalidate separability infos which are calculated on demand.
1866 _areSeparabilityInfosUpToDate = false;
1867
1868 delete[] _valueTab;
1869
1870 _valueTab = nullptr;
1871 delete[] _coordTab;
1872 _coordTab = nullptr;
1873}
1874
1875
1876//-------------------------------------------------------------------------------------------
1877// Add a new coordinate with value to the coordinate and value table.
1878// Still not tested! If update is true (default) then the kernel extents
1879// are updated.
1880//-------------------------------------------------------------------------------------------
1881template <typename KDATATYPE>
1883{
1884 // Create new data tables.
1885 ImageVector* newCoordTab = nullptr;
1886 KDATATYPE* newValueTab = nullptr;
1887
1888 // Invalidate separability infos which are calculated on demand.
1889 _areSeparabilityInfosUpToDate = false;
1890
1891 // Compute new table size.
1892 size_t newTabSize = _tabSize + 1;
1893
1894 newCoordTab = new ImageVector[_tabSize + 1];
1895 newValueTab = new KDATATYPE[_tabSize + 1];
1896
1897 // Handle not enough memory.
1898 if (!newCoordTab || !newValueTab) {
1899 delete[] newCoordTab;
1900 newCoordTab = nullptr;
1901 delete[] newValueTab;
1902 newValueTab = nullptr;
1903 ML_PRINT_FATAL_ERROR("Kernel<KDATATYPE>::_addCoordinate(...):", ML_NO_MEMORY,
1904 "Cannot create kernel tables. Returning with invalid "
1905 "reset tables. This will probably cause other errors.");
1906 return;
1907 }
1908
1909 // Copy old contents into new tables.
1910 if (_tabSize > 0) {
1911#if defined(__clang__)
1912// Suppress Clang warning:
1913// "call to 'memcpy' writing to an object of type 'ml::ImageVector'
1914// with a non-trivial copy constructor or destructor [-Wnontrivial-memcall]"
1915//
1916// We intentionally use memcpy here because ImageVector behaves like a trivially
1917// copyable POD type in this context. The operation is safe.
1918//
1919// Well... safe *today*. Murphy's Law says it will inevitably break and this memcpy
1920// becomes undefined behavior and explodes spectacularly.
1921#pragma clang diagnostic push
1922#pragma clang diagnostic ignored "-Wnontrivial-memcall"
1923#elif defined(__GNUC__)
1924 // Suppress warning:
1925 // "'void* memcpy(void*, const void*, size_t)' writing to an object of type 'ml::ImageVector'
1926 // {aka 'class ml::TImageVector<long long int>'} with no trivial copy-assignment;
1927 // use copy-assignment or copy-initialization instead [-Wclass-memaccess]"
1928 // We are sure this is ok in this case!
1929#pragma GCC diagnostic push
1930#pragma GCC diagnostic ignored "-Wclass-memaccess"
1931#endif
1932 memcpy(newCoordTab, _coordTab, _tabSize * sizeof(ImageVector));
1933#if defined(__clang__)
1934#pragma clang diagnostic pop
1935#elif defined(__GNUC__)
1936#pragma GCC diagnostic pop
1937#endif
1938 memcpy(newValueTab, _valueTab, _tabSize * sizeof(KDATATYPE));
1939 }
1940
1941 // Set new entry.
1942 newCoordTab[_tabSize] = pos;
1943 newValueTab[_tabSize] = value;
1944
1945 // Remove old tables.
1946 _clearTables();
1947
1948 // Increase table size.
1949 _tabSize = newTabSize;
1950 _coordTab = newCoordTab;
1951 _valueTab = newValueTab;
1952
1953 // Update the real kernel size.
1954 if (update) {
1955 _calculateRealKernelExt();
1956 }
1957}
1958
1959
1960//-------------------------------------------------------------------------------------------
1961// Calculate the correct maximum kernel extent for all used kernel elements.
1962// The maximum extent in all dimensions is reduced as much that all kernel coordinates just
1963// remain in valid extent. Leading empty entries in the kernel are not removed.
1964// Empty kernels are considered as kernels with extent (1,1,1,1,1,1).
1965//-------------------------------------------------------------------------------------------
1966template <typename KDATATYPE> void TKernel<KDATATYPE>::_calculateRealKernelExt()
1967{
1968 // Search minimum and maximum extent of the kernel.
1969 // For the case that no coordinate elements are available set
1970 // values to (0,0,0,0,0,0) so that resulting kernel ext is
1971 // calculated to (1,1,1,1,1,1) below.
1972 ImageVector maximum(0, 0, 0, 0, 0, 0);
1973 if (getTabSize() > 0) {
1974 for (size_t c = 0; c < getTabSize(); c++) {
1975 maximum = ImageVector::compMax(_coordTab[c], maximum);
1976 }
1977 }
1978
1979 // Define kernel ext as difference between corners of bounding box.
1980 _ext = maximum + ImageVector(1, 1, 1, 1, 1, 1);
1981
1982 // Compute a negative and positive extend of the kernel. So even and odd kernels
1983 // can be handled without really having a kernel center. Subtract one to avoid a
1984 // to avoid increment of extents by one.
1985 _negExt = calculateNegativeExtentFromExtent(_ext);
1986 _posExt = calculatePositiveExtentFromExtent(_ext);
1987
1988 // The kernel must never have extents smaller than 1 after this call.
1989 if (!_ext.allBiggerZero()) {
1990 ML_PRINT_FATAL_ERROR("void TKernel<KDATATYPE>::_calculateRealKernelExt()", ML_PROGRAMMING_ERROR,
1991 "Kernel has invalid extents now. Continuing anyway.");
1992 }
1993}
1994
1995
1996//-------------------------------------------------------------------------------------------
1997//
1998// Support for an interpretation as separable kernel.
1999//
2000//-------------------------------------------------------------------------------------------
2001
2002//-------------------------------------------------------------------------------------------
2003// Set/unset a flag to indicate that the first 6 rows of the first kernel slice
2004// is considered as 1-D axes of a separable filter kernel. Note that this flag
2005// only denotes how applications shall interpret this kernel; however it does
2006// NOT change any behaviour of this class.
2007//-------------------------------------------------------------------------------------------
2008template <typename KDATATYPE> void TKernel<KDATATYPE>::setSeparable(bool isSeparableVal)
2009{
2010 // Invalidate separability information if flag changes.
2011 if (_isSeparable != isSeparableVal) {
2012 _isSeparable = isSeparableVal;
2013 _invalidateSeparableInfos();
2014 }
2015}
2016
2017//-------------------------------------------------------------------------------------------
2018// Indicates whether the first 6 rows of the first kernel slice are
2019// interpreted as 1-D axes of a separable filter kernel; default is false.
2020//-------------------------------------------------------------------------------------------
2021template <typename KDATATYPE> bool TKernel<KDATATYPE>::isSeparable() const
2022{
2023 return _isSeparable;
2024}
2025
2026//-------------------------------------------------------------------------------------------
2027// Returns a ImageVector with the number of entries of the separable kernel for
2028// the dimensions 0,...,5. That means the n-th index contains the number
2029// of valueTab entries of row n, where n is from [0,...,5].
2030//-------------------------------------------------------------------------------------------
2031template <typename KDATATYPE> ImageVector TKernel<KDATATYPE>::getSeparableDimEntries() const
2032{
2033 _validateSeparabilityInfos();
2034 return _separableDimEntries;
2035}
2036
2037//------------------------------------------------------------------------------------------
2043//------------------------------------------------------------------------------------------
2045{
2046 _validateSeparabilityInfos();
2047 return _separableOneDimExt;
2048}
2049
2050//-------------------------------------------------------------------------------------------
2057//-------------------------------------------------------------------------------------------
2058template <typename KDATATYPE> size_t TKernel<KDATATYPE>::getSeparableDimIndex(size_t dim) const
2059{
2060 _validateSeparabilityInfos();
2061 if (dim > 5) {
2062 dim = 5;
2063 }
2064
2065 // Sum up elements in lower dimensions to get index to the correct table entry.
2066 switch (dim) {
2067 case 0:
2068 return 0;
2069
2070 case 1:
2071 return static_cast<size_t>(_separableDimEntries.x);
2072
2073 case 2:
2074 return static_cast<size_t>(_separableDimEntries.x + _separableDimEntries.y);
2075
2076 case 3:
2077 return static_cast<size_t>(_separableDimEntries.x + _separableDimEntries.y + _separableDimEntries.z);
2078
2079 case 4:
2080 return static_cast<size_t>(_separableDimEntries.x + _separableDimEntries.y + _separableDimEntries.z +
2081 _separableDimEntries.c);
2082
2083 case 5:
2084 return static_cast<size_t>(_separableDimEntries.x + _separableDimEntries.y + _separableDimEntries.z +
2085 _separableDimEntries.c + _separableDimEntries.t);
2086 default:
2087 {
2088 ML_PRINT_FATAL_ERROR("TKernel<KDATATYPE>::getSeparableDimIndex", ML_PROGRAMMING_ERROR, "returning x-table entries");
2089 return 0;
2090 }
2091 }
2092}
2093
2094//-------------------------------------------------------------------------------------------
2095// Returns the table of all coordinates for filtering with separable kernels.
2096//-------------------------------------------------------------------------------------------
2097template <typename KDATATYPE> const std::vector<ImageVector>& TKernel<KDATATYPE>::getSeparableCoordTab() const
2098{
2099 _validateSeparabilityInfos();
2100 return _separableCoordTab;
2101}
2102
2103//-------------------------------------------------------------------------------------------
2104// Invalidate separability information.
2105//-------------------------------------------------------------------------------------------
2106template <typename KDATATYPE> void TKernel<KDATATYPE>::_invalidateSeparableInfos()
2107{
2108 _areSeparabilityInfosUpToDate = false;
2109}
2110
2111//-------------------------------------------------------------------------------------------
2112// This method updates all members which are needed in query methods for
2113// separability properties of the kernel.
2114// Note:
2115// This method changes mutable members since it is required for get-methods
2116// on information about separability information.
2117//-------------------------------------------------------------------------------------------
2118template <typename KDATATYPE> void TKernel<KDATATYPE>::_validateSeparabilityInfos() const
2119{
2120 // Speed up performance since it's called first in all separable info methods.
2121 if (_areSeparabilityInfosUpToDate) {
2122 return;
2123 }
2124 if (!_areSeparabilityInfosUpToDate) {
2125
2126 // Scan all coordinate components of the kernel until the y-coordinate is >= 6,
2127 // because all other information after that is not relevant for first 6 separable
2128 // filter rows. Expand the extent of the separable kernel and determine coordinate
2129 // of the axis components.
2130 _separableDimEntries.set(0);
2131 _separableOneDimExt.set(0);
2132 _separableExt.set(0);
2133 _separableCoordTab.clear();
2135 size_t idx = 0;
2136 while ((idx < _tabSize) && (_coordTab[idx].y < 6)) {
2137 // Get the current entry.
2138 const ImageVector& entry = _coordTab[idx];
2139
2140 const size_t entryY = mlrange_cast<size_t>(entry.y);
2141
2142 // Increment the number of entries of a certain dimension of the
2143 // 6 1-D kernels if the kernel is interpreted as a separable kernel.
2144 // Note that each of the first six rows contains the separable 1-D kernel
2145 // for dimensions 1-6.
2146 _separableDimEntries[entryY]++;
2147
2148 // Increment the extent of the separable kernel dimensions if the
2149 // coordinate given by entry has a larger x-coordinate than the
2150 // extent of the corresponding dimension.
2151 if (entry.x + 1 > _separableOneDimExt[entryY]) {
2152 _separableOneDimExt[entryY] = entry.x + 1;
2153 }
2154
2155 // Add the coordinate of the 1-D kernel to the table of coordinates.
2156 // Note that separable kernels are placed in the "center" of the corresponding
2157 // "normal" kernel. Hence, all components which are not given by entry.y,
2158 // need to be set to the position of the kernel "center" which is given by
2159 // the negative extent of the kernel. However, we do not have this "center"
2160 // here, because we do not know it before having all extents.
2161 // So we we mark the missing coordinate components with -1 and replace them
2162 // in an additional loop afterwards.
2163 sepCoord.set(-1);
2164 sepCoord[entryY] = entry.x;
2165 _separableCoordTab.push_back(sepCoord);
2166
2167 // Count the number of separable entries in the kernel with idx: Go to next entry.
2168 ++idx;
2169 }
2170
2171 // Determine second version of separable kernel extent where non filtered
2172 // dimensions are set to 1.
2173 _separableExt = _separableOneDimExt;
2174 _separableExt.fillSmallerComps(1, 1);
2175
2176 // Determine the center of the kernel which is considered to be the negative kernel extent.
2177 const ImageVector negExt = _separableExt / ImageVector(2);
2178
2179 // Replace all -1 component values with the kernel center; thus the 1-D kernel is
2180 // centered in the region where the corresponding normal kernel would also have its
2181 // "center".
2182 for (size_t e = 0; e < idx; ++e) {
2183 // Get coordinate.
2184 ImageVector& coord = _separableCoordTab[e];
2185 for (size_t d = 0; d < 6; ++d) {
2186 // Replace all -1 component values with the kernel center.
2187 if (coord[d] == -1) {
2188 coord[d] = negExt[d];
2189 }
2190 }
2191 }
2192
2193 // Calculate negative and positive kernel extent for a separable kernel.
2194 // If a dimension is empty or zero sized then a zero component is returned.
2195 _separableNegExt = _separableExt / ImageVector(2);
2196 _separablePosExt = (_separableExt - (_separableExt / ImageVector(2))) - ImageVector(1);
2197
2198 // Mark infos as valid.
2199 _areSeparabilityInfosUpToDate = true;
2200 }
2201}
2202
2203//-------------------------------------------------------------------------------------------
2204// End of support for the interpretation of the kernel as separable kernel.
2205//-------------------------------------------------------------------------------------------
2206
2207
2212
2215
2218
2219
2222
2226
2227
2229
2230#endif // __mlKernel_H
Class to manage a filtering kernel for images.
Definition mlKernel.h:74
virtual ~TKernel()
Destructor. Cleans up and removes instance of kernel.
Definition mlKernel.h:571
void mirror(int dimension=-1)
Applies a point symmetric mirroring of all kernel elements.
Definition mlKernel.h:1688
std::string getKernel(bool asLines=false, MLint fieldWidth=0, MLint precision=10) const
Returns the current kernel elements and values as string: The string needs has the following format: ...
Definition mlKernel.h:1114
const ImageVector & getPositiveExtent() const
See getNegativeExtent().
Definition mlKernel.h:964
bool isSeparable() const
Indicates whether the first 6 rows of the first kernel slice are interpreted as 1-D axes of a separab...
Definition mlKernel.h:2021
static ImageVector indexToCoord(MLint idx, const ImageVector &ext)
Converts an index into an array with extents ext to a coordinate.
Definition mlKernel.h:996
void makeCircular()
Takes the current kernel, computes radii from the extents of the kernel and removes all kernel elemen...
Definition mlKernel.h:1615
static ImageVector calculateNegativeExtentFromExtent(const ImageVector &ext)
Calculate the negative extent of a kernel from a kernel extent.
Definition mlKernel.h:1004
static ImageVector calculatePositiveExtentFromExtent(const ImageVector &ext)
Calculate the positive extent of a kernel from a kernel extent.
Definition mlKernel.h:1012
void _invalidateSeparableInfos()
Invalidate separability information.
Definition mlKernel.h:2106
static MLldouble binomialcoeff(MLint n, MLint k)
Calculate binomial coefficients for (n) (k)
Definition mlKernel.h:1745
void _init()
Initialization. Should be called only by constructors.
Definition mlKernel.h:1834
void fillUndefinedElements(KDATATYPE newVal=0)
Fill all undefined kernel elements with newVal.
Definition mlKernel.h:1575
static MLint coordToIndex(const ImageVector &p, const ImageVector &size)
Converts the coordinate into the kernel with extents size to an index.
Definition mlKernel.h:988
void setPartialKernel(size_t numElems, ImageVector *const coords, KDATATYPE *const values=nullptr)
Defines a set of local kernel coordinates and optionally a set of values which define the kernel elem...
Definition mlKernel.h:1043
size_t getTabSize() const
Returns the current number of kernel elements.
Definition mlKernel.h:620
ImageVector getSeparableDimEntries() const
Returns a ImageVector with the number of entries of the separable kernel for the dimensions 0,...
Definition mlKernel.h:2031
KDATATYPE getMinValue() const
Return the minimum value of all kernel element values If kernel value table is empty then 0 is return...
Definition mlKernel.h:672
KDATATYPE getMaxValue() const
Return the maximum value of all kernel element values If kernel value table is empty then 1 is return...
Definition mlKernel.h:688
void setSeparable(bool isSeparableVal)
Set/unset a flag to indicate that the first 6 rows of the first kernel slice is considered as 1-D axe...
Definition mlKernel.h:2008
const TKernel & operator=(const TKernel &kern)
Assignment operator. Sets current instance to contents of kern.
Definition mlKernel.h:579
void manipulateKernelElements(KernModifier mode, KDATATYPE v)
Modify all kernel element values with the value v.
Definition mlKernel.h:736
TKernel()
Constructor. Builds an empty kernel.
Definition mlKernel.h:554
static std::vector< KDATATYPE > get1DGauss(size_t numSamples, bool normalize=true)
Returns a vector with numSample values binomial coefficients.
Definition mlKernel.h:1776
std::string setKernel(const std::string &kernString)
Defines elements and values of the kernel matrix by a string.
Definition mlKernel.h:1239
void reset()
Reset kernel to construction state.
Definition mlKernel.h:607
const ImageVector & getExtent() const
Returns the kernel extents in 6D.
Definition mlKernel.h:933
ImageVector getSeparableOneDimExtents() const
Returns a vector where the components 0,...,5 contain the extent of the region spanned by the 6 separ...
Definition mlKernel.h:2044
const std::vector< ImageVector > & getSeparableCoordTab() const
Returns the table of with all coordinates for filtering with separable kernels.
Definition mlKernel.h:2097
const KDATATYPE * getValueTab(size_t dim=0) const
Gets the table of kernel element values which are currently defined.
Definition mlKernel.h:650
void _clearTables()
Clear all internal (dynamic) tables.
Definition mlKernel.h:1860
MLint findIndex(const ImageVector &pos) const
Return index to kernel element if it exists; otherwise return -1.
Definition mlKernel.h:1022
KernModifier
Manipulation modes for kernel values with a given value v:
Definition mlKernel.h:102
KDATATYPE getValueTabSum() const
Return the sum of all kernel element values.
Definition mlKernel.h:658
void setKernel(const ImageVector &ext, const KDATATYPE2 *const xaxis, const KDATATYPE2 *const yaxis, const KDATATYPE2 *const zaxis, const KDATATYPE2 *const caxis, const KDATATYPE2 *const taxis, const KDATATYPE2 *const uaxis, bool normalize)
Defines a complete kernel matrix whose extents are defined by ext.
Definition mlKernel.h:295
static MLint coordToIndex(MLint x, MLint y, MLint z, MLint c, MLint t, MLint u, const ImageVector &size)
Converts the coordinate (x,y,z,c,t,u) into the kernel to an index into an array with 6D extents given...
Definition mlKernel.h:980
const ImageVector * getCoordTab(size_t dim=0) const
Gets a table of coordinates pointing to all kernel elements which are currently defined.
Definition mlKernel.h:639
TKernel(const TKernel &kern)
Copy constructor. Builds a kernel with contents of kern.
Definition mlKernel.h:562
void _addCoordinate(const ImageVector &pos, KDATATYPE value, bool update)
Add a new coordinate with value to the coordinate and value table.
Definition mlKernel.h:1882
const ImageVector & getNegativeExtent() const
The extent of the kernel to both sides.
Definition mlKernel.h:950
void _calculateRealKernelExt()
Calculate the correct maximum kernel extent for used kernel elements.
Definition mlKernel.h:1966
size_t getSeparableDimIndex(size_t dim=0) const
Returns the index to entries of valueTab or coordTab which are related to the 1-D separable kernel fo...
Definition mlKernel.h:2058
void setGauss(const ImageVector &ext)
Replaces the current kernel by a normalized gauss kernel.
Definition mlKernel.h:1809
KDATATYPE getNegativeValueSum() const
Return the sum of all negative kernel element values.
Definition mlKernel.h:705
KDATATYPE getPositiveValueSum() const
Return the sum of all positive kernel element values.
Definition mlKernel.h:721
void setKernel(const ImageVector &ext, const KDATATYPE *const values=nullptr, bool *const mask=nullptr)
Defines a complete kernel matrix whose extents are defined by ext.
Definition mlKernel.h:1388
void _validateSeparabilityInfos() const
This method updates all members which are needed in query methods for separability properties of the ...
Definition mlKernel.h:2118
void setSeparableKernel(const std::vector< typename std::vector< KDATATYPE > > &separableRows)
Create kernel coordinate and value tables in separable table format, that means a 2-D kernel where ea...
Definition mlKernel.h:1469
void resizeKernel(const ImageVector &ext, KDATATYPE newVal=0)
Resizes the kernel to a new state and tries to maintain the previous elements if possible.
Definition mlKernel.h:1525
std::string print(const std::string &openStr="", const std::string &sepStr=" ", const std::string &termStr="", const int numDigits=-1) const
Returns the string openStr + v.array[0] + sepStr + ... + v.array[NumberOfDimensions-2] + sepStr + v....
bool MLValueIs0WOM(MLint8 a)
Returns true if value is 0; otherwise, it returns false.
bool MLValuesDifferWOM(MLint8 a, MLint8 b)
Returns true if values differ; otherwise, it returns false.
#define ML_CALCULATION_ERROR
This is an unspecific error used in some cases where the error is not very specific.
Definition mlTypeDefs.h:888
#define ML_PROGRAMMING_ERROR
A case occurred that should not appear and there are a variety of reasons, typically it is a programm...
Definition mlTypeDefs.h:844
#define ML_BAD_PARAMETER
A bad/invalid parameter (or even an inappropriate image) has been passed to a module or an algorithm,...
Definition mlTypeDefs.h:879
#define ML_NO_MEMORY
The system does not have enough memory to perform the desired operation; try to reduce application da...
Definition mlTypeDefs.h:791
#define ML_PRINT_FATAL_ERROR(FUNC_NAME, REASON, HANDLING)
Like ML_PRINT_FATAL_ERROR_DUMP(FUNC_NAME, REASON, HANDLING, RT_OBJ) without a runtime object to be du...
#define ML_PRINT_ERROR(FUNC_NAME, REASON, HANDLING)
Like ML_PRINT_ERROR_DUMP(FUNC_NAME, REASON, HANDLING, RT_OBJ) without a runtime object to be dumped.
Target mlrange_cast(Source arg)
Generic version of checked ML casts.
@ ML_FATAL_MEMORY_ERROR
On allocation failure, a fatal error print is done and NULL is returned.
Definition mlTypeDefs.h:729
long double MLldouble
Definition mlTypeDefs.h:232
double MLdouble
Definition mlTypeDefs.h:217
MLint64 MLint
A signed ML integer type with at least 64 bits used for index calculations on very large images even ...
Definition mlTypeDefs.h:489
signed int MLint32
Definition mlTypeDefs.h:161
double log(T value)
double sqrt(T value)
T mlAbs(T a)
Defines ML specific abs template since only type-dependent library functions exists.
MLdouble KernelDataType
Define the standard data type for kernel elements to be used in this library.
Definition mlKernel.h:2221