diff --git a/docs/Coding_Knowledge_Base.md b/docs/Coding_Knowledge_Base.md index 74cffa0f3b..2f6f86aed6 100644 --- a/docs/Coding_Knowledge_Base.md +++ b/docs/Coding_Knowledge_Base.md @@ -50,7 +50,7 @@ repository, but contains no code from one. - [Check the file close and the stream state before you report a successful write](#check-the-file-close-and-the-stream-state-before-you-report-a-successful-write) - [Check for cancel in every long loop](#check-for-cancel-in-every-long-loop) - [Write floating-point output through a saturating cast](#write-floating-point-output-through-a-saturating-cast) - - [Let the user choose whether a NaN input value is an error or is skipped](#let-the-user-choose-whether-a-nan-input-value-is-an-error-or-is-skipped) + - [Decide NaN and infinity handling by where the value comes from](#decide-nan-and-infinity-handling-by-where-the-value-comes-from) - [Copy every field that sets behavior when you clone an object](#copy-every-field-that-sets-behavior-when-you-clone-an-object) - [Feature data](#feature-data) - [Do not compute anything for feature 0, and give empty features a defined output](#do-not-compute-anything-for-feature-0-and-give-empty-features-a-defined-output) @@ -327,20 +327,42 @@ cannot use, before any cast: - related values: legal combinations; accept `min <= max` when the operation defines equal bounds. - values cast to an array element type: inside the range of that type. -Write each comparison so that NaN fails it. Validate a value only when the algorithm uses it (follow the parameter -linking), and always validate a value that it always reads. A direction or axis parameter does not default to -`{0, 0, 0}`, and preflight rejects a zero-length or non-finite vector. Every parameter reaches the algorithm's input -values and changes its behavior, or it is removed. When a filter stores the random seed it used, the algorithm uses that -same seed, so the stored seed reproduces the output. +Write each comparison so that NaN fails it. Reject NaN, and reject infinity unless the filter documentation gives it a +meaning; a value the user asks the filter to store in a floating-point array may be NaN or infinity +([Decide NaN and infinity handling by where the value comes from](#decide-nan-and-infinity-handling-by-where-the-value-comes-from)). +Validate a value only when the algorithm uses it (follow the parameter linking), and always validate a value that it +always reads. A direction or axis parameter does not default to `{0, 0, 0}`, and preflight rejects a zero-length or +non-finite vector. Every parameter reaches the algorithm's input values and changes its behavior, or it is removed. When +a filter stores the random seed it used, the algorithm uses that same seed, so the stored seed reproduces the output. + +Validate the derived representation as well as the parameter value. For radii and dimensions, check derived widths, +signed coordinate and loop limits, padded extents, element counts and byte counts before the affected arithmetic or +allocation. An index must fit every array or axis it selects; use `index < count`, without subtracting one from the +count. For integer destinations, do not use a rounded floating-point representation of the maximum as an inclusive upper +bound. When fractional conversion is supported, validate the effective value and check related values in the type the +consumer uses. Preserve supported equality. Validate and normalize direction parameters with arithmetic that remains +safe for finite nonzero directions, then use that normalized value. **Example of the broken rule:** `CreateDataArrayAdvanced` converted negative or fractional tuple dimensions to `usize`; `InitializeData` accepted a reversed random range; `SliceTriangleGeometry` accepted an invalid slice spacing (all -PR #1763); SurfaceNets accepted a negative smoothing distance and iteration count (PR #1765). +PR #1763); SurfaceNets accepted a negative smoothing distance and iteration count (PR #1765). `WhiteTopHatImageFilter` +and `BinaryDilateImageFilter` narrowed unsigned radii before constructing kernels, and the constructor also used +unchecked derived sizes; `BinaryProjectionImageFilter` checked against rounded Float64 integer maxima; +`WriteGBCDGMTFileFilter` checked a phase against GBCD tuples but also used it to index Crystal Structures; +`ComputeGBCDPoleFigureDirect` normalized Float32 axes through a squared magnitude that can overflow for finite +components (issue #1873). -**Why:** a cast of an out-of-range or NaN value is undefined behavior, and `value < 0` alone lets NaN through. +**Why:** a cast of an out-of-range or NaN value is undefined behavior, and `value < 0` alone lets NaN through. A value +can also fit its declared type while its derived size, converted value or contextual index is invalid, and a finite +vector can overflow during normalization; checking only the original value leaves these failures reachable. **What to look for:** a `static_cast` of a parameter before a domain check; `if(value < 0)` on a floating-point value; a -zero step; an unchecked `min`/`max` pair. +zero step; an unchecked `min`/`max` pair. Also: + +- radius-derived widths, padding, products or signed loop endpoints computed before validation; +- one selector used with several arrays but checked against only one count; an upper bound written as `count - 1`; +- integer-range guards using floating-point `max()` values; relations checked only before conversion; +- a direction check followed by normalization that squares components in a narrow type. **Pattern to use:** @@ -354,6 +376,12 @@ if(!std::isfinite(dim) || !(dim >= 1.0) || !(dim < upperExclusive) || std::floor tupleDims.push_back(static_cast(dim)); ``` +`ValidateKernelRadius()` in `simplnx/Utilities/ImageProcessing/StructuringElement.hpp` and `ValidateMorphologyLayout()` +in `MorphologyEngine.hpp` validate derived sizes without constructing the kernel or allocating image values. Check each +contextual count before access and each relation after safe conversion. For a direction, first reject nonfinite +components and the zero vector, scale by the largest absolute component, and normalize the scaled vector with +sufficiently wide arithmetic. + ### Never throw in preflight **Rule:** `IFilter::preflight()` does not convert exceptions into errors, so an exception in `preflightImpl()` can end @@ -601,25 +629,36 @@ guarantee: it counts real changes, caps the iterations or applies a timeout. Che before the loop, and again after a step that can take a long time (a write, a complete read). A filter that modifies its input in place may finish once its first in-place write has happened, when its documentation says so. +When a neighborhood traversal discards positions outside a finite contributing domain, intersect its loop bounds with +that domain before iteration, and keep the contributing positions, their order and their weights. A valid large radius +is not invalid merely because the traversal spends time on discarded positions. Cancellation checks remain required. + **Example of the broken rule:** PR #1582 added missing cancel checks to 28 algorithms, among them ComputeAvgCAxes, ComputeBoundaryStrengths, ComputeGBCDMetricBased, ComputeSchmids, MergeTwins, AlignGeometries, ComputeFeatureClustering, MultiThresholdObjects and RobustAutomaticThreshold. `PointSampleTriangleGeometry` still has a masked rejection loop with -no cancel check or progress bound (issue #1876). +no cancel check or progress bound (issue #1876). `AdaptiveHistogramEqualizationEngine.hpp` enumerated the full radius +around each voxel and then discarded out-of-image coordinates (issue #1873); `ComputeNeighborhoods.cpp` similarly +enumerates radius-derived bins and discards absent bins (issue #1908). -**Why:** the user cannot stop a long filter, and a loop without a progress guarantee can run forever on bad input. +**Why:** the user cannot stop a long filter, and a loop without a progress guarantee can run forever on bad input. Work +can also keep growing with a valid parameter after the useful neighborhood already covers the data. **What to look for:** an inner rejection or convergence loop whose outer cancel check is never reached; an expensive -phase with no check between its steps. +phase with no check between its steps; a radius-driven coordinate or bin loop followed by an out-of-domain `continue` or +an unsuccessful lookup. **Pattern to use:** a check at each interruptible work boundary, as PR #1582 added them; the -`bluequartz-skills:progress-messaging` skill. +`bluequartz-skills:progress-messaging` skill. For an image axis, intersect `[-radius, radius]` with +`[-position, dimension - 1 - position]` using signed arithmetic before iteration. Apply this only when omitted positions +contribute nothing; clipping a neighborhood that repeats clamped boundary samples changes its result. ### Write floating-point output through a saturating cast **Rule:** a filter whose output type can be an integer type (for example an output type that follows the input type) -writes each computed floating-point value through `ImageProcessing::detail::SaturateCastFromDouble()`. For an -integral `U` it maps NaN to 0 and clamps to the range of `U`. The general rule is in the numeric-correctness reference -of `cpp-best-practices`. +writes each computed finite floating-point value through `ImageProcessing::detail::SaturateCastFromDouble()`, which +clamps it to the range of `U`, and reports one warning with the number of clipped values. A NaN or an infinity computed +for an integer output is an error that names the value's index and the output type; it is never written as 0. The +general rule is in the numeric-correctness reference of `cpp-best-practices`. **Example of the broken rule:** `ExpImageFilter` casts `exp(double(value))` straight to the integer output, and `LogImageFilter`, `SquareImageFilter` and `TanImageFilter` do the same: `log(0)`, the `uint8` square of 16 and the @@ -630,53 +669,68 @@ of `cpp-best-practices`. **What to look for:** `static_cast(floatingExpression)` where `U` can be integral. **Pattern to use:** `SaturateCastFromDouble()` in -`simplnx/Utilities/ImageProcessing/ImageProcessingFilterUtilities.hpp`. - -### Let the user choose whether a NaN input value is an error or is skipped - -**Rule:** a calculation in which a NaN input value would change a result other than its own element's output, or would -reach a comparison, an ordering, an index or an integer conversion, lets the user choose how NaN is handled. This covers -reductions (sums, means, standard deviations, extrema and data ranges, histograms, medians, modes and unique-value -counts, per feature or per region), neighborhood operations on floating-point data (smoothing, median and gradient -filters, morphology) and decisions made from a value (thresholds, segmentation tolerances, bin and index selection, -conversion to an integer). - -- The filter has a choice parameter **NaN Value Handling** with two choices: **Error** (the default) and **Warning**. -- **Error:** the algorithm stops at the first NaN value with a filter-specific error. The message names the array and - the tuple, and says that setting **NaN Value Handling** to **Warning** skips NaN values instead. -- **Warning:** the algorithm skips every NaN value and reports one warning with the number of values it skipped. A - reduction or a neighborhood leaves the value out; a decision gives the NaN element a defined output that the filter - documentation states (for example "not selected" or "no bin"). -- The check reads array values, so it runs in execute. The parameter has no effect on integer arrays. -- The in-core and out-of-core algorithms use one shared NaN test and skip rule. - -Element-wise math, where NaN in gives NaN out at the same element and no other element changes (Array Calculator, an -orientation conversion of one tuple), may let NaN pass through. A NaN that the algorithm itself produces from degenerate -input (a zero-length vector, a singular matrix) is a degenerate-input problem, not this rule. +`simplnx/Utilities/ImageProcessing/ImageProcessingFilterUtilities.hpp` for finite values; the nonfinite integer-output +error and the clipping warning of `SmoothingRecursiveGaussianImageFilter` and `CurvatureFlowImageFilter` (PR #1888). + +### Decide NaN and infinity handling by where the value comes from + +**Rule:** NaN and positive and negative infinity (nonfinite values) are handled by where the value comes from: + +- **Parameter values:** preflight rejects NaN. It also rejects positive and negative infinity unless the filter + documentation gives infinity a meaning, such as an unbounded side of a range. A value that the user asks the filter + to store in a floating-point array (a fill value or a replacement value) may be NaN or infinity. +- **Values read from a file:** the reader rejects a nonfinite value where the format requires a finite one, with an + error that names the file and the field. +- **Input array values** that would change a result other than their own element's output, or would reach a + comparison, an ordering, a range, a histogram, a threshold, a color map, a search, an index or an integer conversion. + This covers reductions (sums, means, standard deviations, extrema and data ranges, histograms, medians, modes and + unique-value counts, per feature or per region), neighborhood operations on floating-point data (smoothing, median and + gradient filters, morphology) and decisions made from a value (thresholds, segmentation tolerances, bin and index + selection). The filter has a choice parameter **Nonfinite Input Handling** (key + `nonfinite_input_handling_index`) with two choices, **Error** (the default) and **Warn and Continue**. + - **Error** stops at the first nonfinite value, before any output is written. The message names the array and the + tuple and says that **Warn and Continue** handles these values instead. + - **Warn and Continue** computes ranges and bounds from finite values only, gives each nonfinite element the result + that the filter documentation states (for example "first bin" or "Outside Value"), and reports one warning with + the number of nonfinite values. For reductions and neighborhood operations, exclude nonfinite values from the + contributing samples and counts. + - The in-core and out-of-core algorithms use one shared test and rule. The parameter has no effect on integer arrays. +- **Element-wise floating-point math**, where one element in gives the same element out and no other element changes, + lets the IEEE result pass through. The filter documentation lists what NaN, infinity, zero and out-of-domain inputs + produce. When integer input can produce a fraction or NaN, the output type is floating point. +- **A computed value written to an integer output:** see + [Write floating-point output through a saturating cast](#write-floating-point-output-through-a-saturating-cast). +- **A result that is undefined for degenerate input** (a zero-length vector, an all-zero quaternion) is NaN in a + floating-point output, and the documentation says so. It is not reported as bad input data. + +These rules apply to new filters and to filters a change already fixes; changing an existing filter's output type or +failure behavior to meet them is a breaking change that its pull request names. **Example of the broken rule:** **Compute Bounding Box Stats** gives two different wrong answers for Float32 values {NaN, 1, 2}: the in-core algorithm treats NaN as equal to every value (`Equivalent()` in `ComputeBoundingBoxStatsDirect`) and reports one unique value and a NaN median, and the out-of-core algorithm sorts with -`operator<`, which is undefined when a value is NaN (issue #1867, `ComputeBoundingBoxStatsFilter#9`). **Compute Array +`operator<`, which is undefined when a value is NaN (issue #1867). **Compute Array Histogram** groups values with the same equality test, and the shared statistics helpers in `StatisticsCalculations.hpp` and `HistogramUtilities.hpp` sort and key floating-point values with `operator<`. `ComputeArrayMinMax` is not NaN-aware -(issue #1874). +(issue #1874). **Invert Intensity Image** accepts a NaN **Maximum** and writes 0 to every integer pixel (issue #1873). **Why:** every comparison with NaN is false. `operator<` is then not a strict weak ordering, so `std::sort`, `std::stable_sort` and `std::map` keys are undefined; a threshold or a bin search puts NaN on one side without saying -so; an equality test written as "neither is less than the other" groups NaN with every value; and a cast of NaN to an -integer is undefined behavior. Whether NaN means "bad data" or "no measurement" depends on the user's data, so the -code cannot pick one answer for everyone. +so; an equality test written as "neither is less than the other" groups NaN with every value; and a cast of NaN or an +infinity to an integer is undefined behavior. Whether a nonfinite input value means "bad data" or "no measurement" +depends on the user's data, so input array values get a choice; parameters and file values do not. **What to look for:** - `std::sort`, `std::stable_sort`, `std::map`, `std::set` or `std::unique` over floating-point input values; - an equivalence written as `!(a < b) && !(b < a)` on floating-point values; -- a running minimum, maximum or sum over input values with no NaN test; -- a threshold, tolerance or bin index computed from an input value with no NaN test. +- a running minimum, maximum or sum over input values with no finiteness test; +- a threshold, tolerance or bin index computed from an input value with no finiteness test; +- a parameter check written as `value < 0` or `value <= 0`, which NaN passes. -**Pattern to use:** the **NaN Value Handling** parameter and the shared NaN skip rule of **Compute Bounding Box Stats** -(the fix for `ComputeBoundingBoxStatsFilter#9` of issue #1867). +**Pattern to use:** **Nonfinite Input Handling** in `ThresholdMaximumConnectedComponentsImageFilter` and +`WriteImageFilter` (PR #1888); the Upper Boundary of `ThresholdMaximumConnectedComponentsImageFilter` for a documented +meaning of infinity (PR #1888). ### Copy every field that sets behavior when you clone an object diff --git a/src/Plugins/NXImageProcessing/docs/BinaryDilateImageFilter.md b/src/Plugins/NXImageProcessing/docs/BinaryDilateImageFilter.md index ca54cd806e..93ae5d5074 100644 --- a/src/Plugins/NXImageProcessing/docs/BinaryDilateImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/BinaryDilateImageFilter.md @@ -43,6 +43,8 @@ The `BinaryMorphScanline` out-of-core path bulk-reads bounded slabs with a share ![Binary dilation example.](Images/BinaryDilation.png) +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/BinaryErodeImageFilter.md b/src/Plugins/NXImageProcessing/docs/BinaryErodeImageFilter.md index d7c2d92732..b7d82e4831 100644 --- a/src/Plugins/NXImageProcessing/docs/BinaryErodeImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/BinaryErodeImageFilter.md @@ -43,6 +43,8 @@ The `BinaryMorphScanline` out-of-core path bulk-reads bounded slabs with a share ![Binary erosion example.](Images/BinaryErosion.png) +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/BinaryMorphologicalClosingImageFilter.md b/src/Plugins/NXImageProcessing/docs/BinaryMorphologicalClosingImageFilter.md index 4363ca87a3..3e94346f95 100644 --- a/src/Plugins/NXImageProcessing/docs/BinaryMorphologicalClosingImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/BinaryMorphologicalClosingImageFilter.md @@ -49,6 +49,8 @@ Other cases retain the raw-ring fallback. If the ring reservation is unavailable ![Binary closing example.](Images/BinaryClosing.png) +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/BinaryMorphologicalOpeningImageFilter.md b/src/Plugins/NXImageProcessing/docs/BinaryMorphologicalOpeningImageFilter.md index ea85fa9eba..b1beb1b8ee 100644 --- a/src/Plugins/NXImageProcessing/docs/BinaryMorphologicalOpeningImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/BinaryMorphologicalOpeningImageFilter.md @@ -43,6 +43,8 @@ Other cases retain the raw-ring fallback. If the ring reservation is unavailable ![Binary opening example.](Images/BinaryOpening.png) +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/BinaryOpeningByReconstructionImageFilter.md b/src/Plugins/NXImageProcessing/docs/BinaryOpeningByReconstructionImageFilter.md index 58c78ac874..e709fd7d97 100644 --- a/src/Plugins/NXImageProcessing/docs/BinaryOpeningByReconstructionImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/BinaryOpeningByReconstructionImageFilter.md @@ -36,6 +36,8 @@ The filter erodes the binary foreground and reconstructs the surviving marker wi ![Binary opening by reconstruction.](Images/OpeningByReconstruction.png) +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/BlackTopHatImageFilter.md b/src/Plugins/NXImageProcessing/docs/BlackTopHatImageFilter.md index 3ccb880862..5554546644 100644 --- a/src/Plugins/NXImageProcessing/docs/BlackTopHatImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/BlackTopHatImageFilter.md @@ -44,6 +44,8 @@ The out-of-core composite path uses Z-rings bounded by the kernel radius and ser ![Black top-hat example.](Images/BlackTopHat_1.png) ![Black top-hat example.](Images/BlackTopHat_2.png) +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/ClosingByReconstructionImageFilter.md b/src/Plugins/NXImageProcessing/docs/ClosingByReconstructionImageFilter.md index 74c121293c..92160098bf 100644 --- a/src/Plugins/NXImageProcessing/docs/ClosingByReconstructionImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/ClosingByReconstructionImageFilter.md @@ -34,6 +34,8 @@ Geodesic morphology and opening/closing by reconstruction are described in Chapt The filter dilates the input and reconstructs the dilated marker under the input by erosion, optionally performing a second reconstruction to restore preserved intensities. Resident arrays use the Vincent hybrid reconstruction, whose raster, anti-raster, and fold-to-convergence sweeps run as dependency-exact, block-wavefront parallel plane sweeps when the reconstruction uses face connectivity (**Fully Connected** off); with full connectivity it falls back to the exact serial sweeps, since a same-row diagonal read can land in the horizontally adjacent block, which no rectangular block schedule can order. Disk-backed reconstruction iterates a forward raster sweep followed by a reverse anti-raster sweep over consecutive Z-plane slabs until stable, skipping any slab whose planes are already proven unchanged since that direction's last visit. Within a plane, the raster/anti-raster sweep is tiled into independent blocks that run in parallel; under face connectivity every voxel still sees exactly the values the un-blocked sweep would produce, and under full connectivity the iterated forward/reverse passes still converge to the identical final result. Each work and mask slab targets 16 MiB, plus one boundary plane. At least one plane is processed, so a single plane wider than the target can make the buffers exceed 16 MiB. Update order and output are unchanged, preserving exact storage-path parity. +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/DilateObjectMorphologyImageFilter.md b/src/Plugins/NXImageProcessing/docs/DilateObjectMorphologyImageFilter.md index 7597443b0e..8062521065 100644 --- a/src/Plugins/NXImageProcessing/docs/DilateObjectMorphologyImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/DilateObjectMorphologyImageFilter.md @@ -43,6 +43,8 @@ For a true 3D image with an out-of-core input or output, the filter first asks t For a true 2D image, a checked planner keeps the combined input halo, boundary mask, and output below a 64 MiB target. Normal-width images use full-width row blocks; exceptionally wide images use X tiles with halos. Both routes preserve the same boundary classification, kernel-offset order, exact-value comparisons, and non-cascading output as the in-core path. +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/ErodeObjectMorphologyImageFilter.md b/src/Plugins/NXImageProcessing/docs/ErodeObjectMorphologyImageFilter.md index e281baf811..5f878007a6 100644 --- a/src/Plugins/NXImageProcessing/docs/ErodeObjectMorphologyImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/ErodeObjectMorphologyImageFilter.md @@ -43,6 +43,8 @@ For a true 3D image with an out-of-core input or output, the filter first asks t For a true 2D image, a checked planner keeps the combined input halo, boundary mask, and output below a 64 MiB target. Normal-width images use full-width row blocks; exceptionally wide images use X tiles with halos. Both routes preserve the same boundary classification, kernel-offset order, exact-value comparisons, and non-cascading output as the in-core path. +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/GrayscaleDilateImageFilter.md b/src/Plugins/NXImageProcessing/docs/GrayscaleDilateImageFilter.md index 404feddac2..c58a6d1fb6 100644 --- a/src/Plugins/NXImageProcessing/docs/GrayscaleDilateImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/GrayscaleDilateImageFilter.md @@ -37,6 +37,8 @@ The `MorphScanline` out-of-core path bulk-reads bounded slabs with a shared Z ha ![Grayscale dilation example.](Images/GrayscaleDilation.png) +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/GrayscaleErodeImageFilter.md b/src/Plugins/NXImageProcessing/docs/GrayscaleErodeImageFilter.md index 581aed0ab8..0273c557df 100644 --- a/src/Plugins/NXImageProcessing/docs/GrayscaleErodeImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/GrayscaleErodeImageFilter.md @@ -37,6 +37,8 @@ The `MorphScanline` out-of-core path bulk-reads bounded slabs with a shared Z ha ![Grayscale erosion example.](Images/GrayscaleErosion.png) +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/GrayscaleMorphologicalClosingImageFilter.md b/src/Plugins/NXImageProcessing/docs/GrayscaleMorphologicalClosingImageFilter.md index aa72cce1fe..3cb0060253 100644 --- a/src/Plugins/NXImageProcessing/docs/GrayscaleMorphologicalClosingImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/GrayscaleMorphologicalClosingImageFilter.md @@ -43,6 +43,8 @@ The out-of-core composite path uses Z-rings bounded by the kernel radius and ser ![Grayscale closing example.](Images/GrayscaleClosing.png) +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/GrayscaleMorphologicalOpeningImageFilter.md b/src/Plugins/NXImageProcessing/docs/GrayscaleMorphologicalOpeningImageFilter.md index 9e10f5414e..5c648a1163 100644 --- a/src/Plugins/NXImageProcessing/docs/GrayscaleMorphologicalOpeningImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/GrayscaleMorphologicalOpeningImageFilter.md @@ -43,6 +43,8 @@ The out-of-core composite path uses Z-rings bounded by the kernel radius and ser ![Grayscale opening example.](Images/GrayscaleOpening.png) +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/MorphologicalGradientImageFilter.md b/src/Plugins/NXImageProcessing/docs/MorphologicalGradientImageFilter.md index 00fb4f24b0..b38ccd5567 100644 --- a/src/Plugins/NXImageProcessing/docs/MorphologicalGradientImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/MorphologicalGradientImageFilter.md @@ -37,6 +37,8 @@ The `MorphGradientScanline` out-of-core path keeps store reads and writes serial For a single-slice image, the path uses a checked 64 MiB aggregate target. A fitting out-of-core input may use a fixed 48 MiB input buffer and at most 16 MiB of output staging; otherwise the image is processed as full-width row blocks or, for exceptionally wide rows, X tiles with their clipped X/Y halos. Empty structuring elements emit zero through the same bounded-write policy. No datastore access occurs inside the parallel voxel loop. +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/OpeningByReconstructionImageFilter.md b/src/Plugins/NXImageProcessing/docs/OpeningByReconstructionImageFilter.md index 7c67f4e329..dc8497ca90 100644 --- a/src/Plugins/NXImageProcessing/docs/OpeningByReconstructionImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/OpeningByReconstructionImageFilter.md @@ -34,6 +34,8 @@ Geodesic morphology and opening/closing by reconstruction are described in Chapt The filter erodes the input and reconstructs the eroded marker under the input by dilation, optionally performing a second reconstruction to restore preserved intensities. Resident arrays use the Vincent hybrid reconstruction, whose raster, anti-raster, and fold-to-convergence sweeps run as dependency-exact, block-wavefront parallel plane sweeps when the reconstruction uses face connectivity (**Fully Connected** off); with full connectivity it falls back to the exact serial sweeps, since a same-row diagonal read can land in the horizontally adjacent block, which no rectangular block schedule can order. Disk-backed reconstruction iterates a forward raster sweep followed by a reverse anti-raster sweep over consecutive Z-plane slabs until stable, skipping any slab whose planes are already proven unchanged since that direction's last visit. Within a plane, the raster/anti-raster sweep is tiled into independent blocks that run in parallel; under face connectivity every voxel still sees exactly the values the un-blocked sweep would produce, and under full connectivity the iterated forward/reverse passes still converge to the identical final result. Each work and mask slab targets 16 MiB, plus one boundary plane. At least one plane is processed, so a single plane wider than the target can make the buffers exceed 16 MiB. Update order and output are unchanged, preserving exact storage-path parity. +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/docs/WhiteTopHatImageFilter.md b/src/Plugins/NXImageProcessing/docs/WhiteTopHatImageFilter.md index 7cf9935533..491590338f 100644 --- a/src/Plugins/NXImageProcessing/docs/WhiteTopHatImageFilter.md +++ b/src/Plugins/NXImageProcessing/docs/WhiteTopHatImageFilter.md @@ -43,6 +43,8 @@ The out-of-core composite path uses Z-rings bounded by the kernel radius and ser ![White top-hat example.](Images/WhiteTopHat.png) +**Kernel Radius** accepts 0–2147483646 cells per axis when kernel counts and image layouts are representable. + % Auto generated parameter table will be inserted here ## Example Pipelines diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryDilateImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryDilateImageFilter.cpp index 4e28546c9c..ba44afbc06 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryDilateImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryDilateImageFilter.cpp @@ -101,6 +101,18 @@ IFilter::PreflightResult BinaryDilateImageFilter::preflightImpl(const DataStruct auto backgroundValue = filterArgs.value(k_BackgroundValue_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(layoutInputArray.getDataType())); layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); if(inputArray.getNumberOfComponents() != 1) { @@ -144,8 +156,18 @@ Result<> BinaryDilateImageFilter::executeImpl(DataStructure& dataStructure, cons auto foregroundValue = filterArgs.value(k_ForegroundValue_Key); auto boundaryToForeground = filterArgs.value(k_BoundaryToForeground_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(inputArray.getDataType())); layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); return ImageProcessing::ExecuteBinaryMorphologyImageFilter(dataStructure, imageGeomPath, selectedInputArray, outputArrayPath, se, ImageProcessing::MorphOp::Dilate, foregroundValue, backgroundValue, boundaryToForeground, shouldCancel, messageHandler); diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryErodeImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryErodeImageFilter.cpp index 64fb9579b5..0093f54ca6 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryErodeImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryErodeImageFilter.cpp @@ -100,6 +100,18 @@ IFilter::PreflightResult BinaryErodeImageFilter::preflightImpl(const DataStructu auto backgroundValue = filterArgs.value(k_BackgroundValue_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(layoutInputArray.getDataType())); layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); if(inputArray.getNumberOfComponents() != 1) { @@ -143,8 +155,18 @@ Result<> BinaryErodeImageFilter::executeImpl(DataStructure& dataStructure, const auto foregroundValue = filterArgs.value(k_ForegroundValue_Key); auto boundaryToForeground = filterArgs.value(k_BoundaryToForeground_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(inputArray.getDataType())); layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); return ImageProcessing::ExecuteBinaryMorphologyImageFilter(dataStructure, imageGeomPath, selectedInputArray, outputArrayPath, se, ImageProcessing::MorphOp::Erode, foregroundValue, backgroundValue, boundaryToForeground, shouldCancel, messageHandler); diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryMorphologicalClosingImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryMorphologicalClosingImageFilter.cpp index c93e79e5c7..dbe3d0a800 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryMorphologicalClosingImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryMorphologicalClosingImageFilter.cpp @@ -96,6 +96,19 @@ IFilter::PreflightResult BinaryMorphologicalClosingImageFilter::preflightImpl(co auto foregroundValue = filterArgs.value(k_ForegroundValue_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, filterArgs.value(k_SafeBorder_Key), GetDataTypeSize(layoutInputArray.getDataType())); + layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); if(inputArray.getNumberOfComponents() != 1) { @@ -139,8 +152,19 @@ Result<> BinaryMorphologicalClosingImageFilter::executeImpl(DataStructure& dataS auto foregroundValue = filterArgs.value(k_ForegroundValue_Key); auto safeBorder = filterArgs.value(k_SafeBorder_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, filterArgs.value(k_SafeBorder_Key), GetDataTypeSize(inputArray.getDataType())); + layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); // Closing derives its own internal background, so the façade's background argument is unused for Closing; pass 0.0. return ImageProcessing::ExecuteBinaryMorphologyCompositeImageFilter(dataStructure, imageGeomPath, selectedInputArray, outputArrayPath, se, ImageProcessing::BinaryCompositeOp::Closing, diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryMorphologicalOpeningImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryMorphologicalOpeningImageFilter.cpp index 18e3b84ec1..9eafdc0814 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryMorphologicalOpeningImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryMorphologicalOpeningImageFilter.cpp @@ -99,6 +99,18 @@ IFilter::PreflightResult BinaryMorphologicalOpeningImageFilter::preflightImpl(co auto backgroundValue = filterArgs.value(k_BackgroundValue_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(layoutInputArray.getDataType())); layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); if(inputArray.getNumberOfComponents() != 1) { @@ -141,8 +153,18 @@ Result<> BinaryMorphologicalOpeningImageFilter::executeImpl(DataStructure& dataS auto backgroundValue = filterArgs.value(k_BackgroundValue_Key); auto foregroundValue = filterArgs.value(k_ForegroundValue_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(inputArray.getDataType())); layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); // SafeBorder is irrelevant for Opening (ITK binary opening never pads); pass false. return ImageProcessing::ExecuteBinaryMorphologyCompositeImageFilter(dataStructure, imageGeomPath, selectedInputArray, outputArrayPath, se, ImageProcessing::BinaryCompositeOp::Opening, diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryOpeningByReconstructionImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryOpeningByReconstructionImageFilter.cpp index 13ed026969..d5e61bfa45 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryOpeningByReconstructionImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BinaryOpeningByReconstructionImageFilter.cpp @@ -100,6 +100,18 @@ IFilter::PreflightResult BinaryOpeningByReconstructionImageFilter::preflightImpl auto backgroundValue = filterArgs.value(k_BackgroundValue_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(layoutInputArray.getDataType())); layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + // Foreground and background must be distinct: a binary image is defined by two different labels, and fg==bg makes // the strict-binary input scan, the erode boundary fill, and the fg/bg-ordering reconstruction-op selection all // degenerate. @@ -147,8 +159,18 @@ Result<> BinaryOpeningByReconstructionImageFilter::executeImpl(DataStructure& da auto backgroundValue = filterArgs.value(k_BackgroundValue_Key); auto fullyConnected = filterArgs.value(k_FullyConnected_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(inputArray.getDataType())); layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); // Binary opening by reconstruction == binary erode with the structuring element, then binary // reconstruction-by-dilation of the eroded image under the original input (retain surviving foreground objects). diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BlackTopHatImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BlackTopHatImageFilter.cpp index f9219e4c6d..453a66e190 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BlackTopHatImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/BlackTopHatImageFilter.cpp @@ -76,6 +76,19 @@ IFilter::PreflightResult BlackTopHatImageFilter::preflightImpl(const DataStructu auto outputArrayName = filterArgs.value(k_OutputImageArrayName_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, filterArgs.value(k_SafeBorder_Key), GetDataTypeSize(layoutInputArray.getDataType())); + layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); if(inputArray.getNumberOfComponents() != 1) { @@ -98,8 +111,19 @@ Result<> BlackTopHatImageFilter::executeImpl(DataStructure& dataStructure, const auto kernelType = filterArgs.value(k_KernelType_Key); auto safeBorder = filterArgs.value(k_SafeBorder_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, filterArgs.value(k_SafeBorder_Key), GetDataTypeSize(inputArray.getDataType())); + layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); return ImageProcessing::ExecuteMorphologyCompositeImageFilter(dataStructure, imageGeomPath, selectedInputArray, outputArrayPath, se, ImageProcessing::MorphCompositeOp::BlackTopHat, safeBorder, shouldCancel, messageHandler); diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/ClosingByReconstructionImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/ClosingByReconstructionImageFilter.cpp index 4e318a6d19..13196bacd0 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/ClosingByReconstructionImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/ClosingByReconstructionImageFilter.cpp @@ -79,6 +79,18 @@ IFilter::PreflightResult ClosingByReconstructionImageFilter::preflightImpl(const auto outputArrayName = filterArgs.value(k_OutputImageArrayName_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(layoutInputArray.getDataType())); layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + // requireScalar=true: the grayscale reconstruction engine is defined on scalar images (matching the legacy ITK // operator); the shared preflight also validates type membership and the geometry/tuple match. return {ImageProcessing::PreflightFullOverwriteImageFilter(dataStructure, selectedInputArray, imageGeomPath, outputArrayPath, @@ -97,8 +109,18 @@ Result<> ClosingByReconstructionImageFilter::executeImpl(DataStructure& dataStru auto fullyConnected = filterArgs.value(k_FullyConnected_Key); auto preserveIntensities = filterArgs.value(k_PreserveIntensities_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(inputArray.getDataType())); layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); // Closing by reconstruction == grayscale dilate with the structuring element, then reconstruct-by-erosion of the // dilated image under the original input as the mask (firstOp = Dilate). diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/DilateObjectMorphologyImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/DilateObjectMorphologyImageFilter.cpp index 0fd62c6c06..85634bc415 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/DilateObjectMorphologyImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/DilateObjectMorphologyImageFilter.cpp @@ -93,6 +93,18 @@ IFilter::PreflightResult DilateObjectMorphologyImageFilter::preflightImpl(const auto objectValue = filterArgs.value(k_ObjectValue_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(layoutInputArray.getDataType())); layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); if(inputArray.getNumberOfComponents() != 1) { @@ -135,8 +147,18 @@ Result<> DilateObjectMorphologyImageFilter::executeImpl(DataStructure& dataStruc auto kernelType = filterArgs.value(k_KernelType_Key); auto objectValue = filterArgs.value(k_ObjectValue_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(inputArray.getDataType())); layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); return ImageProcessing::ExecuteObjectMorphologyImageFilter(dataStructure, imageGeomPath, selectedInputArray, outputArrayPath, se, ImageProcessing::ObjectMorphOp::Dilate, objectValue, /*backgroundValue=*/0.0, shouldCancel, messageHandler); diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/ErodeObjectMorphologyImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/ErodeObjectMorphologyImageFilter.cpp index 4f1551936e..c99aadf6f0 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/ErodeObjectMorphologyImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/ErodeObjectMorphologyImageFilter.cpp @@ -98,6 +98,18 @@ IFilter::PreflightResult ErodeObjectMorphologyImageFilter::preflightImpl(const D auto backgroundValue = filterArgs.value(k_BackgroundValue_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(layoutInputArray.getDataType())); layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); if(inputArray.getNumberOfComponents() != 1) { @@ -153,8 +165,18 @@ Result<> ErodeObjectMorphologyImageFilter::executeImpl(DataStructure& dataStruct auto objectValue = filterArgs.value(k_ObjectValue_Key); auto backgroundValue = filterArgs.value(k_BackgroundValue_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(inputArray.getDataType())); layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); return ImageProcessing::ExecuteObjectMorphologyImageFilter(dataStructure, imageGeomPath, selectedInputArray, outputArrayPath, se, ImageProcessing::ObjectMorphOp::Erode, objectValue, backgroundValue, shouldCancel, messageHandler); diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleDilateImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleDilateImageFilter.cpp index 519c165a09..565d012faf 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleDilateImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleDilateImageFilter.cpp @@ -74,6 +74,18 @@ IFilter::PreflightResult GrayscaleDilateImageFilter::preflightImpl(const DataStr auto outputArrayName = filterArgs.value(k_OutputImageArrayName_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(layoutInputArray.getDataType())); layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); if(inputArray.getNumberOfComponents() != 1) { @@ -95,8 +107,18 @@ Result<> GrayscaleDilateImageFilter::executeImpl(DataStructure& dataStructure, c auto kernelRadius = filterArgs.value(k_KernelRadius_Key); auto kernelType = filterArgs.value(k_KernelType_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(inputArray.getDataType())); layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); return ImageProcessing::ExecuteMorphologyImageFilter(dataStructure, imageGeomPath, selectedInputArray, outputArrayPath, se, ImageProcessing::MorphOp::Dilate, shouldCancel, messageHandler); } diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleErodeImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleErodeImageFilter.cpp index 3def9c340e..8a87291679 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleErodeImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleErodeImageFilter.cpp @@ -74,6 +74,18 @@ IFilter::PreflightResult GrayscaleErodeImageFilter::preflightImpl(const DataStru auto outputArrayName = filterArgs.value(k_OutputImageArrayName_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(layoutInputArray.getDataType())); layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); if(inputArray.getNumberOfComponents() != 1) { @@ -95,8 +107,18 @@ Result<> GrayscaleErodeImageFilter::executeImpl(DataStructure& dataStructure, co auto kernelRadius = filterArgs.value(k_KernelRadius_Key); auto kernelType = filterArgs.value(k_KernelType_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(inputArray.getDataType())); layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); return ImageProcessing::ExecuteMorphologyImageFilter(dataStructure, imageGeomPath, selectedInputArray, outputArrayPath, se, ImageProcessing::MorphOp::Erode, shouldCancel, messageHandler); } diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleMorphologicalClosingImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleMorphologicalClosingImageFilter.cpp index dea76abca7..f2ab868706 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleMorphologicalClosingImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleMorphologicalClosingImageFilter.cpp @@ -76,6 +76,19 @@ IFilter::PreflightResult GrayscaleMorphologicalClosingImageFilter::preflightImpl auto outputArrayName = filterArgs.value(k_OutputImageArrayName_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, filterArgs.value(k_SafeBorder_Key), GetDataTypeSize(layoutInputArray.getDataType())); + layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); if(inputArray.getNumberOfComponents() != 1) { @@ -98,8 +111,19 @@ Result<> GrayscaleMorphologicalClosingImageFilter::executeImpl(DataStructure& da auto kernelType = filterArgs.value(k_KernelType_Key); auto safeBorder = filterArgs.value(k_SafeBorder_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, filterArgs.value(k_SafeBorder_Key), GetDataTypeSize(inputArray.getDataType())); + layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); return ImageProcessing::ExecuteMorphologyCompositeImageFilter(dataStructure, imageGeomPath, selectedInputArray, outputArrayPath, se, ImageProcessing::MorphCompositeOp::Closing, safeBorder, shouldCancel, messageHandler); diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleMorphologicalOpeningImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleMorphologicalOpeningImageFilter.cpp index f8938dcfd9..ccf965c65f 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleMorphologicalOpeningImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/GrayscaleMorphologicalOpeningImageFilter.cpp @@ -76,6 +76,19 @@ IFilter::PreflightResult GrayscaleMorphologicalOpeningImageFilter::preflightImpl auto outputArrayName = filterArgs.value(k_OutputImageArrayName_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, filterArgs.value(k_SafeBorder_Key), GetDataTypeSize(layoutInputArray.getDataType())); + layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); if(inputArray.getNumberOfComponents() != 1) { @@ -98,8 +111,19 @@ Result<> GrayscaleMorphologicalOpeningImageFilter::executeImpl(DataStructure& da auto kernelType = filterArgs.value(k_KernelType_Key); auto safeBorder = filterArgs.value(k_SafeBorder_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, filterArgs.value(k_SafeBorder_Key), GetDataTypeSize(inputArray.getDataType())); + layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); return ImageProcessing::ExecuteMorphologyCompositeImageFilter(dataStructure, imageGeomPath, selectedInputArray, outputArrayPath, se, ImageProcessing::MorphCompositeOp::Opening, safeBorder, shouldCancel, messageHandler); diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/MorphologicalGradientImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/MorphologicalGradientImageFilter.cpp index 449ae09048..a0daf4ca78 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/MorphologicalGradientImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/MorphologicalGradientImageFilter.cpp @@ -74,6 +74,18 @@ IFilter::PreflightResult MorphologicalGradientImageFilter::preflightImpl(const D auto outputArrayName = filterArgs.value(k_OutputImageArrayName_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(layoutInputArray.getDataType())); layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); if(inputArray.getNumberOfComponents() != 1) { @@ -95,8 +107,18 @@ Result<> MorphologicalGradientImageFilter::executeImpl(DataStructure& dataStruct auto kernelRadius = filterArgs.value(k_KernelRadius_Key); auto kernelType = filterArgs.value(k_KernelType_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(inputArray.getDataType())); layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); // Morphological Gradient has no SafeBorder in ITK (single-pass dilate - erode), so safeBorder is passed // false and ignored by the composite façade for this op. diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/OpeningByReconstructionImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/OpeningByReconstructionImageFilter.cpp index 16f80f0cea..bc23f23af7 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/OpeningByReconstructionImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/OpeningByReconstructionImageFilter.cpp @@ -79,6 +79,18 @@ IFilter::PreflightResult OpeningByReconstructionImageFilter::preflightImpl(const auto outputArrayName = filterArgs.value(k_OutputImageArrayName_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(layoutInputArray.getDataType())); layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + // requireScalar=true: the grayscale reconstruction engine is defined on scalar images (matching the legacy ITK // operator); the shared preflight also validates type membership and the geometry/tuple match. return {ImageProcessing::PreflightFullOverwriteImageFilter(dataStructure, selectedInputArray, imageGeomPath, outputArrayPath, @@ -97,8 +109,18 @@ Result<> OpeningByReconstructionImageFilter::executeImpl(DataStructure& dataStru auto fullyConnected = filterArgs.value(k_FullyConnected_Key); auto preserveIntensities = filterArgs.value(k_PreserveIntensities_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, false, GetDataTypeSize(inputArray.getDataType())); layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); // Opening by reconstruction == grayscale erode with the structuring element, then reconstruct-by-dilation of the // eroded image under the original input as the mask (firstOp = Erode). diff --git a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/WhiteTopHatImageFilter.cpp b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/WhiteTopHatImageFilter.cpp index ae6f9150e1..5734d4d811 100644 --- a/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/WhiteTopHatImageFilter.cpp +++ b/src/Plugins/NXImageProcessing/src/NXImageProcessing/Filters/WhiteTopHatImageFilter.cpp @@ -76,6 +76,19 @@ IFilter::PreflightResult WhiteTopHatImageFilter::preflightImpl(const DataStructu auto outputArrayName = filterArgs.value(k_OutputImageArrayName_Key); const DataPath outputArrayPath = selectedInputArray.replaceName(outputArrayName); + const auto kernelRadius = filterArgs.value(k_KernelRadius_Key); + if(auto radiusResult = ImageProcessing::ValidateKernelRadius(kernelRadius); radiusResult.invalid()) + { + return {ConvertResultTo(std::move(radiusResult), OutputActions{})}; + } + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& layoutInputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, filterArgs.value(k_SafeBorder_Key), GetDataTypeSize(layoutInputArray.getDataType())); + layoutResult.invalid()) + { + return {ConvertResultTo(ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath), OutputActions{})}; + } + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); if(inputArray.getNumberOfComponents() != 1) { @@ -98,8 +111,19 @@ Result<> WhiteTopHatImageFilter::executeImpl(DataStructure& dataStructure, const auto kernelType = filterArgs.value(k_KernelType_Key); auto safeBorder = filterArgs.value(k_SafeBorder_Key); - const ImageProcessing::StructuringElement se = ImageProcessing::MakeStructuringElement( - static_cast(kernelType), {static_cast(kernelRadius[0]), static_cast(kernelRadius[1]), static_cast(kernelRadius[2])}); + const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); + const auto& inputArray = dataStructure.getDataRefAs(selectedInputArray); + if(auto layoutResult = ImageProcessing::ValidateMorphologyLayout(imageGeom.getDimensions(), kernelRadius, filterArgs.value(k_SafeBorder_Key), GetDataTypeSize(inputArray.getDataType())); + layoutResult.invalid()) + { + return ImageProcessing::AddMorphologyLayoutGeometryContext(std::move(layoutResult), imageGeomPath); + } + auto kernelResult = ImageProcessing::MakeCheckedStructuringElement(static_cast(kernelType), kernelRadius); + if(kernelResult.invalid()) + { + return ConvertInvalidResult(std::move(kernelResult)); + } + const ImageProcessing::StructuringElement& se = kernelResult.value(); return ImageProcessing::ExecuteMorphologyCompositeImageFilter(dataStructure, imageGeomPath, selectedInputArray, outputArrayPath, se, ImageProcessing::MorphCompositeOp::WhiteTopHat, safeBorder, shouldCancel, messageHandler); diff --git a/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationEngineTest.cpp b/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationEngineTest.cpp index 4271e2f433..cf9118494e 100644 --- a/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationEngineTest.cpp +++ b/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationEngineTest.cpp @@ -538,3 +538,224 @@ TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationEngine: validates dim REQUIRE(result.errors().front().code == -8544); } } + +namespace +{ +// Both traversals use the same LUT to isolate traversal differences. +template +std::vector MakeTraversalLut(const std::vector& input, float64 iscale) +{ + const auto [minimum, maximum] = std::minmax_element(input.cbegin(), input.cend()); + const int64 span = static_cast(*maximum) - static_cast(*minimum); + std::vector lookupTable(static_cast(2 * span + 1)); + for(usize index = 0; index < lookupTable.size(); ++index) + { + const int64 difference = static_cast(index) - span; + const float64 normalizedDifference = static_cast(difference) / iscale; + const float32 sign = static_cast(ImageProcessing::detail::AdaptiveEqualizationSgn(static_cast(normalizedDifference))); + const float32 absoluteDifference = static_cast(std::fabs(2.0 * normalizedDifference)); + lookupTable[index] = 0.5f * sign * std::pow(absoluteDifference, 0.37f) - (0.21f * 0.5f) * sign * absoluteDifference; + } + return lookupTable; +} + +template +void CheckPlaneTraversalIdentity() +{ + constexpr usize dimX = 7; + constexpr usize dimY = 6; + constexpr usize dimZ = 7; + constexpr usize sliceValues = dimX * dimY; + const std::vector input = MakeAhePattern(dimX, dimY, dimZ); + const auto [minimum, maximum] = std::minmax_element(input.cbegin(), input.cend()); + const float64 minValue = static_cast(*minimum); + const float64 iscale = static_cast(*maximum) - minValue; + const std::array, 2> radii = {{{2, 1, 1}, {1, 3, 0}}}; + for(const auto& radius : radii) + { + for(usize z = 0; z < dimZ; ++z) + { + const usize zLo = z > radius[2] ? z - radius[2] : 0; + const usize zHi = std::min(dimZ - 1, z + radius[2]); + CAPTURE(radius, z, zLo); + const std::vector slab(input.begin() + zLo * sliceValues, input.begin() + (zHi + 1) * sliceValues); + std::vector actual(sliceValues, T{73}); + std::vector expected(sliceValues, T{91}); + if constexpr(std::is_integral_v) + { + const std::vector lookupTable = MakeTraversalLut(input, iscale); + ImageProcessing::detail::AdaptiveHistogramEqualizationLutPlaneBody body{ + slab.data(), actual.data(), dimX, dimY, dimZ, radius[0], radius[1], radius[2], zLo, z, minValue, iscale, 0.21f, lookupTable.data(), -static_cast(iscale), lookupTable.size()}; + auto referenceBody = body; + referenceBody.outPlane = expected.data(); + ahe_test::unclipped::AdaptiveHistogramEqualizationLutPlaneBody(referenceBody, Range{0, sliceValues}); + body(Range{0, sliceValues}); + } + else + { + ImageProcessing::detail::AdaptiveHistogramEqualizationPlaneBody body{slab.data(), actual.data(), dimX, dimY, dimZ, radius[0], radius[1], radius[2], zLo, z, minValue, iscale, 0.37f, 0.21f}; + auto referenceBody = body; + referenceBody.outPlane = expected.data(); + ahe_test::unclipped::AdaptiveHistogramEqualizationPlaneBody(referenceBody, Range{0, sliceValues}); + body(Range{0, sliceValues}); + } + REQUIRE(actual == expected); + } + } +} + +template +void CheckBlockTraversalIdentity() +{ + constexpr usize dimX = 9; + constexpr usize dimY = 8; + const std::vector input = MakeAhePattern(dimX, dimY, 1); + const auto [minimum, maximum] = std::minmax_element(input.cbegin(), input.cend()); + const float64 minValue = static_cast(*minimum); + const float64 iscale = static_cast(*maximum) - minValue; + const std::atomic_bool shouldCancel{false}; + const std::array, 2> radii = {{{2, 1}, {1, 3}}}; + const std::array, 2> outputOrigins = {{{0, 0}, {6, 5}}}; + for(const auto& radius : radii) + { + for(const auto& origin : outputOrigins) + { + constexpr usize outputWidth = 3; + constexpr usize outputRows = 3; + const usize inputXBegin = origin[0] > radius[0] ? origin[0] - radius[0] : 0; + const usize inputYBegin = origin[1] > radius[1] ? origin[1] - radius[1] : 0; + const usize inputXEnd = std::min(dimX, origin[0] + outputWidth + radius[0]); + const usize inputYEnd = std::min(dimY, origin[1] + outputRows + radius[1]); + const usize inputWidth = inputXEnd - inputXBegin; + CAPTURE(radius, origin, inputXBegin, inputYBegin); + std::vector block; + for(usize y = inputYBegin; y < inputYEnd; ++y) + { + block.insert(block.end(), input.begin() + y * dimX + inputXBegin, input.begin() + y * dimX + inputXEnd); + } + std::vector actual(outputWidth * outputRows, T{73}); + std::vector expected(outputWidth * outputRows, T{91}); + if constexpr(std::is_integral_v) + { + const std::vector lookupTable = MakeTraversalLut(input, iscale); + ImageProcessing::detail::AdaptiveHistogramEqualizationLut2DBlockBody body{block.data(), + actual.data(), + dimX, + dimY, + radius[0], + radius[1], + inputXBegin, + inputYBegin, + inputWidth, + origin[0], + origin[1], + outputWidth, + minValue, + iscale, + 0.21f, + lookupTable.data(), + -static_cast(iscale), + lookupTable.size(), + shouldCancel}; + auto referenceBody = body; + referenceBody.output = expected.data(); + ahe_test::unclipped::AdaptiveHistogramEqualizationLut2DBlockBody(referenceBody, Range{0, actual.size()}); + body(Range{0, actual.size()}); + } + else + { + ImageProcessing::detail::AdaptiveHistogramEqualization2DBlockBody body{block.data(), actual.data(), dimX, dimY, radius[0], radius[1], inputXBegin, inputYBegin, inputWidth, + origin[0], origin[1], outputWidth, minValue, iscale, 0.37f, 0.21f, shouldCancel}; + auto referenceBody = body; + referenceBody.output = expected.data(); + ahe_test::unclipped::AdaptiveHistogramEqualization2DBlockBody(referenceBody, Range{0, actual.size()}); + body(Range{0, actual.size()}); + } + REQUIRE(actual == expected); + } + } +} + +template +void CheckBoundedTraversalIdentity() +{ + constexpr usize dimX = 9; + constexpr usize dimY = 7; + const std::vector input = MakeAhePattern(dimX, dimY, 1); + const auto [minimum, maximum] = std::minmax_element(input.cbegin(), input.cend()); + const float64 minValue = static_cast(*minimum); + const float64 iscale = static_cast(*maximum) - minValue; + std::vector expected(input.size(), T{91}); + usize lookupBytes = 0; + if constexpr(std::is_integral_v) + { + const std::vector lookupTable = MakeTraversalLut(input, iscale); + lookupBytes = lookupTable.size() * sizeof(float32); + const ImageProcessing::detail::AdaptiveHistogramEqualizationLutPlaneBody body{ + input.data(), expected.data(), dimX, dimY, 1, 2, 1, 3, 0, 0, minValue, iscale, 0.21f, lookupTable.data(), -static_cast(iscale), lookupTable.size()}; + ahe_test::unclipped::AdaptiveHistogramEqualizationLutPlaneBody(body, Range{0, input.size()}); + } + else + { + const ImageProcessing::detail::AdaptiveHistogramEqualizationPlaneBody body{input.data(), expected.data(), dimX, dimY, 1, 2, 1, 3, 0, 0, minValue, iscale, 0.37f, 0.21f}; + ahe_test::unclipped::AdaptiveHistogramEqualizationPlaneBody(body, Range{0, input.size()}); + } + // This test store advertises OutOfCore to select useBounded2D. It is resident, not a real disk-backed store. + // Twenty values of scratch force 2-column tiles, including nonzero input and output origins. + const std::vector actual = RunBoundedAhe(input, dimX, dimY, {2, 1, 3}, 0.37f, 0.21f, 20 * sizeof(T) + lookupBytes, + /*maximumReadValues=*/6, /*maximumWriteValues=*/2, /*expectedWriteCount=*/35); + REQUIRE(actual == expected); +} +} // namespace + +TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationEngine: generic plane operation-order identity", "[NXImageProcessing][AdaptiveHistogramEqualizationEngine]") +{ + CheckPlaneTraversalIdentity(); +} + +TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationEngine: LUT plane operation-order identity", "[NXImageProcessing][AdaptiveHistogramEqualizationEngine]") +{ + CheckPlaneTraversalIdentity(); +} + +TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationEngine: generic 2D block operation-order identity", "[NXImageProcessing][AdaptiveHistogramEqualizationEngine]") +{ + CheckBlockTraversalIdentity(); +} + +TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationEngine: LUT 2D block operation-order identity", "[NXImageProcessing][AdaptiveHistogramEqualizationEngine]") +{ + CheckBlockTraversalIdentity(); +} + +TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationEngine: bounded-store operation-order identity", "[NXImageProcessing][AdaptiveHistogramEqualizationEngine]") +{ + SECTION("generic tiled route") + { + CheckBoundedTraversalIdentity(); + } + SECTION("LUT tiled route") + { + CheckBoundedTraversalIdentity(); + } +} + +TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationEngine: linear uint8 huge-radius positive control", "[NXImageProcessing][AdaptiveHistogramEqualizationEngine]") +{ + constexpr usize huge = std::numeric_limits::max(); + SECTION("3D ring") + { + const auto input = MakeAhePattern(3, 3, 2); + REQUIRE(RunApplyAhe(input, 3, 3, 2, {huge, huge, huge}, 1.0f, 0.25f) == RunApplyAhe(input, 3, 3, 2, {2, 2, 1}, 1.0f, 0.25f)); + } + SECTION("bounded 2D") + { + const auto input = MakeAhePattern(9, 7, 1); + const auto [minimum, maximum] = std::minmax_element(input.cbegin(), input.cend()); + const usize lookupBytes = (2 * static_cast(*maximum - *minimum) + 1) * sizeof(float32); + const auto expected = RunApplyAhe(input, 9, 7, 1, {8, 6, 0}, 1.0f, 0.25f); + const auto actual = RunBoundedAhe(input, 9, 7, {huge, huge, huge}, 1.0f, 0.25f, 4096 + lookupBytes, + /*maximumReadValues=*/63, /*maximumWriteValues=*/63, /*expectedWriteCount=*/1); + REQUIRE(actual == expected); + } +} diff --git a/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationFilterTestUtils.hpp b/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationFilterTestUtils.hpp index 28e077d536..7b22811abe 100644 --- a/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationFilterTestUtils.hpp +++ b/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationFilterTestUtils.hpp @@ -312,4 +312,244 @@ inline void RunAheFilter(IFilter& filter, DataStructure& ds, const DataPath& inp auto executeResult = filter.execute(ds, args); SIMPLNX_RESULT_REQUIRE_VALID(executeResult.result); } +// Frozen pre-clipping traversals from 3321af983. These preserve operation order for exact regression +// comparisons, separate from the independent correctness oracle above. Do not clip these reference loops. +namespace unclipped +{ +using nx::core::ImageProcessing::detail::AdaptiveEqualizationSgn; +template +void AdaptiveHistogramEqualizationPlaneBody(const nx::core::ImageProcessing::detail::AdaptiveHistogramEqualizationPlaneBody& body, const Range& range) +{ + const auto& [slab, outPlane, dimX, dimY, dimZ, rx, ry, rz, zLo, z, minValue, iscale, alpha, beta] = body; + const usize sliceValues = dimX * dimY; + const int64 dimXi = static_cast(dimX); + const int64 dimYi = static_cast(dimY); + const int64 dimZi = static_cast(dimZ); + const int64 rxi = static_cast(rx); + const int64 ryi = static_cast(ry); + const int64 rzi = static_cast(rz); + + for(usize tuple = range.min(); tuple < range.max(); ++tuple) + { + const usize x = tuple % dimX; + const usize y = tuple / dimX; + const int64 xi = static_cast(x); + const int64 yi = static_cast(y); + const int64 zi = static_cast(z); + + const usize centerSlab = (z - zLo) * sliceValues + y * dimX + x; + const float u = static_cast((static_cast(slab[centerSlab]) - minValue) / iscale - 0.5); + // Keep these center-only terms and their expression order fixed for exact traversal comparisons. + const float betaU = beta * u; + const float betaHalf = beta * 0.5f; + + float64 localSum = 0.0; + usize inBounds = 0; + for(int64 dz = -rzi; dz <= rzi; ++dz) + { + const int64 nz = zi + dz; + if(nz < 0 || nz >= dimZi) + { + continue; // OOB neighbor ignored (over-weight the valid part; see struct docs) + } + const usize slabZBase = (static_cast(nz) - zLo) * sliceValues; // nz in [zLo, zHi] once in-bounds + for(int64 dy = -ryi; dy <= ryi; ++dy) + { + const int64 ny = yi + dy; + if(ny < 0 || ny >= dimYi) + { + continue; + } + const usize rowBase = slabZBase + static_cast(ny) * dimX; + for(int64 dx = -rxi; dx <= rxi; ++dx) + { + const int64 nx = xi + dx; + if(nx < 0 || nx >= dimXi) + { + continue; + } + const float v = static_cast((static_cast(slab[rowBase + static_cast(nx)]) - minValue) / iscale - 0.5); + const float sF = static_cast(AdaptiveEqualizationSgn(u - v)); + const float ad = static_cast(std::fabs(2.0 * static_cast(u - v))); + const float cf = 0.5f * sF * std::pow(ad, alpha) - betaHalf * sF * ad + betaU; + localSum += static_cast(cf); + ++inBounds; + } + } + } + const float64 result = iscale * (localSum / static_cast(inBounds) + 0.5) + minValue; + outPlane[tuple] = static_cast(result); + } +} + +template +void AdaptiveHistogramEqualizationLutPlaneBody(const nx::core::ImageProcessing::detail::AdaptiveHistogramEqualizationLutPlaneBody& body, const Range& range) +{ + const auto& [slab, outPlane, dimX, dimY, dimZ, rx, ry, rz, zLo, z, minValue, iscale, beta, gLut, dMin, lutSize] = body; + const usize sliceValues = dimX * dimY; + const int64 dimXi = static_cast(dimX); + const int64 dimYi = static_cast(dimY); + const int64 dimZi = static_cast(dimZ); + const int64 rxi = static_cast(rx); + const int64 ryi = static_cast(ry); + const int64 rzi = static_cast(rz); + + for(usize tuple = range.min(); tuple < range.max(); ++tuple) + { + const usize x = tuple % dimX; + const usize y = tuple / dimX; + const int64 xi = static_cast(x); + const int64 yi = static_cast(y); + const int64 zi = static_cast(z); + + const usize centerSlab = (z - zLo) * sliceValues + y * dimX + x; + const T centerValue = slab[centerSlab]; + const float u = static_cast((static_cast(centerValue) - minValue) / iscale - 0.5); + // Center-only cumulative-function term (independent of the neighbor difference); folded into every + // neighbor contribution below, exactly as the sibling body's per-voxel betaU. + const float betaU = beta * u; + + float64 localSum = 0.0; + usize inBounds = 0; + for(int64 dz = -rzi; dz <= rzi; ++dz) + { + const int64 nz = zi + dz; + if(nz < 0 || nz >= dimZi) + { + continue; // OOB neighbor ignored (over-weight the valid part; see struct docs) + } + const usize slabZBase = (static_cast(nz) - zLo) * sliceValues; // nz in [zLo, zHi] once in-bounds + for(int64 dy = -ryi; dy <= ryi; ++dy) + { + const int64 ny = yi + dy; + if(ny < 0 || ny >= dimYi) + { + continue; + } + const usize rowBase = slabZBase + static_cast(ny) * dimX; + for(int64 dx = -rxi; dx <= rxi; ++dx) + { + const int64 nx = xi + dx; + if(nx < 0 || nx >= dimXi) + { + continue; + } + // Promote to int64 BEFORE subtracting: for unsigned T a T - T subtraction would underflow. The + // gate in ApplyAdaptiveHistogramEqualization guarantees this difference does not overflow int64. + const int64 d = static_cast(centerValue) - static_cast(slab[rowBase + static_cast(nx)]); + const usize lutIndex = static_cast(d - dMin); // in [0, 2*span] by construction + assert(lutIndex < lutSize); + localSum += static_cast(gLut[lutIndex] + betaU); + ++inBounds; + } + } + } + const float64 result = iscale * (localSum / static_cast(inBounds) + 0.5) + minValue; + outPlane[tuple] = static_cast(result); + } +} + +template +void AdaptiveHistogramEqualization2DBlockBody(const nx::core::ImageProcessing::detail::AdaptiveHistogramEqualization2DBlockBody& body, const Range& range) +{ + const auto& [input, output, dimX, dimY, radiusX, radiusY, inputXBegin, inputYBegin, inputWidth, outputXBegin, outputYBegin, outputWidth, minValue, iscale, alpha, beta, shouldCancel] = body; + const int64 dimXi = static_cast(dimX); + const int64 dimYi = static_cast(dimY); + const int64 radiusXi = static_cast(radiusX); + const int64 radiusYi = static_cast(radiusY); + for(usize tuple = range.min(); tuple < range.max(); ++tuple) + { + if(((tuple - range.min()) & 4095ULL) == 0 && shouldCancel) + { + return; + } + const usize localX = tuple % outputWidth; + const usize localY = tuple / outputWidth; + const usize x = outputXBegin + localX; + const usize y = outputYBegin + localY; + const T centerValue = input[(y - inputYBegin) * inputWidth + x - inputXBegin]; + const float u = static_cast((static_cast(centerValue) - minValue) / iscale - 0.5); + const float betaU = beta * u; + const float betaHalf = beta * 0.5f; + float64 localSum = 0.0; + usize inBounds = 0; + for(int64 dy = -radiusYi; dy <= radiusYi; ++dy) + { + const int64 neighborY = static_cast(y) + dy; + if(neighborY < 0 || neighborY >= dimYi) + { + continue; + } + const usize inputRow = (static_cast(neighborY) - inputYBegin) * inputWidth; + for(int64 dx = -radiusXi; dx <= radiusXi; ++dx) + { + const int64 neighborX = static_cast(x) + dx; + if(neighborX < 0 || neighborX >= dimXi) + { + continue; + } + const float v = static_cast((static_cast(input[inputRow + static_cast(neighborX) - inputXBegin]) - minValue) / iscale - 0.5); + const float sign = static_cast(AdaptiveEqualizationSgn(u - v)); + const float absoluteDifference = static_cast(std::fabs(2.0 * static_cast(u - v))); + const float cumulative = 0.5f * sign * std::pow(absoluteDifference, alpha) - betaHalf * sign * absoluteDifference + betaU; + localSum += static_cast(cumulative); + ++inBounds; + } + } + const float64 result = iscale * (localSum / static_cast(inBounds) + 0.5) + minValue; + output[tuple] = static_cast(result); + } +} + +template +void AdaptiveHistogramEqualizationLut2DBlockBody(const nx::core::ImageProcessing::detail::AdaptiveHistogramEqualizationLut2DBlockBody& body, const Range& range) +{ + const auto& [input, output, dimX, dimY, radiusX, radiusY, inputXBegin, inputYBegin, inputWidth, outputXBegin, outputYBegin, outputWidth, minValue, iscale, beta, lookupTable, differenceMinimum, + lookupTableSize, shouldCancel] = body; + const int64 dimXi = static_cast(dimX); + const int64 dimYi = static_cast(dimY); + const int64 radiusXi = static_cast(radiusX); + const int64 radiusYi = static_cast(radiusY); + for(usize tuple = range.min(); tuple < range.max(); ++tuple) + { + if(((tuple - range.min()) & 4095ULL) == 0 && shouldCancel) + { + return; + } + const usize localX = tuple % outputWidth; + const usize localY = tuple / outputWidth; + const usize x = outputXBegin + localX; + const usize y = outputYBegin + localY; + const T centerValue = input[(y - inputYBegin) * inputWidth + x - inputXBegin]; + const float u = static_cast((static_cast(centerValue) - minValue) / iscale - 0.5); + const float betaU = beta * u; + float64 localSum = 0.0; + usize inBounds = 0; + for(int64 dy = -radiusYi; dy <= radiusYi; ++dy) + { + const int64 neighborY = static_cast(y) + dy; + if(neighborY < 0 || neighborY >= dimYi) + { + continue; + } + const usize inputRow = (static_cast(neighborY) - inputYBegin) * inputWidth; + for(int64 dx = -radiusXi; dx <= radiusXi; ++dx) + { + const int64 neighborX = static_cast(x) + dx; + if(neighborX < 0 || neighborX >= dimXi) + { + continue; + } + const int64 difference = static_cast(centerValue) - static_cast(input[inputRow + static_cast(neighborX) - inputXBegin]); + const usize lookupIndex = static_cast(difference - differenceMinimum); + assert(lookupIndex < lookupTableSize); + localSum += static_cast(lookupTable[lookupIndex] + betaU); + ++inBounds; + } + } + const float64 result = iscale * (localSum / static_cast(inBounds) + 0.5) + minValue; + output[tuple] = static_cast(result); + } +} +} // namespace unclipped } // namespace ahe_test diff --git a/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationImageFilterTest.cpp index 22c29e57fd..69a22113b4 100644 --- a/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationImageFilterTest.cpp @@ -10,6 +10,7 @@ #include "simplnx/Parameters/VectorParameter.hpp" #include +#include #include #include @@ -247,3 +248,48 @@ TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationImageFilter: ITK real { RunAheItkGolden("BasicFilters/ITKAdaptiveHistogramEqualizationFilterTest2.png", /*alpha=*/1.0f, /*beta=*/0.25f, /*radius=*/{10, 10, 10}, /*aMaxDiffFraction=*/0.005); } + +namespace +{ +template +void CheckHugeRadiusFilter(usize dimX, usize dimY, usize dimZ, const std::vector& hugeRadius, const std::vector& coveringRadius) +{ + const auto application = Application::GetOrCreateInstance(); + const UnitTest::PreferencesSentinel preferencesSentinel(DataStorageMode::ForceInCore, 0); + std::array, 2> outputs; + const std::array, 2> radii = {coveringRadius, hugeRadius}; + for(usize run = 0; run < radii.size(); ++run) + { + DataStructure dataStructure; + const DataPath inputPath = aht::BuildAheImage(dataStructure, dimX, dimY, dimZ); + AdaptiveHistogramEqualizationImageFilter filter; + aht::RunAheFilter(filter, dataStructure, inputPath, 0.37f, 0.21f, radii[run]); + const DataPath outputPath = inputPath.getParent().createChildPath("Output"); + REQUIRE_NOTHROW(dataStructure.getDataRefAs>(outputPath)); + const auto& outputStore = dataStructure.getDataRefAs>(outputPath).getDataStoreRef(); + REQUIRE(outputStore.getStoreType() == IDataStore::StoreType::InMemory); + outputs[run].resize(outputStore.getSize()); + const Result<> copyResult = outputStore.copyIntoBuffer(0, nonstd::span(outputs[run].data(), outputs[run].size())); + SIMPLNX_RESULT_REQUIRE_VALID(copyResult); + UnitTest::CheckArraysInheritTupleDims(dataStructure); + } + REQUIRE(outputs[0] == outputs[1]); +} +} // namespace + +TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationImageFilter: generic huge-radius clipped neighborhood", "[NXImageProcessing][AdaptiveHistogramEqualizationImageFilter]") +{ + // One unfixed X-only traversal can finish within the 60-second RED timeout on a fast machine. + // Repeat the same approved fixture so that skipped-radius work reliably exceeds that process limit. + for(usize repetition = 0; repetition < 32; ++repetition) + { + CAPTURE(repetition); + CheckHugeRadiusFilter(3, 2, 1, {std::numeric_limits::max(), 0, 0}, {2, 0, 0}); + } +} + +TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationImageFilter: LUT huge-radius clipped neighborhood", "[NXImageProcessing][AdaptiveHistogramEqualizationImageFilter]") +{ + constexpr uint32 huge = std::numeric_limits::max(); + CheckHugeRadiusFilter(3, 3, 2, {huge, huge, huge}, {2, 2, 1}); +} diff --git a/src/Plugins/NXImageProcessing/test/BinaryDilateImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/BinaryDilateImageFilterTest.cpp index e8941423fe..b59c9c429d 100644 --- a/src/Plugins/NXImageProcessing/test/BinaryDilateImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/BinaryDilateImageFilterTest.cpp @@ -233,3 +233,13 @@ TEST_CASE("NXImageProcessing::BinaryDilateImageFilter: Preflight rejects non-sca { morph_test::RequirePreflightRejectsNonScalar(-8460, morph_test::BinaryKernelParamSetter(1.0, 0.0, /*boundaryToForeground=*/false)); } + +TEST_CASE("NXImageProcessing::BinaryDilateImageFilter: Kernel Radius representability", "[NXImageProcessing][BinaryDilateImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::BinaryDilateImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][BinaryDilateImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({5, 5, 5}); +} diff --git a/src/Plugins/NXImageProcessing/test/BinaryErodeImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/BinaryErodeImageFilterTest.cpp index 2713a036e6..9e6909371f 100644 --- a/src/Plugins/NXImageProcessing/test/BinaryErodeImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/BinaryErodeImageFilterTest.cpp @@ -256,3 +256,13 @@ TEST_CASE("NXImageProcessing::BinaryErodeImageFilter: Preflight rejects non-scal { morph_test::RequirePreflightRejectsNonScalar(-8440, morph_test::BinaryKernelParamSetter(1.0, 0.0, /*boundaryToForeground=*/false)); } + +TEST_CASE("NXImageProcessing::BinaryErodeImageFilter: Kernel Radius representability", "[NXImageProcessing][BinaryErodeImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::BinaryErodeImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][BinaryErodeImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({0, 0, 0}); +} diff --git a/src/Plugins/NXImageProcessing/test/BinaryMorphologicalClosingImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/BinaryMorphologicalClosingImageFilterTest.cpp index 582c03f059..bcd480f01c 100644 --- a/src/Plugins/NXImageProcessing/test/BinaryMorphologicalClosingImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/BinaryMorphologicalClosingImageFilterTest.cpp @@ -242,3 +242,18 @@ TEST_CASE("NXImageProcessing::BinaryMorphologicalClosingImageFilter: Preflight r { morph_test::RequirePreflightRejectsNonScalar(-8490, ClosingKernelParamSetter(1.0, /*safeBorder=*/true)); } + +TEST_CASE("NXImageProcessing::BinaryMorphologicalClosingImageFilter: Kernel Radius representability", "[NXImageProcessing][BinaryMorphologicalClosingImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::BinaryMorphologicalClosingImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][BinaryMorphologicalClosingImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({5, 5, 5}); +} + +TEST_CASE("NXImageProcessing::BinaryMorphologicalClosingImageFilter: Kernel Radius layout preflight", "[NXImageProcessing][BinaryMorphologicalClosingImageFilter]") +{ + morph_test::RequireKernelRadiusLayoutPreflight(); +} diff --git a/src/Plugins/NXImageProcessing/test/BinaryMorphologicalOpeningImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/BinaryMorphologicalOpeningImageFilterTest.cpp index a42ce13746..b70b6aaf2c 100644 --- a/src/Plugins/NXImageProcessing/test/BinaryMorphologicalOpeningImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/BinaryMorphologicalOpeningImageFilterTest.cpp @@ -234,3 +234,13 @@ TEST_CASE("NXImageProcessing::BinaryMorphologicalOpeningImageFilter: Preflight r { morph_test::RequirePreflightRejectsNonScalar(-8480, OpeningKernelParamSetter(1.0, 0.0)); } + +TEST_CASE("NXImageProcessing::BinaryMorphologicalOpeningImageFilter: Kernel Radius representability", "[NXImageProcessing][BinaryMorphologicalOpeningImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::BinaryMorphologicalOpeningImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][BinaryMorphologicalOpeningImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({0, 0, 0}); +} diff --git a/src/Plugins/NXImageProcessing/test/BinaryOpeningByReconstructionImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/BinaryOpeningByReconstructionImageFilterTest.cpp index 1278ef66b5..5694810d82 100644 --- a/src/Plugins/NXImageProcessing/test/BinaryOpeningByReconstructionImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/BinaryOpeningByReconstructionImageFilterTest.cpp @@ -1,3 +1,5 @@ +#include "MorphologyFilterTestUtils.hpp" + #include "ReconstructionFilterTestUtils.hpp" #include "NXImageProcessing/Filters/BinaryOpeningByReconstructionImageFilter.hpp" @@ -347,3 +349,13 @@ TEST_CASE("NXImageProcessing::BinaryOpeningByReconstructionImageFilter: ITK real REQUIRE(executeResult.result.invalid()); // non-strictly-binary input (value 100) is rejected REQUIRE(executeResult.result.errors().front().code == -8002); // the documented binary-input contract error } + +TEST_CASE("NXImageProcessing::BinaryOpeningByReconstructionImageFilter: Kernel Radius representability", "[NXImageProcessing][BinaryOpeningByReconstructionImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::BinaryOpeningByReconstructionImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][BinaryOpeningByReconstructionImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({0, 0, 0}); +} diff --git a/src/Plugins/NXImageProcessing/test/BlackTopHatImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/BlackTopHatImageFilterTest.cpp index 136085bed1..56ce2a35a0 100644 --- a/src/Plugins/NXImageProcessing/test/BlackTopHatImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/BlackTopHatImageFilterTest.cpp @@ -168,3 +168,13 @@ TEST_CASE("NXImageProcessing::BlackTopHatImageFilter: Preflight rejects non-scal { morph_test::RequirePreflightRejectsNonScalar(-8420, morph_test::CompositeKernelParamSetter(/*safeBorder=*/true)); } + +TEST_CASE("NXImageProcessing::BlackTopHatImageFilter: Kernel Radius representability", "[NXImageProcessing][BlackTopHatImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::BlackTopHatImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][BlackTopHatImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({0, 5, 0}); +} diff --git a/src/Plugins/NXImageProcessing/test/ClosingByReconstructionImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/ClosingByReconstructionImageFilterTest.cpp index c14b828dd8..b10d851a73 100644 --- a/src/Plugins/NXImageProcessing/test/ClosingByReconstructionImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/ClosingByReconstructionImageFilterTest.cpp @@ -1,3 +1,5 @@ +#include "MorphologyFilterTestUtils.hpp" + #include "ReconstructionFilterTestUtils.hpp" #include "NXImageProcessing/Filters/ClosingByReconstructionImageFilter.hpp" @@ -151,3 +153,13 @@ TEST_CASE("NXImageProcessing::ClosingByReconstructionImageFilter: ITK real-image args.insertOrAssign(ClosingByReconstructionImageFilter::k_KernelRadius_Key, std::make_any>(std::vector{1, 1, 1})); }); } + +TEST_CASE("NXImageProcessing::ClosingByReconstructionImageFilter: Kernel Radius representability", "[NXImageProcessing][ClosingByReconstructionImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::ClosingByReconstructionImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][ClosingByReconstructionImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({5, 5, 5}); +} diff --git a/src/Plugins/NXImageProcessing/test/DilateObjectMorphologyImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/DilateObjectMorphologyImageFilterTest.cpp index 8590a427d2..499d757fef 100644 --- a/src/Plugins/NXImageProcessing/test/DilateObjectMorphologyImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/DilateObjectMorphologyImageFilterTest.cpp @@ -1,3 +1,5 @@ +#include "MorphologyFilterTestUtils.hpp" + #include "ObjectMorphologyFilterTestUtils.hpp" #include "NXImageProcessing/Filters/DilateObjectMorphologyImageFilter.hpp" @@ -385,3 +387,13 @@ TEST_CASE("NXImageProcessing::DilateObjectMorphologyImageFilter: Preflight rejec { omt::RequirePreflightRejectsNonScalar(-8520, omt::DilateParamSetter(1.0)); } + +TEST_CASE("NXImageProcessing::DilateObjectMorphologyImageFilter: Kernel Radius representability", "[NXImageProcessing][DilateObjectMorphologyImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::DilateObjectMorphologyImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][DilateObjectMorphologyImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({5, 5, 5}); +} diff --git a/src/Plugins/NXImageProcessing/test/ErodeObjectMorphologyImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/ErodeObjectMorphologyImageFilterTest.cpp index 5298437084..604bd5201a 100644 --- a/src/Plugins/NXImageProcessing/test/ErodeObjectMorphologyImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/ErodeObjectMorphologyImageFilterTest.cpp @@ -1,3 +1,5 @@ +#include "MorphologyFilterTestUtils.hpp" + #include "ObjectMorphologyFilterTestUtils.hpp" #include "NXImageProcessing/Filters/ErodeObjectMorphologyImageFilter.hpp" @@ -386,3 +388,13 @@ TEST_CASE("NXImageProcessing::ErodeObjectMorphologyImageFilter: Preflight reject { omt::RequirePreflightRejectsNonScalar(-8530, omt::ErodeParamSetter(1.0, 0.0)); } + +TEST_CASE("NXImageProcessing::ErodeObjectMorphologyImageFilter: Kernel Radius representability", "[NXImageProcessing][ErodeObjectMorphologyImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::ErodeObjectMorphologyImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][ErodeObjectMorphologyImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({0, 0, 0}); +} diff --git a/src/Plugins/NXImageProcessing/test/GrayscaleDilateImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/GrayscaleDilateImageFilterTest.cpp index 5aaf4e1e29..fcbaea70fe 100644 --- a/src/Plugins/NXImageProcessing/test/GrayscaleDilateImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/GrayscaleDilateImageFilterTest.cpp @@ -160,3 +160,13 @@ TEST_CASE("NXImageProcessing::GrayscaleDilateImageFilter: Preflight rejects non- { morph_test::RequirePreflightRejectsNonScalar(-8370, morph_test::DefaultKernelParamSetter()); } + +TEST_CASE("NXImageProcessing::GrayscaleDilateImageFilter: Kernel Radius representability", "[NXImageProcessing][GrayscaleDilateImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::GrayscaleDilateImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][GrayscaleDilateImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({5, 5, 5}); +} diff --git a/src/Plugins/NXImageProcessing/test/GrayscaleErodeImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/GrayscaleErodeImageFilterTest.cpp index 68ada0a027..8b800b5af8 100644 --- a/src/Plugins/NXImageProcessing/test/GrayscaleErodeImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/GrayscaleErodeImageFilterTest.cpp @@ -159,3 +159,13 @@ TEST_CASE("NXImageProcessing::GrayscaleErodeImageFilter: Preflight rejects non-s { morph_test::RequirePreflightRejectsNonScalar(-8360, morph_test::DefaultKernelParamSetter()); } + +TEST_CASE("NXImageProcessing::GrayscaleErodeImageFilter: Kernel Radius representability", "[NXImageProcessing][GrayscaleErodeImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::GrayscaleErodeImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][GrayscaleErodeImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({0, 0, 0}); +} diff --git a/src/Plugins/NXImageProcessing/test/GrayscaleMorphologicalClosingImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/GrayscaleMorphologicalClosingImageFilterTest.cpp index 1c74fb8d69..af93327125 100644 --- a/src/Plugins/NXImageProcessing/test/GrayscaleMorphologicalClosingImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/GrayscaleMorphologicalClosingImageFilterTest.cpp @@ -171,3 +171,18 @@ TEST_CASE("NXImageProcessing::GrayscaleMorphologicalClosingImageFilter: Prefligh morph_test::RequirePreflightRejectsNonScalar( -8400, morph_test::CompositeKernelParamSetter(/*safeBorder=*/true)); } + +TEST_CASE("NXImageProcessing::GrayscaleMorphologicalClosingImageFilter: Kernel Radius representability", "[NXImageProcessing][GrayscaleMorphologicalClosingImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::GrayscaleMorphologicalClosingImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][GrayscaleMorphologicalClosingImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({5, 5, 5}); +} + +TEST_CASE("NXImageProcessing::GrayscaleMorphologicalClosingImageFilter: Kernel Radius layout preflight", "[NXImageProcessing][GrayscaleMorphologicalClosingImageFilter]") +{ + morph_test::RequireKernelRadiusLayoutPreflight(); +} diff --git a/src/Plugins/NXImageProcessing/test/GrayscaleMorphologicalOpeningImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/GrayscaleMorphologicalOpeningImageFilterTest.cpp index 0cf3a0a009..d5a8f7d0fd 100644 --- a/src/Plugins/NXImageProcessing/test/GrayscaleMorphologicalOpeningImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/GrayscaleMorphologicalOpeningImageFilterTest.cpp @@ -186,3 +186,13 @@ TEST_CASE("NXImageProcessing::GrayscaleMorphologicalOpeningImageFilter: Prefligh morph_test::RequirePreflightRejectsNonScalar( -8390, morph_test::CompositeKernelParamSetter(/*safeBorder=*/true)); } + +TEST_CASE("NXImageProcessing::GrayscaleMorphologicalOpeningImageFilter: Kernel Radius representability", "[NXImageProcessing][GrayscaleMorphologicalOpeningImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::GrayscaleMorphologicalOpeningImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][GrayscaleMorphologicalOpeningImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({0, 0, 0}); +} diff --git a/src/Plugins/NXImageProcessing/test/MorphologicalGradientImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/MorphologicalGradientImageFilterTest.cpp index 5dd9b40067..bf678ac6d4 100644 --- a/src/Plugins/NXImageProcessing/test/MorphologicalGradientImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/MorphologicalGradientImageFilterTest.cpp @@ -202,3 +202,13 @@ TEST_CASE("NXImageProcessing::MorphologicalGradientImageFilter: Preflight reject { morph_test::RequirePreflightRejectsNonScalar(-8380, morph_test::DefaultKernelParamSetter()); } + +TEST_CASE("NXImageProcessing::MorphologicalGradientImageFilter: Kernel Radius representability", "[NXImageProcessing][MorphologicalGradientImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::MorphologicalGradientImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][MorphologicalGradientImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({5, 5, 5}); +} diff --git a/src/Plugins/NXImageProcessing/test/MorphologyEngineTest.cpp b/src/Plugins/NXImageProcessing/test/MorphologyEngineTest.cpp index 474b3f4763..7948cfd58e 100644 --- a/src/Plugins/NXImageProcessing/test/MorphologyEngineTest.cpp +++ b/src/Plugins/NXImageProcessing/test/MorphologyEngineTest.cpp @@ -1,3 +1,4 @@ +#include "MorphologyFilterTestUtils.hpp" #include "NXImageProcessing/Filters/BinaryDilateImageFilter.hpp" #include "NXImageProcessing/Filters/BinaryErodeImageFilter.hpp" @@ -2517,3 +2518,83 @@ TEST_CASE("NXImageProcessing::MorphologyEngine: fused SafeBorder crop-subtract u SIMPLNX_RESULT_REQUIRE_VALID(copyIntoBufferResult); REQUIRE(actual == expected); } + +TEST_CASE("NXImageProcessing::MorphologyEngine: Kernel Radius flat-fold representability", "[NXImageProcessing][MorphologyEngine]") +{ + using namespace ImageProcessing; + SECTION("Delta exceeds int64") + { + StructuringElement se; + se.radius = {0, 0, 1073741823}; + se.offsets = {{0, 0, -1073741823}, {0, 0, 1073741823}}; + const std::array radius = {0, 0, 1073741823}; + auto layout = ValidateMorphologyLayout({131072, 131072, 2}, radius, false, 1); + SIMPLNX_RESULT_REQUIRE_VALID(layout); + REQUIRE_FALSE(ImageProcessing::detail::ShouldUseMorphologyResidentFlatFold({131072, 131072, 2}, se)); + } + SECTION("Delta plus volume exceeds int64") + { + StructuringElement se; + se.radius = {0, 0, 4}; + se.offsets = {{0, 0, -4}, {0, 0, 4}}; + const std::array radius = {0, 0, 4}; + auto layout = ValidateMorphologyLayout({usize{1} << 30, usize{1} << 30, 4}, radius, false, 1); + SIMPLNX_RESULT_REQUIRE_VALID(layout); + REQUIRE_FALSE(ImageProcessing::detail::ShouldUseMorphologyResidentFlatFold({usize{1} << 30, usize{1} << 30, 4}, se)); + } +} + +TEST_CASE("NXImageProcessing::MorphologyEngine: Kernel Radius layout before allocation", "[NXImageProcessing][MorphologyEngine]") +{ + const std::atomic_bool cancel = false; + const IFilter::MessageHandler handler; + SECTION("Safe Border volume") + { + DataStructure ds; + const auto inputPath = morph_test::BuildKernelRadiusMetadata(ds, {3, 3, 1024}); + const auto geomPath = inputPath.getParent().getParent(); + const auto outputPath = inputPath.replaceName("Output"); + ImageProcessing::StructuringElement se; + se.radius = {100000000, 100000000, 0}; + // The invalid layout returns before resolving or allocating an output or scratch store. + auto grayscale = ImageProcessing::ExecuteMorphologyCompositeImageFilter(ds, geomPath, inputPath, outputPath, se, ImageProcessing::MorphCompositeOp::Closing, true, cancel, handler); + SIMPLNX_RESULT_REQUIRE_INVALID(grayscale); + REQUIRE(grayscale.errors().front().code == ImageProcessing::k_MorphologyVolumeError); + morph_test::RequireSingleGeometryContext(grayscale.errors().front().message, geomPath); + auto binary = ImageProcessing::ExecuteBinaryMorphologyCompositeImageFilter(ds, geomPath, inputPath, outputPath, se, ImageProcessing::BinaryCompositeOp::Closing, 5, 0, true, cancel, handler); + SIMPLNX_RESULT_REQUIRE_INVALID(binary); + REQUIRE(binary.errors().front().code == ImageProcessing::k_MorphologyVolumeError); + morph_test::RequireSingleGeometryContext(binary.errors().front().message, geomPath); + REQUIRE_FALSE(ds.containsData(outputPath)); + UnitTest::CheckArraysInheritTupleDims(ds); + } + SECTION("All seven execution helpers") + { + DataStructure ds; + const auto inputPath = morph_test::BuildKernelRadiusMetadata(ds, {static_cast(std::numeric_limits::max()) - 2, 1, 1}); + const auto geomPath = inputPath.getParent().getParent(); + const auto outputPath = inputPath.replaceName("Output"); + const auto se = ImageProcessing::MakeStructuringElement(ImageProcessing::KernelType::Box, {2, 0, 0}); + // These checks return before dispatch, so no algorithm-path witness or value store is needed. + std::vector> results; + results.push_back(ImageProcessing::ExecuteMorphologyImageFilter(ds, geomPath, inputPath, outputPath, se, ImageProcessing::MorphOp::Dilate, cancel, handler)); + results.push_back(ImageProcessing::ExecuteObjectMorphologyImageFilter(ds, geomPath, inputPath, outputPath, se, ImageProcessing::ObjectMorphOp::Dilate, 5, 0, cancel, handler)); + results.push_back(ImageProcessing::ExecuteBinaryMorphologyImageFilter(ds, geomPath, inputPath, outputPath, se, ImageProcessing::MorphOp::Dilate, 5, 0, false, cancel, handler)); + results.push_back(ImageProcessing::ExecuteMorphologyCompositeImageFilter(ds, geomPath, inputPath, outputPath, se, ImageProcessing::MorphCompositeOp::Closing, true, cancel, handler)); + results.push_back(ImageProcessing::ExecuteBinaryMorphologyCompositeImageFilter(ds, geomPath, inputPath, outputPath, se, ImageProcessing::BinaryCompositeOp::Closing, 5, 0, true, cancel, handler)); + results.push_back(ImageProcessing::ExecuteReconstructionOpenCloseImageFilter(ds, geomPath, inputPath, outputPath, se, ImageProcessing::MorphOp::Erode, false, false, cancel, handler)); + results.push_back(ImageProcessing::ExecuteBinaryOpeningByReconstructionImageFilter(ds, geomPath, inputPath, outputPath, se, 5, 0, false, cancel, handler)); + for(usize i = 0; i < results.size(); ++i) + { + DYNAMIC_SECTION("Execution helper " << i) + { + const auto& result = results[i]; + SIMPLNX_RESULT_REQUIRE_INVALID(result); + REQUIRE(result.errors().front().code == ImageProcessing::k_MorphologyCoordinateError); + morph_test::RequireSingleGeometryContext(result.errors().front().message, geomPath); + } + } + REQUIRE_FALSE(ds.containsData(outputPath)); + UnitTest::CheckArraysInheritTupleDims(ds); + } +} diff --git a/src/Plugins/NXImageProcessing/test/MorphologyFilterTestUtils.hpp b/src/Plugins/NXImageProcessing/test/MorphologyFilterTestUtils.hpp index b33ca0377b..cf9408e749 100644 --- a/src/Plugins/NXImageProcessing/test/MorphologyFilterTestUtils.hpp +++ b/src/Plugins/NXImageProcessing/test/MorphologyFilterTestUtils.hpp @@ -8,6 +8,7 @@ #include "simplnx/DataStructure/DataArray.hpp" #include "simplnx/DataStructure/DataPath.hpp" #include "simplnx/DataStructure/DataStructure.hpp" +#include "simplnx/DataStructure/EmptyDataStore.hpp" #include "simplnx/DataStructure/Geometry/ImageGeom.hpp" #include "simplnx/DataStructure/IDataArray.hpp" #include "simplnx/Filter/Arguments.hpp" @@ -744,3 +745,179 @@ inline void RunMorphologyMd5ItkGolden(const std::string& inputFile, const std::s UnitTest::CheckArraysInheritTupleDims(ds); } } // namespace morph_test + +namespace morph_test +{ +/** + * @brief Sets common morphology parameters on a scalar image for radius validation tests. + * @tparam FilterT Filter with kernel parameters. + * @param inputPath Scalar input array path. + * @param radius X, Y and Z radii in cells. + * @param safeBorder Enables padding when the filter supports it. + * @return Complete arguments with fixed foreground, background and object values where applicable. + */ +template +Arguments KernelRadiusTestArguments(const DataPath& inputPath, const std::vector& radius, bool safeBorder = false) +{ + Arguments args = FilterT().getDefaultArguments(); + args.insertOrAssign(FilterT::k_InputImageGeomPath_Key, std::make_any(inputPath.getParent().getParent())); + args.insertOrAssign(FilterT::k_InputImageDataPath_Key, std::make_any(inputPath)); + args.insertOrAssign(FilterT::k_OutputImageArrayName_Key, std::make_any("Output")); + args.insertOrAssign(FilterT::k_KernelType_Key, std::make_any(static_cast(KernelType::Box))); + args.insertOrAssign(FilterT::k_KernelRadius_Key, std::make_any>(radius)); + if constexpr(requires { FilterT::k_SafeBorder_Key; }) + { + args.insertOrAssign(FilterT::k_SafeBorder_Key, std::make_any(safeBorder)); + } + if constexpr(requires { FilterT::k_ForegroundValue_Key; }) + { + args.insertOrAssign(FilterT::k_ForegroundValue_Key, std::make_any(5)); + } + if constexpr(requires { FilterT::k_BackgroundValue_Key; }) + { + args.insertOrAssign(FilterT::k_BackgroundValue_Key, std::make_any(0)); + } + if constexpr(requires { FilterT::k_ObjectValue_Key; }) + { + args.insertOrAssign(FilterT::k_ObjectValue_Key, std::make_any(5)); + } + return args; +} + +/** + * @brief Checks the shared radius boundary without constructing a large kernel. + * @tparam FilterT Filter with kernel parameters. + */ +template +void RequireKernelRadiusPreflight() +{ + const auto application = Application::GetOrCreateInstance(); + REQUIRE(application != nullptr); + const UnitTest::PreferencesSentinel prefs(DataStorageMode::ForceInCore, 0); + DataStructure ds; + const DataPath inputPath = BuildMorphologyImage(ds, 3, 1, 1); + const std::array, 2> invalidRadii = {{{std::numeric_limits::max(), 0, 0}, {0, 2147483647u, 0}}}; + FilterT filter; + for(usize i = 0; i < invalidRadii.size(); ++i) + { + DYNAMIC_SECTION("Invalid radius axis " << i) + { + auto result = filter.preflight(ds, KernelRadiusTestArguments(inputPath, invalidRadii[i])); + SIMPLNX_RESULT_REQUIRE_INVALID(result.outputActions); + REQUIRE(result.outputActions.errors().front().code == ImageProcessing::k_KernelRadiusRangeError); + const auto& message = result.outputActions.errors().front().message; + REQUIRE(message.find(i == 0 ? "X" : "Y") != std::string::npos); + REQUIRE(message.find(std::to_string(invalidRadii[i][i])) != std::string::npos); + REQUIRE(message.find("2147483646") != std::string::npos); + auto executeResult = filter.execute(ds, KernelRadiusTestArguments(inputPath, invalidRadii[i])); + SIMPLNX_RESULT_REQUIRE_INVALID(executeResult.result); + REQUIRE(executeResult.result.errors().front().code == ImageProcessing::k_KernelRadiusRangeError); + REQUIRE_FALSE(ds.containsData(inputPath.replaceName("Output"))); + REQUIRE_NOTHROW(ds.getDataRefAs(inputPath)); + const auto& input = ds.getDataRefAs(inputPath); + for(usize x = 0; x < 3; ++x) + { + REQUIRE(input[x] == (x + ((x * 131) % 37)) % 200); + } + } + } + SECTION("Last representable Z radius") + { + auto result = filter.preflight(ds, KernelRadiusTestArguments(inputPath, {0, 0, 2147483646u})); + SIMPLNX_RESULT_REQUIRE_VALID(result.outputActions); + } + UnitTest::CheckArraysInheritTupleDims(ds); +} + +/** + * @brief Checks a hand-calculated one-dimensional morphology result for both algorithm paths. + * @tparam FilterT Filter with kernel parameters. + * @param expected Hand-calculated output for input values {5, 0, 5}. + */ +template +void RequireOrdinaryKernelRadius(const std::array& expected) +{ + const auto scenario = GENERATE(from_range(UnitTest::SelectAlgorithmTestScenariosForInMemoryStores())); + CAPTURE(scenario); + UnitTest::AlgorithmTestScope scope(scenario); + DataStructure ds; + const DataPath inputPath = BuildMorphologyImage(ds, 3, 1, 1); + REQUIRE_NOTHROW(ds.getDataRefAs(inputPath)); + auto& input = ds.getDataRefAs(inputPath); + const std::array values = {5, 0, 5}; + auto writeResult = input.getDataStoreRef().copyFromBuffer(0, nonstd::span(values)); + SIMPLNX_RESULT_REQUIRE_VALID(writeResult); + FilterT filter; + auto args = KernelRadiusTestArguments(inputPath, {1, 0, 0}); + auto result = scope.executeFilter(filter, ds, args); + SIMPLNX_RESULT_REQUIRE_VALID(result.result); + const auto outputPath = inputPath.replaceName("Output"); + REQUIRE_NOTHROW(ds.getDataRefAs(outputPath)); + const auto& output = ds.getDataRefAs(outputPath); + for(usize i = 0; i < expected.size(); ++i) + { + REQUIRE(output[i] == expected[i]); + } + UnitTest::CheckArraysInheritTupleDims(ds); +} +} // namespace morph_test + +namespace morph_test +{ +/** + * @brief Creates scalar input metadata without allocating image values. + * @param ds Receives the geometry, cell matrix and input placeholder. + * @param dims X, Y and Z image extents in cells. + * @return Input array path. + */ +inline DataPath BuildKernelRadiusMetadata(DataStructure& ds, const SizeVec3& dims) +{ + const ShapeType shape = {dims[2], dims[1], dims[0]}; + auto* geom = ImageGeom::Create(ds, "Image Geometry"); + geom->setDimensions(dims); + auto* cells = AttributeMatrix::Create(ds, "CellData", shape, geom->getId()); + geom->setCellData(*cells); + auto store = EmptyDataStore::Create(shape, {1}, ""); + SIMPLNX_RESULT_REQUIRE_VALID(store); + DataArray::Create(ds, "Input", std::move(store.value()), cells->getId()); + return DataPath({"Image Geometry", "CellData", "Input"}); +} + +/** + * @brief Requires exactly one quoted geometry-path suffix in a diagnostic. + * @param message Error message to inspect. + * @param geometryPath Selected Image Geometry path. + */ +inline void RequireSingleGeometryContext(const std::string& message, const DataPath& geometryPath) +{ + const auto context = "Image Geometry: '" + geometryPath.toString() + "'"; + const auto first = message.find(context); + REQUIRE(first != std::string::npos); + REQUIRE(message.find(context, first + context.size()) == std::string::npos); +} + +/** + * @brief Checks that preflight rejects an unrepresentable Safe Border volume. + * @tparam FilterT Filter with Safe Border support. + */ +template +void RequireKernelRadiusLayoutPreflight() +{ + DataStructure ds; + const auto inputPath = BuildKernelRadiusMetadata(ds, {3, 3, 1024}); + FilterT filter; + auto result = filter.preflight(ds, KernelRadiusTestArguments(inputPath, {100000000, 100000000, 0}, true)); + SIMPLNX_RESULT_REQUIRE_INVALID(result.outputActions); + REQUIRE(result.outputActions.errors().front().code == ImageProcessing::k_MorphologyVolumeError); + REQUIRE(result.outputActions.errors().front().message.find("volume") != std::string::npos); + const auto geometryPath = inputPath.getParent().getParent(); + RequireSingleGeometryContext(result.outputActions.errors().front().message, geometryPath); + // Public execute repeats preflight and must preserve one copy of the geometry context. + auto executeResult = filter.execute(ds, KernelRadiusTestArguments(inputPath, {100000000, 100000000, 0}, true)); + SIMPLNX_RESULT_REQUIRE_INVALID(executeResult.result); + REQUIRE(executeResult.result.errors().front().code == ImageProcessing::k_MorphologyVolumeError); + RequireSingleGeometryContext(executeResult.result.errors().front().message, geometryPath); + REQUIRE_FALSE(ds.containsData(inputPath.replaceName("Output"))); + UnitTest::CheckArraysInheritTupleDims(ds); +} +} // namespace morph_test diff --git a/src/Plugins/NXImageProcessing/test/OpeningByReconstructionImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/OpeningByReconstructionImageFilterTest.cpp index e86976fea5..55bee3f3a4 100644 --- a/src/Plugins/NXImageProcessing/test/OpeningByReconstructionImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/OpeningByReconstructionImageFilterTest.cpp @@ -1,3 +1,5 @@ +#include "MorphologyFilterTestUtils.hpp" + #include "ReconstructionFilterTestUtils.hpp" #include "NXImageProcessing/Filters/OpeningByReconstructionImageFilter.hpp" @@ -153,3 +155,13 @@ TEST_CASE("NXImageProcessing::OpeningByReconstructionImageFilter: ITK real-image args.insertOrAssign(OpeningByReconstructionImageFilter::k_KernelRadius_Key, std::make_any>(std::vector{1, 1, 1})); }); } + +TEST_CASE("NXImageProcessing::OpeningByReconstructionImageFilter: Kernel Radius representability", "[NXImageProcessing][OpeningByReconstructionImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::OpeningByReconstructionImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][OpeningByReconstructionImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({0, 0, 0}); +} diff --git a/src/Plugins/NXImageProcessing/test/WhiteTopHatImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/WhiteTopHatImageFilterTest.cpp index 097cdfd02f..a75464a830 100644 --- a/src/Plugins/NXImageProcessing/test/WhiteTopHatImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/WhiteTopHatImageFilterTest.cpp @@ -168,3 +168,13 @@ TEST_CASE("NXImageProcessing::WhiteTopHatImageFilter: Preflight rejects non-scal { morph_test::RequirePreflightRejectsNonScalar(-8410, morph_test::CompositeKernelParamSetter(/*safeBorder=*/true)); } + +TEST_CASE("NXImageProcessing::WhiteTopHatImageFilter: Kernel Radius representability", "[NXImageProcessing][WhiteTopHatImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("NXImageProcessing::WhiteTopHatImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][WhiteTopHatImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({5, 0, 5}); +} diff --git a/src/simplnx/Utilities/ImageProcessing/AdaptiveHistogramEqualizationEngine.hpp b/src/simplnx/Utilities/ImageProcessing/AdaptiveHistogramEqualizationEngine.hpp index cfbc9c4061..0c7994bcd1 100644 --- a/src/simplnx/Utilities/ImageProcessing/AdaptiveHistogramEqualizationEngine.hpp +++ b/src/simplnx/Utilities/ImageProcessing/AdaptiveHistogramEqualizationEngine.hpp @@ -104,31 +104,27 @@ struct AdaptiveHistogramEqualizationPlaneBody const float betaU = beta * u; const float betaHalf = beta * 0.5f; + // Intersect the radius window with the image bounds. Preserve increasing Z/Y/X accumulation order. + const int64 dzLo = std::max(-rzi, -zi); + const int64 dzHi = std::min(rzi, dimZi - 1 - zi); + const int64 dyLo = std::max(-ryi, -yi); + const int64 dyHi = std::min(ryi, dimYi - 1 - yi); + const int64 dxLo = std::max(-rxi, -xi); + const int64 dxHi = std::min(rxi, dimXi - 1 - xi); + float64 localSum = 0.0; usize inBounds = 0; - for(int64 dz = -rzi; dz <= rzi; ++dz) + for(int64 dz = dzLo; dz <= dzHi; ++dz) { const int64 nz = zi + dz; - if(nz < 0 || nz >= dimZi) - { - continue; // OOB neighbor ignored (over-weight the valid part; see struct docs) - } const usize slabZBase = (static_cast(nz) - zLo) * sliceValues; // nz in [zLo, zHi] once in-bounds - for(int64 dy = -ryi; dy <= ryi; ++dy) + for(int64 dy = dyLo; dy <= dyHi; ++dy) { const int64 ny = yi + dy; - if(ny < 0 || ny >= dimYi) - { - continue; - } const usize rowBase = slabZBase + static_cast(ny) * dimX; - for(int64 dx = -rxi; dx <= rxi; ++dx) + for(int64 dx = dxLo; dx <= dxHi; ++dx) { const int64 nx = xi + dx; - if(nx < 0 || nx >= dimXi) - { - continue; - } const float v = static_cast((static_cast(slab[rowBase + static_cast(nx)]) - minValue) / iscale - 0.5); const float sF = static_cast(AdaptiveEqualizationSgn(u - v)); const float ad = static_cast(std::fabs(2.0 * static_cast(u - v))); @@ -146,7 +142,7 @@ struct AdaptiveHistogramEqualizationPlaneBody /** * @brief Integer bounded-range fast path for @ref AdaptiveHistogramEqualizationPlaneBody. This body is a - * near-duplicate of that one: the slab indexing, out-of-bounds skip, in-bounds count, deliberate + * near-duplicate of that one: the slab indexing, clipped neighbor bounds, in-bounds count, deliberate * center double-count, and the final rescale are kept BYTE-IDENTICAL and the two MUST stay in sync * (any change to the boundary rule in one has to be mirrored in the other). The ONLY difference is the * inner cumulative-function term: instead of recomputing @c std::pow per neighbor, the neighbor term @@ -205,31 +201,27 @@ struct AdaptiveHistogramEqualizationLutPlaneBody // neighbor contribution below, exactly as the sibling body's per-voxel betaU. const float betaU = beta * u; + // Intersect the radius window with the image bounds. Preserve increasing Z/Y/X accumulation order. + const int64 dzLo = std::max(-rzi, -zi); + const int64 dzHi = std::min(rzi, dimZi - 1 - zi); + const int64 dyLo = std::max(-ryi, -yi); + const int64 dyHi = std::min(ryi, dimYi - 1 - yi); + const int64 dxLo = std::max(-rxi, -xi); + const int64 dxHi = std::min(rxi, dimXi - 1 - xi); + float64 localSum = 0.0; usize inBounds = 0; - for(int64 dz = -rzi; dz <= rzi; ++dz) + for(int64 dz = dzLo; dz <= dzHi; ++dz) { const int64 nz = zi + dz; - if(nz < 0 || nz >= dimZi) - { - continue; // OOB neighbor ignored (over-weight the valid part; see struct docs) - } const usize slabZBase = (static_cast(nz) - zLo) * sliceValues; // nz in [zLo, zHi] once in-bounds - for(int64 dy = -ryi; dy <= ryi; ++dy) + for(int64 dy = dyLo; dy <= dyHi; ++dy) { const int64 ny = yi + dy; - if(ny < 0 || ny >= dimYi) - { - continue; - } const usize rowBase = slabZBase + static_cast(ny) * dimX; - for(int64 dx = -rxi; dx <= rxi; ++dx) + for(int64 dx = dxLo; dx <= dxHi; ++dx) { const int64 nx = xi + dx; - if(nx < 0 || nx >= dimXi) - { - continue; - } // Promote to int64 BEFORE subtracting: for unsigned T a T - T subtraction would underflow. The // gate in ApplyAdaptiveHistogramEqualization guarantees this difference does not overflow int64. const int64 d = static_cast(centerValue) - static_cast(slab[rowBase + static_cast(nx)]); @@ -709,27 +701,25 @@ struct AdaptiveHistogramEqualization2DBlockBody const usize localY = tuple / outputWidth; const usize x = outputXBegin + localX; const usize y = outputYBegin + localY; + const int64 signedX = static_cast(x); + const int64 signedY = static_cast(y); + const int64 dyLo = std::max(-radiusYi, -signedY); + const int64 dyHi = std::min(radiusYi, dimYi - 1 - signedY); + const int64 dxLo = std::max(-radiusXi, -signedX); + const int64 dxHi = std::min(radiusXi, dimXi - 1 - signedX); const T centerValue = input[(y - inputYBegin) * inputWidth + x - inputXBegin]; const float u = static_cast((static_cast(centerValue) - minValue) / iscale - 0.5); const float betaU = beta * u; const float betaHalf = beta * 0.5f; float64 localSum = 0.0; usize inBounds = 0; - for(int64 dy = -radiusYi; dy <= radiusYi; ++dy) + for(int64 dy = dyLo; dy <= dyHi; ++dy) { const int64 neighborY = static_cast(y) + dy; - if(neighborY < 0 || neighborY >= dimYi) - { - continue; - } const usize inputRow = (static_cast(neighborY) - inputYBegin) * inputWidth; - for(int64 dx = -radiusXi; dx <= radiusXi; ++dx) + for(int64 dx = dxLo; dx <= dxHi; ++dx) { const int64 neighborX = static_cast(x) + dx; - if(neighborX < 0 || neighborX >= dimXi) - { - continue; - } const float v = static_cast((static_cast(input[inputRow + static_cast(neighborX) - inputXBegin]) - minValue) / iscale - 0.5); const float sign = static_cast(AdaptiveEqualizationSgn(u - v)); const float absoluteDifference = static_cast(std::fabs(2.0 * static_cast(u - v))); @@ -783,26 +773,24 @@ struct AdaptiveHistogramEqualizationLut2DBlockBody const usize localY = tuple / outputWidth; const usize x = outputXBegin + localX; const usize y = outputYBegin + localY; + const int64 signedX = static_cast(x); + const int64 signedY = static_cast(y); + const int64 dyLo = std::max(-radiusYi, -signedY); + const int64 dyHi = std::min(radiusYi, dimYi - 1 - signedY); + const int64 dxLo = std::max(-radiusXi, -signedX); + const int64 dxHi = std::min(radiusXi, dimXi - 1 - signedX); const T centerValue = input[(y - inputYBegin) * inputWidth + x - inputXBegin]; const float u = static_cast((static_cast(centerValue) - minValue) / iscale - 0.5); const float betaU = beta * u; float64 localSum = 0.0; usize inBounds = 0; - for(int64 dy = -radiusYi; dy <= radiusYi; ++dy) + for(int64 dy = dyLo; dy <= dyHi; ++dy) { const int64 neighborY = static_cast(y) + dy; - if(neighborY < 0 || neighborY >= dimYi) - { - continue; - } const usize inputRow = (static_cast(neighborY) - inputYBegin) * inputWidth; - for(int64 dx = -radiusXi; dx <= radiusXi; ++dx) + for(int64 dx = dxLo; dx <= dxHi; ++dx) { const int64 neighborX = static_cast(x) + dx; - if(neighborX < 0 || neighborX >= dimXi) - { - continue; - } const int64 difference = static_cast(centerValue) - static_cast(input[inputRow + static_cast(neighborX) - inputXBegin]); const usize lookupIndex = static_cast(difference - differenceMinimum); assert(lookupIndex < lookupTableSize); diff --git a/src/simplnx/Utilities/ImageProcessing/ImageProcessingFilterUtilities.hpp b/src/simplnx/Utilities/ImageProcessing/ImageProcessingFilterUtilities.hpp index 05fb2d3c8a..e596b40593 100644 --- a/src/simplnx/Utilities/ImageProcessing/ImageProcessingFilterUtilities.hpp +++ b/src/simplnx/Utilities/ImageProcessing/ImageProcessingFilterUtilities.hpp @@ -69,6 +69,25 @@ namespace nx::core::ImageProcessing { +/** + * @brief Adds the selected geometry path to layout errors at a filter boundary. + * @param result Layout validation result. Error codes and warnings remain unchanged. + * @param imageGeomPath Selected Image Geometry path. + * @return Result with quoted geometry context on each error, or the unchanged valid result. + */ +inline Result<> AddMorphologyLayoutGeometryContext(Result<> result, const DataPath& imageGeomPath) +{ + if(result.invalid()) + { + const auto context = fmt::format(" Image Geometry: '{}'.", imageGeomPath.toString()); + for(auto& error : result.errors()) + { + error.message += context; + } + } + return result; +} + // Element-type dispatch policies. Each reuses a core ExecuteDataFunction* helper + its matching // allowed-DataType set — no duplicated type switch. struct AllNumeric @@ -4834,6 +4853,11 @@ Result<> ExecuteMorphologyImageFilter(DataStructure& dataStructure, const DataPa const DataType inputType = inputArray.getDataType(); const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); const SizeVec3 dims = imageGeom.getDimensions(); + if(auto layout = ValidateMorphologyLayout(dims, se, false, GetDataTypeSize(inputType)); layout.invalid()) + { + return AddMorphologyLayoutGeometryContext(std::move(layout), imageGeomPath); + } + detail::MorphologyExecuteFn executeFn{dataStructure, inputArrayPath, outputArrayPath, dims, se, op, shouldCancel, messageHandler}; return TypeSetPolicy::dispatch(inputType, executeFn); } @@ -4862,6 +4886,11 @@ Result<> ExecuteObjectMorphologyImageFilter(DataStructure& dataStructure, const const DataType inputType = inputArray.getDataType(); const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); const SizeVec3 dims = imageGeom.getDimensions(); + if(auto layout = ValidateMorphologyLayout(dims, se, false, GetDataTypeSize(inputType)); layout.invalid()) + { + return AddMorphologyLayoutGeometryContext(std::move(layout), imageGeomPath); + } + const std::vector boxOffsets = detail::MakeFullBoxNeighborOffsets(); detail::ObjectMorphologyExecuteFn executeFn{dataStructure, inputArrayPath, outputArrayPath, dims, se, boxOffsets, op, objectValue, backgroundValue, shouldCancel, messageHandler}; return TypeSetPolicy::dispatch(inputType, executeFn); @@ -4925,6 +4954,11 @@ Result<> ExecuteBinaryMorphologyImageFilter(DataStructure& dataStructure, const const DataType inputType = inputArray.getDataType(); const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); const SizeVec3 dims = imageGeom.getDimensions(); + if(auto layout = ValidateMorphologyLayout(dims, se, false, GetDataTypeSize(inputType)); layout.invalid()) + { + return AddMorphologyLayoutGeometryContext(std::move(layout), imageGeomPath); + } + detail::BinaryMorphologyExecuteFn executeFn{dataStructure, inputArrayPath, outputArrayPath, dims, se, op, foreground, background, boundaryToForeground, shouldCancel, messageHandler}; return TypeSetPolicy::dispatch(inputType, executeFn); } @@ -4950,6 +4984,11 @@ Result<> ExecuteMorphologyCompositeImageFilter(DataStructure& dataStructure, con const DataType inputType = inputArray.getDataType(); const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); const SizeVec3 dims = imageGeom.getDimensions(); + if(auto layout = ValidateMorphologyLayout(dims, se, safeBorder && op != MorphCompositeOp::Gradient, GetDataTypeSize(inputType)); layout.invalid()) + { + return AddMorphologyLayoutGeometryContext(std::move(layout), imageGeomPath); + } + detail::MorphologyCompositeExecuteFn executeFn{dataStructure, inputArrayPath, outputArrayPath, dims, se, op, safeBorder, shouldCancel, messageHandler}; return TypeSetPolicy::dispatch(inputType, executeFn); } @@ -4983,6 +5022,11 @@ Result<> ExecuteBinaryMorphologyCompositeImageFilter(DataStructure& dataStructur const DataType inputType = inputArray.getDataType(); const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); const SizeVec3 dims = imageGeom.getDimensions(); + if(auto layout = ValidateMorphologyLayout(dims, se, safeBorder && op == BinaryCompositeOp::Closing, GetDataTypeSize(inputType)); layout.invalid()) + { + return AddMorphologyLayoutGeometryContext(std::move(layout), imageGeomPath); + } + detail::BinaryMorphologyCompositeExecuteFn executeFn{dataStructure, inputArrayPath, outputArrayPath, dims, se, op, foreground, background, safeBorder, shouldCancel, messageHandler}; return TypeSetPolicy::dispatch(inputType, executeFn); } @@ -5073,6 +5117,11 @@ Result<> ExecuteReconstructionOpenCloseImageFilter(DataStructure& dataStructure, const DataType inputType = inputArray.getDataType(); const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); const SizeVec3 dims = imageGeom.getDimensions(); + if(auto layout = ValidateMorphologyLayout(dims, se, false, GetDataTypeSize(inputType)); layout.invalid()) + { + return AddMorphologyLayoutGeometryContext(std::move(layout), imageGeomPath); + } + detail::ReconstructionOpenCloseExecuteFn executeFn{dataStructure, inputArrayPath, outputArrayPath, dims, se, firstOp, fullyConnected, preserveIntensities, shouldCancel, messageHandler}; return TypeSetPolicy::dispatch(inputType, executeFn); } @@ -5092,6 +5141,11 @@ Result<> ExecuteBinaryOpeningByReconstructionImageFilter(DataStructure& dataStru const DataType inputType = inputArray.getDataType(); const auto& imageGeom = dataStructure.getDataRefAs(imageGeomPath); const SizeVec3 dims = imageGeom.getDimensions(); + if(auto layout = ValidateMorphologyLayout(dims, se, false, GetDataTypeSize(inputType)); layout.invalid()) + { + return AddMorphologyLayoutGeometryContext(std::move(layout), imageGeomPath); + } + detail::BinaryReconstructionOpeningExecuteFn executeFn{dataStructure, inputArrayPath, outputArrayPath, dims, se, foreground, background, fullyConnected, shouldCancel, messageHandler}; return TypeSetPolicy::dispatch(inputType, executeFn); } diff --git a/src/simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp b/src/simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp index 6477f93bca..74ac05fe56 100644 --- a/src/simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp +++ b/src/simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp @@ -57,6 +57,91 @@ enum class MorphOp Erode }; +inline constexpr int32 k_MorphologyPaddedExtentError = -88005; +inline constexpr int32 k_MorphologyCoordinateError = -88006; +inline constexpr int32 k_MorphologyPlaneError = -88007; +inline constexpr int32 k_MorphologyVolumeError = -88008; +inline constexpr int32 k_MorphologyByteCountError = -88009; + +/** + * @brief Checks image and Safe Border layout arithmetic without allocating image values. + * @param dims Original X, Y and Z image extents in cells. + * @param radius X, Y and Z kernel radii in cells. + * @param safeBorder Includes radius padding, except on Z for a single-plane image. + * @param elementBytes Size of one scalar image value in bytes. + * @pre radius has exactly three components and satisfies ValidateKernelRadius(). + * @return Layout error if counts, coordinates or typed byte counts are unrepresentable. + * @note Flat-offset optimization limits do not restrict this layout contract. + */ +inline Result<> ValidateMorphologyLayout(const SizeVec3& dims, nonstd::span radius, bool safeBorder, usize elementBytes) +{ + SizeVec3 paddedDims = dims; + constexpr std::array axes = {"X", "Y", "Z"}; + for(usize axis = 0; axis < 3; ++axis) + { + const usize pad = safeBorder && (axis != 2 || dims[2] != 1) ? static_cast(radius[axis]) : 0; + if(pad > (std::numeric_limits::max() - dims[axis]) / 2) + { + return MakeErrorResult(k_MorphologyPaddedExtentError, + fmt::format("Morphology dimensions ({}) and Kernel Radius (X={}, Y={}, Z={}) overflow padded extent dims[{}]+2*pad. Reduce the dimensions or radii.", + StringUtilities::formatDimensions3D(dims), radius[0], radius[1], radius[2], axes.at(axis))); + } + paddedDims[axis] += 2 * pad; + } + constexpr uint64 signedMax = static_cast(std::numeric_limits::max()); + for(usize axis = 0; axis < 3; ++axis) + { + // Padded extents are at least the original extents, so this also bounds original coordinates. + if(paddedDims[axis] > signedMax - static_cast(radius[axis]) - 1) + { + return MakeErrorResult(k_MorphologyCoordinateError, + fmt::format("Morphology dimensions ({}) and Kernel Radius (X={}, Y={}, Z={}) exceed the signed coordinate limit: padded extent {} + radius {} + 1 on axis {} must be at " + "most {}. Reduce the dimensions or radii.", + StringUtilities::formatDimensions3D(dims), radius[0], radius[1], radius[2], paddedDims[axis], radius[axis], axes.at(axis), signedMax)); + } + } + if(paddedDims[0] != 0 && paddedDims[1] > signedMax / paddedDims[0]) + { + return MakeErrorResult( + k_MorphologyPlaneError, + fmt::format("Morphology dimensions ({}) and Kernel Radius (X={}, Y={}, Z={}) exceed the signed plane count limit: padded X*Y = {}*{} must be at most {}. Reduce the dimensions or radii.", + StringUtilities::formatDimensions3D(dims), radius[0], radius[1], radius[2], paddedDims[0], paddedDims[1], signedMax)); + } + const uint64 plane = static_cast(paddedDims[0]) * paddedDims[1]; + if(plane != 0 && paddedDims[2] > signedMax / plane) + { + return MakeErrorResult( + k_MorphologyVolumeError, + fmt::format("Morphology dimensions ({}) and Kernel Radius (X={}, Y={}, Z={}) exceed the signed volume count limit: padded X*Y*Z = {}*{}*{} must be at most {}. Reduce the dimensions or radii.", + StringUtilities::formatDimensions3D(dims), radius[0], radius[1], radius[2], paddedDims[0], paddedDims[1], paddedDims[2], signedMax)); + } + const uint64 volume = plane * paddedDims[2]; + if(elementBytes != 0 && volume > std::numeric_limits::max() / elementBytes) + { + return MakeErrorResult( + k_MorphologyByteCountError, + fmt::format("Morphology dimensions ({}) and Kernel Radius (X={}, Y={}, Z={}) overflow the typed byte count: padded volume {} * element bytes {}. Reduce the dimensions or radii.", + StringUtilities::formatDimensions3D(dims), radius[0], radius[1], radius[2], volume, elementBytes)); + } + return {}; +} + +/** + * @brief Checks the layout of a rasterized kernel before an engine allocates scratch. + * @param dims Original image extents in cells. + * @param kernel Rasterized kernel. Negative legacy radii describe an empty range. + * @param safeBorder Includes the effective Safe Border padding. + * @param elementBytes Size of one scalar value in bytes. + * @pre Kernel radii satisfy ValidateKernelRadius() after negative legacy radii are clamped to zero. + * @return Layout error. + */ +inline Result<> ValidateMorphologyLayout(const SizeVec3& dims, const StructuringElement& kernel, bool safeBorder, usize elementBytes) +{ + const std::array radius = {static_cast(std::max(0, kernel.radius[0])), static_cast(std::max(0, kernel.radius[1])), + static_cast(std::max(0, kernel.radius[2]))}; + return ValidateMorphologyLayout(dims, radius, safeBorder, elementBytes); +} + namespace detail { enum class MorphologyCompositeOutputMode @@ -116,11 +201,58 @@ constexpr T MorphologyGradientDifference(T maximum, T minimum) noexcept } } +/** + * @brief Checks signed flat-delta and staged-index arithmetic for an optional flat fold. + * @param dims Complete image or padded bounds. + * @param kernel Rasterized offsets. + * @return True if every computed delta and its sum with a volume-sized base fit int64. + */ +inline bool MorphologyFlatFoldIsRepresentable(const SizeVec3& dims, const StructuringElement& kernel) +{ + constexpr uint64 signedMax = static_cast(std::numeric_limits::max()); + if(dims[0] > signedMax || dims[1] > signedMax || dims[2] > signedMax || (dims[0] != 0 && dims[1] > signedMax / dims[0])) + { + return false; + } + const uint64 slice = static_cast(dims[0]) * dims[1]; + if(slice != 0 && dims[2] > signedMax / slice) + { + return false; + } + const uint64 volume = slice * dims[2]; + for(const SEOffset& offset : kernel.offsets) + { + const std::array values = {offset.dx, offset.dy, offset.dz}; + const std::array strides = {1, dims[0], slice}; + int64 delta = 0; + for(usize step = 0; step < 3; ++step) + { + const usize axis = 2 - step; + const uint64 magnitude = static_cast(values.at(axis) < 0 ? -values.at(axis) : values.at(axis)); + if(magnitude != 0 && strides.at(axis) > signedMax / magnitude) + { + return false; + } + const int64 product = values.at(axis) < 0 ? -static_cast(magnitude * strides.at(axis)) : static_cast(magnitude * strides.at(axis)); + if((product > 0 && delta > std::numeric_limits::max() - product) || (product < 0 && delta < std::numeric_limits::min() - product)) + { + return false; + } + delta += product; + } + const uint64 magnitude = delta < 0 ? static_cast(-(delta + 1)) + 1 : static_cast(delta); + if(magnitude > signedMax - volume) + { + return false; + } + } + return true; +} + inline bool ShouldUseMorphologyResidentFlatFold(const SizeVec3& dims, const StructuringElement& se) { - // The flat fold is faster for moderate neighborhoods, but its work grows with the full offset count. - // Keep larger kernels on the moving-histogram path, whose work grows with the entering/leaving boundary. - return dims[2] > 1 && !se.offsets.empty() && se.offsets.size() <= k_MaxMorphologyResidentFlatFoldOffsets; + // Larger kernels use the moving histogram, whose work scales with the entering and leaving boundary. + return dims[2] > 1 && !se.offsets.empty() && se.offsets.size() <= k_MaxMorphologyResidentFlatFoldOffsets && MorphologyFlatFoldIsRepresentable(dims, se); } inline std::array MorphologySafeBorderPadRadius(const StructuringElement& se, const SizeVec3& dims) @@ -1255,9 +1387,18 @@ struct MorphologyFlatFoldOffset int64 flatDelta = 0; }; -inline std::vector MakeMorphologyFlatFoldOffsets(const StructuringElement& se, usize dimX, usize dimY) +/** + * @brief Flattens offsets for a representable optional morphology fold. + * @param se Rasterized kernel offsets. + * @param dims Complete image or padded bounds. + * @pre MorphologyFlatFoldIsRepresentable(dims, se) is true. + * @return Offsets with signed flat deltas for these bounds. + */ +inline std::vector MakeMorphologyFlatFoldOffsets(const StructuringElement& se, const SizeVec3& dims) { - const int64 sliceValues = static_cast(dimX * dimY); + assert(MorphologyFlatFoldIsRepresentable(dims, se)); + const int64 dimX = static_cast(dims[0]); + const int64 sliceValues = static_cast(dims[0]) * static_cast(dims[1]); std::vector flatOffsets; flatOffsets.reserve(se.offsets.size()); for(const SEOffset& offset : se.offsets) @@ -1420,7 +1561,7 @@ template void RunMorphologyFlatFoldBlock(const T* stagedInput, T* output, const SizeVec3& boundDims, usize stagedZLo, const SizeVec3& outputDims, const SizeVec3& outputOrigin, const StructuringElement& se, const std::atomic_bool& shouldCancel) { - const std::vector offsets = MakeMorphologyFlatFoldOffsets(se, boundDims[0], boundDims[1]); + const std::vector offsets = MakeMorphologyFlatFoldOffsets(se, boundDims); RunMorphologyFlatFoldBlock(stagedInput, output, boundDims, stagedZLo, outputDims, outputOrigin, se, offsets, shouldCancel); } @@ -1574,7 +1715,7 @@ template void RunMorphologyGradientFlatFoldBlock(const T* stagedInput, T* output, const SizeVec3& boundDims, usize stagedZLo, const SizeVec3& outputDims, const SizeVec3& outputOrigin, const StructuringElement& se, const std::atomic_bool& shouldCancel) { - const std::vector offsets = MakeMorphologyFlatFoldOffsets(se, boundDims[0], boundDims[1]); + const std::vector offsets = MakeMorphologyFlatFoldOffsets(se, boundDims); RunMorphologyGradientFlatFoldBlock(stagedInput, output, boundDims, stagedZLo, outputDims, outputOrigin, se, offsets, shouldCancel); } @@ -1707,7 +1848,7 @@ template void RunBinaryMorphologyFlatFoldBlock(const T* stagedInput, T* output, const SizeVec3& boundDims, usize stagedZLo, const SizeVec3& outputDims, const SizeVec3& outputOrigin, const StructuringElement& se, T foreground, T background, bool boundaryToForeground, const std::atomic_bool& shouldCancel) { - const std::vector offsets = MakeMorphologyFlatFoldOffsets(se, boundDims[0], boundDims[1]); + const std::vector offsets = MakeMorphologyFlatFoldOffsets(se, boundDims); RunBinaryMorphologyFlatFoldBlock(stagedInput, output, boundDims, stagedZLo, outputDims, outputOrigin, se, foreground, background, boundaryToForeground, offsets, shouldCancel); } @@ -1900,6 +2041,18 @@ bool PackBinaryMorphologyStagedPlanes(const T* stagedInput, BinaryMorphWord* pac return !shouldCancel; } +/** + * @brief Clamps a packed word endpoint to the row without overflowing signed coordinates. + * @param xStart First bit coordinate, which can lie outside the row. + * @param rowEnd Exclusive end of the row. + * @return The smaller of xStart+64 and rowEnd. + */ +inline int64 MorphologyPackedWordEnd(int64 xStart, int64 rowEnd) +{ + constexpr int64 wordBits = std::numeric_limits::digits; + return xStart > std::numeric_limits::max() - wordBits ? rowEnd : std::min(rowEnd, xStart + wordBits); +} + /** * @brief Extracts 64 membership bits from one logical packed X/Y/Z row. * @@ -1961,7 +2114,7 @@ inline BinaryMorphWord ExtractPackedBinaryWord(const PackedBinaryPlanesView& vie return boundaryWord; } - const int64 xEnd = xStart + static_cast(k_WordBits); + const int64 xEnd = MorphologyPackedWordEnd(xStart, static_cast(boundDims[0])); const int64 inBoundsBegin = std::max(0, xStart); const int64 inBoundsEnd = std::min(static_cast(boundDims[0]), xEnd); if(inBoundsBegin >= inBoundsEnd) @@ -3117,6 +3270,11 @@ class MorphScanline Result<> operator()() { + if(auto layout = ValidateMorphologyLayout(m_Dims, m_SE, false, sizeof(T)); layout.invalid()) + { + return layout; + } + const usize dimX = m_Dims[0]; const usize dimY = m_Dims[1]; const usize dimZ = m_Dims[2]; @@ -3198,7 +3356,7 @@ class MorphScanline // The flat fold uses only its precomputed offsets. The moving-window fallback needs axis sets. const bool useFlatFold = detail::k_UseVectorHistogram && detail::ShouldUseMorphologyResidentFlatFold(m_Dims, m_SE); - const std::vector flatOffsets = useFlatFold ? detail::MakeMorphologyFlatFoldOffsets(m_SE, dimX, dimY) : std::vector{}; + const std::vector flatOffsets = useFlatFold ? detail::MakeMorphologyFlatFoldOffsets(m_SE, m_Dims) : std::vector{}; std::optional axisSets; if(!useFlatFold) { @@ -3357,6 +3515,11 @@ class MorphDirect Result<> operator()() { + if(auto layout = ValidateMorphologyLayout(m_Dims, m_SE, false, sizeof(T)); layout.invalid()) + { + return layout; + } + // Dispatch the runtime op to a compile-time bool so the histogram's comparator/extremum are fixed at // compile time (matching ITK's distinct Dilate/Erode filter classes). return (m_Op == MorphOp::Dilate) ? runImpl() : runImpl(); @@ -3647,6 +3810,11 @@ class MorphWorkingMemory Result<> operator()() { + if(auto layout = ValidateMorphologyLayout(m_Dims, m_SE, false, sizeof(T)); layout.invalid()) + { + return layout; + } + auto allocationResult = detail::ReserveMorphologyResidentWorkingMemory(m_Dims); if(allocationResult.invalid()) { @@ -3712,6 +3880,11 @@ template Result<> ApplyMorphology(const AbstractDataStore& in, AbstractDataStore& out, const SizeVec3& dims, const StructuringElement& se, MorphOp op, const IDataArray& inArray, const IDataArray& outArray, const std::atomic_bool& shouldCancel, const IFilter::MessageHandler& messageHandler) { + if(auto layout = ValidateMorphologyLayout(dims, se, false, sizeof(T)); layout.invalid()) + { + return layout; + } + return DispatchAlgorithm, MorphWorkingMemory>({&inArray, &outArray}, in, out, dims, se, op, shouldCancel, messageHandler); } @@ -3760,6 +3933,11 @@ template Result<> ApplyMorphologyCompositePipeline(const AbstractDataStore& input, AbstractDataStore& output, const SizeVec3& dims, const StructuringElement& se, MorphOp firstOp, MorphOp secondOp, bool safeBorder, detail::MorphologyCompositeOutputMode outputMode, const std::atomic_bool& shouldCancel, usize grantedWorkingMemoryBytes) { + if(auto layout = ValidateMorphologyLayout(dims, se, safeBorder, sizeof(T)); layout.invalid()) + { + return layout; + } + if(shouldCancel) { return {}; @@ -3853,8 +4031,7 @@ Result<> ApplyMorphologyCompositePipeline(const AbstractDataStore& input, Abs const bool secondDilate = secondOp == MorphOp::Dilate; // The flat fold uses only its precomputed offsets. The moving-window fallback needs axis sets. const bool useFlatFold = detail::k_UseVectorHistogram && detail::ShouldUseMorphologyResidentFlatFold(paddedDims, se); - const std::vector flatOffsets = - useFlatFold ? detail::MakeMorphologyFlatFoldOffsets(se, paddedDims[0], paddedDims[1]) : std::vector{}; + const std::vector flatOffsets = useFlatFold ? detail::MakeMorphologyFlatFoldOffsets(se, paddedDims) : std::vector{}; std::optional axisSets; if(!useFlatFold) { @@ -4189,6 +4366,11 @@ class MorphGradientScanline Result<> operator()() { + if(auto layout = ValidateMorphologyLayout(m_Dims, m_SE, false, sizeof(T)); layout.invalid()) + { + return layout; + } + const usize dimX = m_Dims[0]; const usize dimY = m_Dims[1]; const usize dimZ = m_Dims[2]; @@ -4288,7 +4470,7 @@ class MorphGradientScanline // The flat fold uses only its precomputed offsets. The moving-window fallback needs axis sets. const bool useFlatFold = detail::k_UseVectorHistogram && detail::ShouldUseMorphologyResidentFlatFold(m_Dims, m_SE); - const std::vector flatOffsets = useFlatFold ? detail::MakeMorphologyFlatFoldOffsets(m_SE, dimX, dimY) : std::vector{}; + const std::vector flatOffsets = useFlatFold ? detail::MakeMorphologyFlatFoldOffsets(m_SE, m_Dims) : std::vector{}; std::optional axisSets; if(!useFlatFold) { @@ -4422,6 +4604,11 @@ class MorphGradientDirect Result<> operator()() { + if(auto layout = ValidateMorphologyLayout(m_Dims, m_SE, false, sizeof(T)); layout.invalid()) + { + return layout; + } + const usize dimX = m_Dims[0]; const usize dimY = m_Dims[1]; const usize dimZ = m_Dims[2]; @@ -4690,6 +4877,11 @@ class MorphGradientWorkingMemory Result<> operator()() { + if(auto layout = ValidateMorphologyLayout(m_Dims, m_SE, false, sizeof(T)); layout.invalid()) + { + return layout; + } + auto allocationResult = detail::ReserveMorphologyResidentWorkingMemory(m_Dims); if(allocationResult.invalid()) { @@ -4756,6 +4948,11 @@ template Result<> ApplyMorphologyGradient(const AbstractDataStore& in, AbstractDataStore& out, const SizeVec3& dims, const StructuringElement& se, const IDataArray& inArray, const IDataArray& outArray, const std::atomic_bool& shouldCancel, const IFilter::MessageHandler& messageHandler) { + if(auto layout = ValidateMorphologyLayout(dims, se, false, sizeof(T)); layout.invalid()) + { + return layout; + } + return DispatchAlgorithm, MorphGradientWorkingMemory>({&inArray, &outArray}, in, out, dims, se, shouldCancel, messageHandler); } @@ -4819,6 +5016,11 @@ class BinaryMorphScanline Result<> operator()() { + if(auto layout = ValidateMorphologyLayout(m_Dims, m_SE, false, sizeof(T)); layout.invalid()) + { + return layout; + } + const usize dimX = m_Dims[0]; const usize dimY = m_Dims[1]; const usize dimZ = m_Dims[2]; @@ -5096,6 +5298,11 @@ class BinaryMorphDirect Result<> operator()() { + if(auto layout = ValidateMorphologyLayout(m_Dims, m_SE, false, sizeof(T)); layout.invalid()) + { + return layout; + } + // Dispatch the runtime op to a compile-time bool so the accumulator's any/all formula is fixed at compile // time (matching ITK's distinct Dilate/Erode filter classes). return (m_Op == MorphOp::Dilate) ? runImpl() : runImpl(); @@ -5415,6 +5622,11 @@ class BinaryMorphWorkingMemory Result<> operator()() { + if(auto layout = ValidateMorphologyLayout(m_Dims, m_SE, false, sizeof(T)); layout.invalid()) + { + return layout; + } + if constexpr(detail::k_UseVectorHistogram) { if(detail::ShouldUseMorphologyResidentFlatFold(m_Dims, m_SE)) @@ -5466,6 +5678,11 @@ template Result<> ApplyBinaryMorphology(const AbstractDataStore& in, AbstractDataStore& out, const SizeVec3& dims, const StructuringElement& se, MorphOp op, T foreground, T background, bool boundaryToForeground, const IDataArray& inArray, const IDataArray& outArray, const std::atomic_bool& shouldCancel, const IFilter::MessageHandler& messageHandler) { + if(auto layout = ValidateMorphologyLayout(dims, se, false, sizeof(T)); layout.invalid()) + { + return layout; + } + return DispatchAlgorithm, BinaryMorphWorkingMemory>({&inArray, &outArray}, in, out, dims, se, op, foreground, background, boundaryToForeground, shouldCancel, messageHandler); } @@ -5552,6 +5769,11 @@ template Result<> ApplyBinaryMorphologyCompositePipeline(const AbstractDataStore& input, AbstractDataStore& output, const SizeVec3& dims, const StructuringElement& se, MorphOp firstOp, MorphOp secondOp, bool safeBorder, T foreground, T background, const std::atomic_bool& shouldCancel, usize grantedWorkingMemoryBytes) { + if(auto layout = ValidateMorphologyLayout(dims, se, safeBorder, sizeof(T)); layout.invalid()) + { + return layout; + } + if(shouldCancel) { return {}; @@ -5661,7 +5883,7 @@ Result<> ApplyBinaryMorphologyCompositePipeline(const AbstractDataStore& inpu const bool secondBoundaryToForeground = secondOp == MorphOp::Erode; // The flat fold uses only its precomputed offsets. The moving-window fallback needs axis sets. const std::vector flatOffsets = - !usePackedComposite && useFlatFold ? detail::MakeMorphologyFlatFoldOffsets(se, paddedDims[0], paddedDims[1]) : std::vector{}; + !usePackedComposite && useFlatFold ? detail::MakeMorphologyFlatFoldOffsets(se, paddedDims) : std::vector{}; std::optional axisSets; if(!useFlatFold) { diff --git a/src/simplnx/Utilities/ImageProcessing/ObjectMorphologyEngine.hpp b/src/simplnx/Utilities/ImageProcessing/ObjectMorphologyEngine.hpp index c06ef9111d..8b53772cf1 100644 --- a/src/simplnx/Utilities/ImageProcessing/ObjectMorphologyEngine.hpp +++ b/src/simplnx/Utilities/ImageProcessing/ObjectMorphologyEngine.hpp @@ -8,6 +8,7 @@ #include "simplnx/DataStructure/IDataArray.hpp" #include "simplnx/Filter/IFilter.hpp" #include "simplnx/Utilities/AlgorithmDispatch.hpp" +#include "simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp" #include "simplnx/Utilities/ImageProcessing/StructuringElement.hpp" #include "simplnx/Utilities/ImageProcessing/WorkingMemory.hpp" #include "simplnx/Utilities/ParallelDataAlgorithm.hpp" @@ -854,6 +855,11 @@ class ObjectMorphScatter Result<> operator()() { + if(auto layout = ValidateMorphologyLayout(m_Dims, m_SE, false, sizeof(T)); layout.invalid()) + { + return layout; + } + const usize dimX = m_Dims[0]; const usize dimY = m_Dims[1]; const usize dimZ = m_Dims[2]; @@ -967,6 +973,11 @@ class ObjectMorphGather Result<> operator()() { + if(auto layout = ValidateMorphologyLayout(m_Dims, m_SE, false, sizeof(T)); layout.invalid()) + { + return layout; + } + const usize dimX = m_Dims[0]; const usize dimY = m_Dims[1]; const usize dimZ = m_Dims[2]; @@ -1232,6 +1243,11 @@ Result<> ApplyObjectMorphology(const AbstractDataStore& in, AbstractDataStore T objectValue, T backgroundValue, const IDataArray& inArray, const IDataArray& outArray, const std::atomic_bool& shouldCancel, const IFilter::MessageHandler& messageHandler) { + if(auto layout = ValidateMorphologyLayout(dims, se, false, sizeof(T)); layout.invalid()) + { + return layout; + } + const bool usesOutOfCoreStore = in.getStoreType() == IDataStore::StoreType::OutOfCore || out.getStoreType() == IDataStore::StoreType::OutOfCore; if(usesOutOfCoreStore && !ForceInCoreAlgorithm() && detail::ShouldUseObjectMorphologyResidentState(dims)) { diff --git a/src/simplnx/Utilities/ImageProcessing/StructuringElement.hpp b/src/simplnx/Utilities/ImageProcessing/StructuringElement.hpp index 0e042c3044..e861d8bc1d 100644 --- a/src/simplnx/Utilities/ImageProcessing/StructuringElement.hpp +++ b/src/simplnx/Utilities/ImageProcessing/StructuringElement.hpp @@ -1,9 +1,17 @@ #pragma once +#include "simplnx/Common/Result.hpp" #include "simplnx/Common/Types.hpp" +#include +#include + #include #include +#include +#include +#include +#include #include namespace nx::core::ImageProcessing @@ -49,6 +57,56 @@ struct StructuringElement std::vector offsets; // all (dx,dy,dz) where the SE mask is true }; +/** @brief Largest radius whose moving-window offsets can also represent an adjacent offset. */ +inline constexpr uint32 k_MaxKernelRadius = static_cast(std::numeric_limits::max() - 1); +inline constexpr int32 k_KernelRadiusLengthError = -88000; +inline constexpr int32 k_KernelRadiusRangeError = -88001; +inline constexpr int32 k_KernelRadiusCountOverflowError = -88002; +inline constexpr int32 k_KernelRadiusCapacityError = -88003; +inline constexpr int32 k_KernelConstructionError = -88004; + +/** + * @brief Checks kernel representation limits without constructing offsets. + * @param radius X, Y and Z radii in cells. Each radius must be at most k_MaxKernelRadius. + * @return Error for an invalid axis count, radius, bounding-box count or vector element count. + * @note The vector element limit also bounds the allocation byte count on supported 64-bit targets. + * No workload or available-memory limit applies. + */ +inline Result<> ValidateKernelRadius(nonstd::span radius) +{ + if(radius.size() != 3) + { + return MakeErrorResult(k_KernelRadiusLengthError, fmt::format("Kernel Radius has {} components. Supply exactly 3 components (X, Y, Z).", radius.size())); + } + constexpr std::array axes = {"X", "Y", "Z"}; + for(usize axis = 0; axis < 3; ++axis) + { + if(radius[axis] > k_MaxKernelRadius) + { + return MakeErrorResult(k_KernelRadiusRangeError, fmt::format("Kernel Radius {}={} exceeds the maximum {} cells. Reduce this radius.", axes.at(axis), radius[axis], k_MaxKernelRadius)); + } + } + uint64 count = 1; + for(const uint32 value : radius) + { + const uint64 extent = (2 * static_cast(value)) + 1; + if(count > std::numeric_limits::max() / extent) + { + return MakeErrorResult(k_KernelRadiusCountOverflowError, + fmt::format("Kernel Radius (X={}, Y={}, Z={}) overflows the bounding-box count (2*X+1)*(2*Y+1)*(2*Z+1). Reduce the radii.", radius[0], radius[1], radius[2])); + } + count *= extent; + } + const usize capacity = std::vector().max_size(); + if(count > capacity) + { + return MakeErrorResult(k_KernelRadiusCapacityError, + fmt::format("Kernel Radius (X={}, Y={}, Z={}) gives bounding-box element count (2*X+1)*(2*Y+1)*(2*Z+1)={} above the offset vector element count limit {}. Reduce the radii.", + radius[0], radius[1], radius[2], count, capacity)); + } + return {}; +} + namespace detail { // Parameters the ITK Annulus factory is invoked with for the default (parameter-less) Annulus @@ -70,7 +128,7 @@ constexpr int32 k_AnnulusThickness = 1; * EllipsoidInteriorExteriorSpatialFunction, which divides each component by 0.5 * axis and * includes the point when the sum of squares is <= 1. */ -inline bool InEllipsoid(int32 dx, int32 dy, int32 dz, double hx, double hy, double hz) +inline bool InEllipsoid(int64 dx, int64 dy, int64 dz, double hx, double hy, double hz) { const double fx = static_cast(dx) / hx; const double fy = static_cast(dy) / hy; @@ -92,16 +150,26 @@ inline bool InEllipsoid(int32 dx, int32 dy, int32 dz, double hx, double hy, doub * 0.5 * max(2*r_i + 1 - 2*thickness, 1); center excluded. * * A radius of 0 on an axis degenerates that axis to a single plane (so rz == 0 yields a 2D SE); a - * negative radius yields an empty range on that axis. + * negative radius returns an empty element before arithmetic. + * @param type Kernel shape. + * @param radius Signed X, Y and Z radii in cells. + * @return Rasterized offsets in X-fastest order. + * @pre The caller selects small fixed radii. User parameters use MakeCheckedStructuringElement instead. + * @throws std::bad_alloc If offset allocation fails. + * @throws std::length_error If the offset count exceeds the vector capacity. */ inline StructuringElement MakeStructuringElement(KernelType type, const std::array& radius) { - const int32 rx = radius[0]; - const int32 ry = radius[1]; - const int32 rz = radius[2]; + const int64 rx = radius[0]; + const int64 ry = radius[1]; + const int64 rz = radius[2]; StructuringElement se; se.radius = radius; + if(rx < 0 || ry < 0 || rz < 0) + { + return se; + } // Ellipsoid half-axes (shared by Ball and the Annulus outer shell). const double outerHx = rx + 0.5; @@ -109,24 +177,34 @@ inline StructuringElement MakeStructuringElement(KernelType type, const std::arr const double outerHz = rz + 0.5; // Annulus inner-shell half-axes (only used for Annulus). - const double innerHx = 0.5 * std::max(2 * rx + 1 - 2 * detail::k_AnnulusThickness, 1); - const double innerHy = 0.5 * std::max(2 * ry + 1 - 2 * detail::k_AnnulusThickness, 1); - const double innerHz = 0.5 * std::max(2 * rz + 1 - 2 * detail::k_AnnulusThickness, 1); + const double innerHx = 0.5 * std::max(2 * rx + 1 - 2 * detail::k_AnnulusThickness, 1); + const double innerHy = 0.5 * std::max(2 * ry + 1 - 2 * detail::k_AnnulusThickness, 1); + const double innerHz = 0.5 * std::max(2 * rz + 1 - 2 * detail::k_AnnulusThickness, 1); - // Reserve an upper bound (the full bounding box) to avoid reallocation churn. - // Compute in 64-bit to avoid signed-overflow UB on the products for large radii. - if(rx >= 0 && ry >= 0 && rz >= 0) + // A checked bounding-box reservation avoids reallocation without wrapping the element count. + usize bound = 1; + bool boundFits = true; + for(const int32 value : radius) + { + const uint64 extent = (2 * static_cast(value)) + 1; + if(extent > std::numeric_limits::max() || bound > std::numeric_limits::max() / extent) + { + boundFits = false; + break; + } + bound *= static_cast(extent); + } + if(boundFits) { - const usize bound = static_cast(2LL * rx + 1) * static_cast(2LL * ry + 1) * static_cast(2LL * rz + 1); se.offsets.reserve(bound); } // Iterate the bounding box with X fastest-moving (matches simplnx's flat layout). - for(int32 dz = -rz; dz <= rz; ++dz) + for(int64 dz = -rz; dz <= rz; ++dz) { - for(int32 dy = -ry; dy <= ry; ++dy) + for(int64 dy = -ry; dy <= ry; ++dy) { - for(int32 dx = -rx; dx <= rx; ++dx) + for(int64 dx = -rx; dx <= rx; ++dx) { bool on = false; switch(type) @@ -156,7 +234,7 @@ inline StructuringElement MakeStructuringElement(KernelType type, const std::arr if(on) { - se.offsets.push_back(SEOffset{dx, dy, dz}); + se.offsets.push_back(SEOffset{static_cast(dx), static_cast(dy), static_cast(dz)}); } } } @@ -164,4 +242,47 @@ inline StructuringElement MakeStructuringElement(KernelType type, const std::arr return se; } +namespace detail +{ +/** + * @brief Converts construction allocation failures into the shared kernel error. + * @tparam Build Callable that constructs offsets from the validated shape and radius. + * @param type Kernel shape passed to build. + * @param radius User-supplied radii in cells. + * @param build Construction callable. Tests can inject allocation exceptions here. + * @pre radius has exactly three components and satisfies ValidateKernelRadius(). + * @return Constructed element or construction error. + */ +template +Result MakeCheckedStructuringElementWith(KernelType type, nonstd::span radius, Build&& build) +{ + try + { + return {std::forward(build)(type, radius)}; + } catch(const std::bad_alloc&) + { + return MakeErrorResult( + k_KernelConstructionError, fmt::format("Cannot allocate offsets for Kernel Radius (X={}, Y={}, Z={}). Reduce the radii or make more memory available.", radius[0], radius[1], radius[2])); + } catch(const std::length_error&) + { + return MakeErrorResult( + k_KernelConstructionError, + fmt::format("Cannot construct offsets for Kernel Radius (X={}, Y={}, Z={}): the offset vector length is too large. Reduce the radii.", radius[0], radius[1], radius[2])); + } +} +} // namespace detail + +/** + * @brief Constructs a structuring element with checked allocation failure handling. + * @param type Kernel shape. + * @param radius X, Y and Z radii in cells. + * @pre radius has exactly three components and satisfies ValidateKernelRadius(). + * @return Constructed element or construction error. + */ +inline Result MakeCheckedStructuringElement(KernelType type, nonstd::span radius) +{ + return detail::MakeCheckedStructuringElementWith(type, radius, [](KernelType shape, nonstd::span values) { + return MakeStructuringElement(shape, {static_cast(values[0]), static_cast(values[1]), static_cast(values[2])}); + }); +} } // namespace nx::core::ImageProcessing diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index e643bd934c..075ffc066e 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -86,6 +86,7 @@ set(SIMPLNX_TEST_SRCS UpdateImageGeomActionTest.cpp Vec3Test.cpp StringUtilitiesTest.cpp + StructuringElementValidationTest.cpp StbImageIOTest.cpp StoreResizeContractsTest.cpp ThrottledMessageHandlerTest.cpp diff --git a/test/StructuringElementValidationTest.cpp b/test/StructuringElementValidationTest.cpp new file mode 100644 index 0000000000..15e467bf90 --- /dev/null +++ b/test/StructuringElementValidationTest.cpp @@ -0,0 +1,308 @@ +#include "simplnx/Common/Result.hpp" +#include "simplnx/UnitTest/UnitTestCommon.hpp" +#include "simplnx/Utilities/ImageProcessing/ImageProcessingFilterUtilities.hpp" +#include "simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp" +#include "simplnx/Utilities/ImageProcessing/ObjectMorphologyEngine.hpp" +#include "simplnx/Utilities/ImageProcessing/StructuringElement.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +using namespace nx::core; +using namespace nx::core::ImageProcessing; + +namespace +{ +void RequireError(const Result<>& result, int32 code, const std::string& phrase) +{ + SIMPLNX_RESULT_REQUIRE_INVALID(result); + REQUIRE(result.errors().size() == 1); + REQUIRE(result.errors().front().code == code); + REQUIRE(result.errors().front().message.find(phrase) != std::string::npos); +} + +void RequireOffsets(KernelType type, const std::array& radius, const std::vector& expected) +{ + auto result = MakeCheckedStructuringElement(type, radius); + SIMPLNX_RESULT_REQUIRE_VALID(result); + const auto& se = result.value(); + REQUIRE(se.offsets.size() == expected.size()); + for(usize axis = 0; axis < 3; ++axis) + { + REQUIRE(se.radius[axis] == radius[axis]); + } + for(usize i = 0; i < expected.size(); ++i) + { + CAPTURE(i); + REQUIRE(se.offsets[i].dx == expected[i].dx); + REQUIRE(se.offsets[i].dy == expected[i].dy); + REQUIRE(se.offsets[i].dz == expected[i].dz); + } +} +} // namespace + +TEST_CASE("simplnx::StructuringElement: Kernel Radius diagnostics", "[simplnx][StructuringElement]") +{ + SECTION("Length") + { + const std::array radius = {0, 0}; + auto result = ValidateKernelRadius(radius); + RequireError(result, k_KernelRadiusLengthError, "2"); + } + SECTION("Every axis at first invalid") + { + for(usize axis = 0; axis < 3; ++axis) + { + std::array radius = {0, 0, 0}; + radius[axis] = 2147483647u; + auto result = ValidateKernelRadius(radius); + RequireError(result, k_KernelRadiusRangeError, std::array{"X", "Y", "Z"}[axis]); + REQUIRE(result.errors().front().message.find("2147483647") != std::string::npos); + REQUIRE(result.errors().front().message.find("2147483646") != std::string::npos); + } + } + SECTION("Bounding-box product") + { + const std::array radius = {2147483646u, 2147483646u, 2147483646u}; + auto result = ValidateKernelRadius(radius); + RequireError(result, k_KernelRadiusCountOverflowError, "(2*X+1)*(2*Y+1)*(2*Z+1)"); + REQUIRE(result.errors().front().message.find("2147483646") != std::string::npos); + } + SECTION("Vector element capacity") + { + const std::array radius = {1048576, 1048576, 1048576}; + auto result = ValidateKernelRadius(radius); + RequireError(result, k_KernelRadiusCapacityError, "element count"); + REQUIRE(result.errors().front().message.find("1048576") != std::string::npos); + } + SECTION("Large representable element count has no workload cap") + { + const std::array radius = {200000000, 200000000, 0}; + auto result = ValidateKernelRadius(radius); + SIMPLNX_RESULT_REQUIRE_VALID(result); + } + SECTION("Zero and last valid axis") + { + for(usize axis = 0; axis < 3; ++axis) + { + std::array radius = {0, 0, 0}; + auto result = ValidateKernelRadius(radius); + SIMPLNX_RESULT_REQUIRE_VALID(result); + radius[axis] = k_MaxKernelRadius; + result = ValidateKernelRadius(radius); + SIMPLNX_RESULT_REQUIRE_VALID(result); + } + } +} + +TEST_CASE("simplnx::StructuringElement: Checked construction failures", "[simplnx][StructuringElement]") +{ + const std::array radius = {1, 1, 0}; + SECTION("bad_alloc") + { + auto result = ImageProcessing::detail::MakeCheckedStructuringElementWith(KernelType::Box, radius, [](KernelType, nonstd::span) -> StructuringElement { throw std::bad_alloc{}; }); + SIMPLNX_RESULT_REQUIRE_INVALID(result); + REQUIRE(result.errors().front().code == k_KernelConstructionError); + REQUIRE(result.errors().front().message.find("Kernel Radius (X=1, Y=1, Z=0)") != std::string::npos); + } + SECTION("length_error") + { + auto result = ImageProcessing::detail::MakeCheckedStructuringElementWith( + KernelType::Box, radius, [](KernelType, nonstd::span) -> StructuringElement { throw std::length_error("injected construction failure"); }); + SIMPLNX_RESULT_REQUIRE_INVALID(result); + REQUIRE(result.errors().front().code == k_KernelConstructionError); + } +} + +TEST_CASE("simplnx::StructuringElement: Ordered offset oracles", "[simplnx][StructuringElement]") +{ + SECTION("Unit cube") + { + const std::vector box = {{-1, -1, -1}, {0, -1, -1}, {1, -1, -1}, {-1, 0, -1}, {0, 0, -1}, {1, 0, -1}, {-1, 1, -1}, {0, 1, -1}, {1, 1, -1}, + {-1, -1, 0}, {0, -1, 0}, {1, -1, 0}, {-1, 0, 0}, {0, 0, 0}, {1, 0, 0}, {-1, 1, 0}, {0, 1, 0}, {1, 1, 0}, + {-1, -1, 1}, {0, -1, 1}, {1, -1, 1}, {-1, 0, 1}, {0, 0, 1}, {1, 0, 1}, {-1, 1, 1}, {0, 1, 1}, {1, 1, 1}}; + const std::vector ball = {{0, -1, -1}, {-1, 0, -1}, {0, 0, -1}, {1, 0, -1}, {0, 1, -1}, {-1, -1, 0}, {0, -1, 0}, {1, -1, 0}, {-1, 0, 0}, {0, 0, 0}, + {1, 0, 0}, {-1, 1, 0}, {0, 1, 0}, {1, 1, 0}, {0, -1, 1}, {-1, 0, 1}, {0, 0, 1}, {1, 0, 1}, {0, 1, 1}}; + const std::vector annulus = {{0, -1, -1}, {-1, 0, -1}, {0, 0, -1}, {1, 0, -1}, {0, 1, -1}, {-1, -1, 0}, {0, -1, 0}, {1, -1, 0}, {-1, 0, 0}, + {1, 0, 0}, {-1, 1, 0}, {0, 1, 0}, {1, 1, 0}, {0, -1, 1}, {-1, 0, 1}, {0, 0, 1}, {1, 0, 1}, {0, 1, 1}}; + RequireOffsets(KernelType::Box, {1, 1, 1}, box); + RequireOffsets(KernelType::Ball, {1, 1, 1}, ball); + RequireOffsets(KernelType::Annulus, {1, 1, 1}, annulus); + RequireOffsets(KernelType::Cross, {1, 1, 1}, {{0, 0, -1}, {0, -1, 0}, {-1, 0, 0}, {0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}}); + } + SECTION("Unit square") + { + const std::vector square = {{-1, -1, 0}, {0, -1, 0}, {1, -1, 0}, {-1, 0, 0}, {0, 0, 0}, {1, 0, 0}, {-1, 1, 0}, {0, 1, 0}, {1, 1, 0}}; + RequireOffsets(KernelType::Box, {1, 1, 0}, square); + RequireOffsets(KernelType::Ball, {1, 1, 0}, square); + RequireOffsets(KernelType::Annulus, {1, 1, 0}, {{-1, -1, 0}, {0, -1, 0}, {1, -1, 0}, {-1, 0, 0}, {1, 0, 0}, {-1, 1, 0}, {0, 1, 0}, {1, 1, 0}}); + RequireOffsets(KernelType::Cross, {1, 1, 0}, {{0, -1, 0}, {-1, 0, 0}, {0, 0, 0}, {1, 0, 0}, {0, 1, 0}}); + } + SECTION("Asymmetric plane") + { + RequireOffsets(KernelType::Box, {2, 1, 0}, + {{-2, -1, 0}, {-1, -1, 0}, {0, -1, 0}, {1, -1, 0}, {2, -1, 0}, {-2, 0, 0}, {-1, 0, 0}, {0, 0, 0}, {1, 0, 0}, {2, 0, 0}, {-2, 1, 0}, {-1, 1, 0}, {0, 1, 0}, {1, 1, 0}, {2, 1, 0}}); + RequireOffsets(KernelType::Ball, {2, 1, 0}, {{-1, -1, 0}, {0, -1, 0}, {1, -1, 0}, {-2, 0, 0}, {-1, 0, 0}, {0, 0, 0}, {1, 0, 0}, {2, 0, 0}, {-1, 1, 0}, {0, 1, 0}, {1, 1, 0}}); + RequireOffsets(KernelType::Annulus, {2, 1, 0}, {{-1, -1, 0}, {0, -1, 0}, {1, -1, 0}, {-2, 0, 0}, {2, 0, 0}, {-1, 1, 0}, {0, 1, 0}, {1, 1, 0}}); + RequireOffsets(KernelType::Cross, {2, 1, 0}, {{0, -1, 0}, {-2, 0, 0}, {-1, 0, 0}, {0, 0, 0}, {1, 0, 0}, {2, 0, 0}, {0, 1, 0}}); + } +} + +TEST_CASE("simplnx::StructuringElement: Legacy signed radius", "[simplnx][StructuringElement]") +{ + for(const int32 value : std::array{-1, std::numeric_limits::min()}) + { + auto se = MakeStructuringElement(KernelType::Box, {value, 0, 0}); + REQUIRE(se.offsets.empty()); + } + const auto se = MakeStructuringElement(KernelType::Box, {0, 0, 0}); + REQUIRE(se.offsets.size() == 1); + REQUIRE(se.offsets[0].dx == 0); + REQUIRE(se.offsets[0].dy == 0); + REQUIRE(se.offsets[0].dz == 0); +} + +TEST_CASE("simplnx::MorphologyLayout: Representation boundaries", "[simplnx][StructuringElement]") +{ + constexpr usize signedMax = static_cast(std::numeric_limits::max()); + struct LayoutCase + { + SizeVec3 dims; + std::array radius; + bool safeBorder; + usize bytes; + int32 code; + std::string phrase; + }; + const std::vector cases = {{{std::numeric_limits::max() - 1, 1, 1}, {1, 0, 0}, true, 1, k_MorphologyPaddedExtentError, "padded extent"}, + {{signedMax - 2, 1, 1}, {2, 0, 0}, false, 1, k_MorphologyCoordinateError, "coordinate"}, + {{3, 3, 1024}, {100000000, 100000000, 0}, true, 1, k_MorphologyVolumeError, "volume"}, + {{usize{1} << 32, usize{1} << 31, 1}, {0, 0, 0}, false, 1, k_MorphologyPlaneError, "plane"}, + {{usize{1} << 31, usize{1} << 31, 1}, {0, 0, 0}, false, 8, k_MorphologyByteCountError, "byte"}}; + for(const auto& item : cases) + { + CAPTURE(item.phrase); + auto result = ValidateMorphologyLayout(item.dims, item.radius, item.safeBorder, item.bytes); + RequireError(result, item.code, item.phrase); + REQUIRE(result.errors().front().message.find("Kernel Radius") != std::string::npos); + REQUIRE(result.errors().front().message.find(std::to_string(item.dims[0])) != std::string::npos); + REQUIRE(result.errors().front().message.find(std::to_string(item.radius[0])) != std::string::npos); + } + for(const usize axis : std::array{0, 1}) + { + SizeVec3 dims = {1, 1, 1}; + std::array radius = {0, 0, 0}; + dims[axis] = signedMax - 3; + radius[axis] = 2; + auto result = ValidateMorphologyLayout(dims, radius, false, 1); + SIMPLNX_RESULT_REQUIRE_VALID(result); + ++dims[axis]; + result = ValidateMorphologyLayout(dims, radius, false, 1); + RequireError(result, k_MorphologyCoordinateError, "coordinate"); + } + const std::vector controls = {{{signedMax - 1, 1, 1}, {0, 0, 0}, false, 1, 0, "large X"}, + {{1, signedMax - 1, 1}, {0, 0, 0}, false, 1, 0, "large Y"}, + {{3, 3, 1024}, {100000000, 100000000, 0}, false, 1, 0, "Safe Border off"}, + {{3, 3, 1}, {0, 0, 2147483646u}, true, 1, 0, "2D ignores Z padding"}, + {{131072, 131072, 2}, {0, 0, 1073741823}, false, 1, 0, "unrepresentable flat delta"}, + {{usize{1} << 30, usize{1} << 30, 4}, {0, 0, 4}, false, 1, 0, "flat delta plus volume"}}; + for(const auto& item : controls) + { + CAPTURE(item.phrase); + auto result = ValidateMorphologyLayout(item.dims, item.radius, item.safeBorder, item.bytes); + SIMPLNX_RESULT_REQUIRE_VALID(result); + } +} + +TEST_CASE("simplnx::MorphologyLayout: Packed word endpoint", "[simplnx][StructuringElement]") +{ + constexpr int64 signedMax = std::numeric_limits::max(); + REQUIRE(ImageProcessing::detail::MorphologyPackedWordEnd(signedMax - 8, signedMax - 1) == signedMax - 1); + REQUIRE(ImageProcessing::detail::MorphologyPackedWordEnd(0, 3) == 3); + REQUIRE(ImageProcessing::detail::MorphologyPackedWordEnd(-10, 3) == 3); + REQUIRE(ImageProcessing::detail::MorphologyPackedWordEnd(-70, 3) == -6); + const std::array word = {5}; + ImageProcessing::detail::PackedBinaryPlanesView view; + view.words = word.data(); + view.zLo = 0; + view.depth = 1; + view.capacity = 1; + view.layout.wordsPerRow = 1; + view.layout.planeWords = 1; + REQUIRE(ImageProcessing::detail::ExtractPackedBinaryWord(view, {3, 1, 1}, 0, 0, 0, false) == 5); + REQUIRE(ImageProcessing::detail::ExtractPackedBinaryWord(view, {3, 1, 1}, signedMax - 8, 0, 0, false) == 0); +} + +TEST_CASE("simplnx::MorphologyLayout: Direct engine guards", "[simplnx][StructuringElement]") +{ + // Invalid metadata must return before dispatch, reading values, or allocating scratch. + DataStructure ds; + auto* input = UnitTest::CreateTestDataArray(ds, "Input", {1}, {1}); + auto* output = UnitTest::CreateTestDataArray(ds, "Output", {1}, {1}); + REQUIRE(input != nullptr); + REQUIRE(output != nullptr); + const auto& in = input->getDataStoreRef(); + auto& out = output->getDataStoreRef(); + const SizeVec3 dims = {static_cast(std::numeric_limits::max()) - 2, 1, 1}; + const auto se = MakeStructuringElement(KernelType::Box, {2, 0, 0}); + const auto box = ImageProcessing::detail::MakeFullBoxNeighborOffsets(); + const std::atomic_bool cancel = false; + const IFilter::MessageHandler handler; + std::vector> results; + results.push_back(MorphDirect(in, out, dims, se, MorphOp::Dilate, cancel, handler)()); + results.push_back(MorphScanline(in, out, dims, se, MorphOp::Dilate, cancel, handler)()); + results.push_back(MorphWorkingMemory(in, out, dims, se, MorphOp::Dilate, cancel, handler)()); + results.push_back(MorphGradientDirect(in, out, dims, se, cancel, handler)()); + results.push_back(MorphGradientScanline(in, out, dims, se, cancel, handler)()); + results.push_back(MorphGradientWorkingMemory(in, out, dims, se, cancel, handler)()); + results.push_back(BinaryMorphDirect(in, out, dims, se, MorphOp::Dilate, 5, 0, false, cancel, handler)()); + results.push_back(BinaryMorphScanline(in, out, dims, se, MorphOp::Dilate, 5, 0, false, cancel, handler)()); + results.push_back(BinaryMorphWorkingMemory(in, out, dims, se, MorphOp::Dilate, 5, 0, false, cancel, handler)()); + results.push_back(ObjectMorphScatter(in, out, dims, se, box, ObjectMorphOp::Dilate, 5, 0, cancel, handler)()); + results.push_back(ObjectMorphGather(in, out, dims, se, box, ObjectMorphOp::Dilate, 5, 0, cancel, handler)()); + results.push_back(ApplyMorphology(in, out, dims, se, MorphOp::Dilate, *input, *output, cancel, handler)); + results.push_back(ApplyMorphologyGradient(in, out, dims, se, *input, *output, cancel, handler)); + results.push_back(ApplyBinaryMorphology(in, out, dims, se, MorphOp::Dilate, 5, 0, false, *input, *output, cancel, handler)); + results.push_back(ApplyObjectMorphology(in, out, dims, se, box, ObjectMorphOp::Dilate, 5, 0, *input, *output, cancel, handler)); + results.push_back(ApplyMorphologyCompositePipeline(in, out, dims, se, MorphOp::Erode, MorphOp::Dilate, false, ImageProcessing::detail::MorphologyCompositeOutputMode::Morphology, cancel, 0)); + results.push_back(ApplyBinaryMorphologyCompositePipeline(in, out, dims, se, MorphOp::Erode, MorphOp::Dilate, false, 5, 0, cancel, 0)); + for(const auto& result : results) + { + RequireError(result, k_MorphologyCoordinateError, "coordinate"); + } +} + +TEST_CASE("simplnx::MorphologyLayout: Selected geometry error context", "[simplnx][StructuringElement]") +{ + const DataPath geometryPath({"Dataset", "Selected Geometry"}); + constexpr int32 k_TestWarning = 37; + SECTION("Invalid layout keeps its code, message and warnings") + { + auto layout = MakeErrorResult(k_MorphologyVolumeError, "Original layout message."); + layout.warnings().push_back({k_TestWarning, "Original warning."}); + auto result = AddMorphologyLayoutGeometryContext(std::move(layout), geometryPath); + SIMPLNX_RESULT_REQUIRE_INVALID(result); + REQUIRE(result.errors().size() == 1); + REQUIRE(result.errors().front().code == k_MorphologyVolumeError); + REQUIRE(result.errors().front().message == "Original layout message. Image Geometry: 'Dataset/Selected Geometry'."); + REQUIRE(result.warnings().size() == 1); + REQUIRE(result.warnings().front().code == k_TestWarning); + REQUIRE(result.warnings().front().message == "Original warning."); + } + SECTION("Valid result keeps its warnings") + { + Result<> layout; + layout.warnings().push_back({k_TestWarning, "Original warning."}); + auto result = AddMorphologyLayoutGeometryContext(std::move(layout), geometryPath); + SIMPLNX_RESULT_REQUIRE_VALID(result); + REQUIRE(result.warnings().size() == 1); + REQUIRE(result.warnings().front().code == k_TestWarning); + REQUIRE(result.warnings().front().message == "Original warning."); + } +}