From 8a2634365cc251244a97debee32b4afad9e62837 Mon Sep 17 00:00:00 2001 From: Joey Kleingers Date: Mon, 9 Nov 2026 12:30:04 -0500 Subject: [PATCH 1/6] BUG: Reject kernel radii that morphology filters cannot represent Kernel Radius is a UInt32 vector that preflight never checked. Execute narrowed each component to int32, so a radius of 2147483648 or more became negative, the structuring element came out empty and the filter copied its input (top-hats and the gradient wrote zeros). Large radii also overflowed the element-count and Safe Border size arithmetic. - Add ValidateKernelRadius() and MakeCheckedStructuringElement() to StructuringElement.hpp: each radius must be at most 2147483646 and the element count must fit the offset vector. Allocation failures are returned as errors. - Add ValidateMorphologyLayout() to MorphologyEngine.hpp. It checks the Safe Border padded extents and the signed coordinate, plane, volume and byte counts derived from the image and the radius. Preflight and every execution entry point call it before allocating. - Use the flat-offset fold only when its offsets and staged indices fit int64, and clamp the packed binary word end without overflow. - Negative radii in MakeStructuringElement() return an empty element before any negation, and its loops and shell arithmetic use int64. Fixed filters: BinaryDilateImageFilter, BinaryErodeImageFilter, BinaryMorphologicalClosingImageFilter, BinaryMorphologicalOpeningImageFilter, BinaryOpeningByReconstructionImageFilter, BlackTopHatImageFilter, ClosingByReconstructionImageFilter, DilateObjectMorphologyImageFilter, ErodeObjectMorphologyImageFilter, GrayscaleDilateImageFilter, GrayscaleErodeImageFilter, GrayscaleMorphologicalClosingImageFilter, GrayscaleMorphologicalOpeningImageFilter, MorphologicalGradientImageFilter, OpeningByReconstructionImageFilter, WhiteTopHatImageFilter. Part of #1873. Signed-off-by: Joey Kleingers --- .../docs/BinaryDilateImageFilter.md | 2 + .../docs/BinaryErodeImageFilter.md | 2 + .../BinaryMorphologicalClosingImageFilter.md | 2 + .../BinaryMorphologicalOpeningImageFilter.md | 2 + ...inaryOpeningByReconstructionImageFilter.md | 2 + .../docs/BlackTopHatImageFilter.md | 2 + .../ClosingByReconstructionImageFilter.md | 2 + .../docs/DilateObjectMorphologyImageFilter.md | 2 + .../docs/ErodeObjectMorphologyImageFilter.md | 2 + .../docs/GrayscaleDilateImageFilter.md | 2 + .../docs/GrayscaleErodeImageFilter.md | 2 + ...rayscaleMorphologicalClosingImageFilter.md | 2 + ...rayscaleMorphologicalOpeningImageFilter.md | 2 + .../docs/MorphologicalGradientImageFilter.md | 2 + .../OpeningByReconstructionImageFilter.md | 2 + .../docs/WhiteTopHatImageFilter.md | 2 + .../Filters/BinaryDilateImageFilter.cpp | 26 +- .../Filters/BinaryErodeImageFilter.cpp | 26 +- .../BinaryMorphologicalClosingImageFilter.cpp | 28 +- .../BinaryMorphologicalOpeningImageFilter.cpp | 26 +- ...naryOpeningByReconstructionImageFilter.cpp | 26 +- .../Filters/BlackTopHatImageFilter.cpp | 28 +- .../ClosingByReconstructionImageFilter.cpp | 26 +- .../DilateObjectMorphologyImageFilter.cpp | 26 +- .../ErodeObjectMorphologyImageFilter.cpp | 26 +- .../Filters/GrayscaleDilateImageFilter.cpp | 26 +- .../Filters/GrayscaleErodeImageFilter.cpp | 26 +- ...ayscaleMorphologicalClosingImageFilter.cpp | 28 +- ...ayscaleMorphologicalOpeningImageFilter.cpp | 28 +- .../MorphologicalGradientImageFilter.cpp | 26 +- .../OpeningByReconstructionImageFilter.cpp | 26 +- .../Filters/WhiteTopHatImageFilter.cpp | 28 +- .../test/BinaryDilateImageFilterTest.cpp | 10 + .../test/BinaryErodeImageFilterTest.cpp | 10 + ...aryMorphologicalClosingImageFilterTest.cpp | 15 + ...aryMorphologicalOpeningImageFilterTest.cpp | 10 + ...OpeningByReconstructionImageFilterTest.cpp | 12 + .../test/BlackTopHatImageFilterTest.cpp | 10 + ...ClosingByReconstructionImageFilterTest.cpp | 12 + .../DilateObjectMorphologyImageFilterTest.cpp | 12 + .../ErodeObjectMorphologyImageFilterTest.cpp | 12 + .../test/GrayscaleDilateImageFilterTest.cpp | 10 + .../test/GrayscaleErodeImageFilterTest.cpp | 10 + ...aleMorphologicalClosingImageFilterTest.cpp | 15 + ...aleMorphologicalOpeningImageFilterTest.cpp | 10 + .../MorphologicalGradientImageFilterTest.cpp | 10 + .../test/MorphologyEngineTest.cpp | 81 +++++ .../test/MorphologyFilterTestUtils.hpp | 167 +++++++++ ...OpeningByReconstructionImageFilterTest.cpp | 12 + .../test/WhiteTopHatImageFilterTest.cpp | 10 + .../ImageProcessingFilterUtilities.hpp | 54 +++ .../ImageProcessing/MorphologyEngine.hpp | 253 +++++++++++++- .../ObjectMorphologyEngine.hpp | 16 + .../ImageProcessing/StructuringElement.hpp | 156 ++++++++- test/CMakeLists.txt | 1 + test/StructuringElementValidationTest.cpp | 323 ++++++++++++++++++ 56 files changed, 1627 insertions(+), 62 deletions(-) create mode 100644 test/StructuringElementValidationTest.cpp 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/BinaryDilateImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/BinaryDilateImageFilterTest.cpp index e8941423fe..f35e789c9a 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("ImageProcessing::BinaryDilateImageFilter: Kernel Radius representability", "[ImageProcessing][BinaryDilateImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::BinaryDilateImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][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..0d18478ebb 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("ImageProcessing::BinaryErodeImageFilter: Kernel Radius representability", "[ImageProcessing][BinaryErodeImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::BinaryErodeImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][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..a41aa6706c 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("ImageProcessing::BinaryMorphologicalClosingImageFilter: Kernel Radius representability", "[ImageProcessing][BinaryMorphologicalClosingImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::BinaryMorphologicalClosingImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][BinaryMorphologicalClosingImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({5, 5, 5}); +} + +TEST_CASE("ImageProcessing::BinaryMorphologicalClosingImageFilter: Kernel Radius layout preflight", "[ImageProcessing][BinaryMorphologicalClosingImageFilter]") +{ + morph_test::RequireKernelRadiusLayoutPreflight(); +} diff --git a/src/Plugins/NXImageProcessing/test/BinaryMorphologicalOpeningImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/BinaryMorphologicalOpeningImageFilterTest.cpp index a42ce13746..38c7c66651 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("ImageProcessing::BinaryMorphologicalOpeningImageFilter: Kernel Radius representability", "[ImageProcessing][BinaryMorphologicalOpeningImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::BinaryMorphologicalOpeningImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][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..c7e9dc607e 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("ImageProcessing::BinaryOpeningByReconstructionImageFilter: Kernel Radius representability", "[ImageProcessing][BinaryOpeningByReconstructionImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::BinaryOpeningByReconstructionImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][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..c7060844fc 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("ImageProcessing::BlackTopHatImageFilter: Kernel Radius representability", "[ImageProcessing][BlackTopHatImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::BlackTopHatImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][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..26bdc3342a 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("ImageProcessing::ClosingByReconstructionImageFilter: Kernel Radius representability", "[ImageProcessing][ClosingByReconstructionImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::ClosingByReconstructionImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][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..a995a99a41 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("ImageProcessing::DilateObjectMorphologyImageFilter: Kernel Radius representability", "[ImageProcessing][DilateObjectMorphologyImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::DilateObjectMorphologyImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][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..63800139f5 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("ImageProcessing::ErodeObjectMorphologyImageFilter: Kernel Radius representability", "[ImageProcessing][ErodeObjectMorphologyImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::ErodeObjectMorphologyImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][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..13e81bccda 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("ImageProcessing::GrayscaleDilateImageFilter: Kernel Radius representability", "[ImageProcessing][GrayscaleDilateImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::GrayscaleDilateImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][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..dbabd072fc 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("ImageProcessing::GrayscaleErodeImageFilter: Kernel Radius representability", "[ImageProcessing][GrayscaleErodeImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::GrayscaleErodeImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][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..d70c62abc9 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("ImageProcessing::GrayscaleMorphologicalClosingImageFilter: Kernel Radius representability", "[ImageProcessing][GrayscaleMorphologicalClosingImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::GrayscaleMorphologicalClosingImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][GrayscaleMorphologicalClosingImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({5, 5, 5}); +} + +TEST_CASE("ImageProcessing::GrayscaleMorphologicalClosingImageFilter: Kernel Radius layout preflight", "[ImageProcessing][GrayscaleMorphologicalClosingImageFilter]") +{ + morph_test::RequireKernelRadiusLayoutPreflight(); +} diff --git a/src/Plugins/NXImageProcessing/test/GrayscaleMorphologicalOpeningImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/GrayscaleMorphologicalOpeningImageFilterTest.cpp index 0cf3a0a009..db1507b2e9 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("ImageProcessing::GrayscaleMorphologicalOpeningImageFilter: Kernel Radius representability", "[ImageProcessing][GrayscaleMorphologicalOpeningImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::GrayscaleMorphologicalOpeningImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][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..f7a39d6b00 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("ImageProcessing::MorphologicalGradientImageFilter: Kernel Radius representability", "[ImageProcessing][MorphologicalGradientImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::MorphologicalGradientImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][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..57fc637403 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("ImageProcessing::MorphologyEngine: Kernel Radius flat-fold representability", "[ImageProcessing][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("ImageProcessing::MorphologyEngine: Kernel Radius layout before allocation", "[ImageProcessing][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..37c8834a25 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,169 @@ 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); + } + } + 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..d5e1a3d9de 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("ImageProcessing::OpeningByReconstructionImageFilter: Kernel Radius representability", "[ImageProcessing][OpeningByReconstructionImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::OpeningByReconstructionImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][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..8610da9c1d 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("ImageProcessing::WhiteTopHatImageFilter: Kernel Radius representability", "[ImageProcessing][WhiteTopHatImageFilter]") +{ + morph_test::RequireKernelRadiusPreflight(); +} + +TEST_CASE("ImageProcessing::WhiteTopHatImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][WhiteTopHatImageFilter]") +{ + morph_test::RequireOrdinaryKernelRadius({5, 0, 5}); +} 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..cf43dba00c 100644 --- a/src/simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp +++ b/src/simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp @@ -57,6 +57,94 @@ 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. + * @return Radius or 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) +{ + auto radiusResult = ValidateKernelRadius(radius); + if(radiusResult.invalid()) + { + return radiusResult; + } + 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[axis])); + } + paddedDims[axis] += 2 * pad; + } + constexpr uint64 k_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] > k_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[axis], k_SignedMax)); + } + } + if(paddedDims[0] != 0 && paddedDims[1] > k_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], k_SignedMax)); + } + const uint64 plane = static_cast(paddedDims[0]) * paddedDims[1]; + if(plane != 0 && paddedDims[2] > k_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], k_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 se 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. + * @return Shared radius or layout error. + */ +inline Result<> ValidateMorphologyLayout(const SizeVec3& dims, const StructuringElement& se, bool safeBorder, usize elementBytes) +{ + const std::array radius = {static_cast(std::max(0, se.radius[0])), static_cast(std::max(0, se.radius[1])), + static_cast(std::max(0, se.radius[2]))}; + return ValidateMorphologyLayout(dims, radius, safeBorder, elementBytes); +} + namespace detail { enum class MorphologyCompositeOutputMode @@ -116,11 +204,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 se 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& se) +{ + constexpr uint64 k_Max = static_cast(std::numeric_limits::max()); + if(dims[0] > k_Max || dims[1] > k_Max || dims[2] > k_Max || (dims[0] != 0 && dims[1] > k_Max / dims[0])) + { + return false; + } + const uint64 slice = static_cast(dims[0]) * dims[1]; + if(slice != 0 && dims[2] > k_Max / slice) + { + return false; + } + const uint64 volume = slice * dims[2]; + for(const SEOffset& offset : se.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[axis] < 0 ? -values[axis] : values[axis]); + if(magnitude != 0 && strides[axis] > k_Max / magnitude) + { + return false; + } + const int64 product = values[axis] < 0 ? -static_cast(magnitude * strides[axis]) : static_cast(magnitude * strides[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 > k_Max - 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 +1390,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] * dims[1]); std::vector flatOffsets; flatOffsets.reserve(se.offsets.size()); for(const SEOffset& offset : se.offsets) @@ -1420,7 +1564,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 +1718,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 +1851,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 +2044,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 k_WordBits = std::numeric_limits::digits; + return xStart > std::numeric_limits::max() - k_WordBits ? rowEnd : std::min(rowEnd, xStart + k_WordBits); +} + /** * @brief Extracts 64 membership bits from one logical packed X/Y/Z row. * @@ -1961,7 +2117,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 +3273,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 +3359,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 +3518,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 +3813,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 +3883,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 +3936,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 +4034,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 +4369,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 +4473,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 +4607,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 +4880,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 +4951,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 +5019,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 +5301,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 +5625,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 +5681,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 +5772,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 +5886,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..5160e93a47 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[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,50 @@ 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. + * @return Constructed element, radius error or construction error. + */ +template +Result MakeCheckedStructuringElementWith(KernelType type, nonstd::span radius, Build&& build) +{ + auto validation = ValidateKernelRadius(radius); + if(validation.invalid()) + { + return ConvertInvalidResult(std::move(validation)); + } + 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 Validates user radii and constructs a structuring element with checked allocation failure handling. + * @param type Kernel shape. + * @param radius X, Y and Z radii in cells. + * @return Constructed element, radius error 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..cda750e223 --- /dev/null +++ b/test/StructuringElementValidationTest.cpp @@ -0,0 +1,323 @@ +#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); + } + SECTION("Invalid radius returns before invoking build") + { + bool invoked = false; + const std::array invalid = {std::numeric_limits::max(), 0, 0}; + auto result = ImageProcessing::detail::MakeCheckedStructuringElementWith(KernelType::Box, invalid, [&invoked](KernelType, nonstd::span) { + invoked = true; + return StructuringElement{}; + }); + SIMPLNX_RESULT_REQUIRE_INVALID(result); + REQUIRE(result.errors().front().code == k_KernelRadiusRangeError); + REQUIRE_FALSE(invoked); + auto publicResult = MakeCheckedStructuringElement(KernelType::Box, invalid); + SIMPLNX_RESULT_REQUIRE_INVALID(publicResult); + REQUIRE(publicResult.errors().front().code == k_KernelRadiusRangeError); + } +} + +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."); + } +} From 15bbc6f2950fe9a295eee74cd3f2f9aa4d81c5ea Mon Sep 17 00:00:00 2001 From: Joey Kleingers Date: Mon, 9 Nov 2026 12:59:28 -0500 Subject: [PATCH 2/6] DOC: Decide NaN and infinity handling by where the value comes from Replace the knowledge-base entry that let the user choose only how a NaN input value is handled with one rule for NaN and both infinities, decided by where the value comes from. It follows the handling in #1888: - Parameters: preflight rejects NaN, and rejects infinity unless the filter documentation gives it a meaning. Values stored into a floating-point array may be NaN or infinity. - Values read from a file: the reader rejects nonfinite values where the format requires finite ones. - Input array values that reach a comparison, range, histogram, threshold, color map, search, index or integer conversion: a Nonfinite Input Handling choice, Error (default) or Warn and Continue. - Element-wise floating-point math passes IEEE results through and documents them. - A computed nonfinite value for an integer output is an error naming the index and output type; finite out-of-range values are clipped with a warning, instead of NaN becoming 0. - An undefined result for degenerate input is a documented NaN. Update the saturating-cast and parameter-validation entries to match. Part of #1873. Signed-off-by: Joey Kleingers --- docs/Coding_Knowledge_Base.md | 146 +++++++++++++++++++++++----------- 1 file changed, 98 insertions(+), 48 deletions(-) diff --git a/docs/Coding_Knowledge_Base.md b/docs/Coding_Knowledge_Base.md index 74cffa0f3b..3e3d2225b0 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,64 @@ 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. + - 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. **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 From 2cd9ecd377d8eaf0aa1b2f2f9c5c07dfb9802109 Mon Sep 17 00:00:00 2001 From: Joey Kleingers Date: Mon, 9 Nov 2026 13:10:12 -0500 Subject: [PATCH 3/6] BUG: Clip adaptive histogram equalization neighbors to the image The Radius of AdaptiveHistogramEqualizationImageFilter is a UInt32 vector, and every neighbor loop walked the whole -r..r box and skipped the neighbors outside the image. A radius near UINT32_MAX made each voxel run billions of empty iterations, so the filter did not finish. Each of the four neighbor loops (the generic and lookup-table plane bodies and the generic and lookup-table 2D block bodies) now computes its bounds clipped to the image before it iterates. The skipped iterations are exactly the ones that were skipped before, in the same order, so the accumulated sum, the in-bounds count and every output value are unchanged. The linear uint8 paths already bounded their traversal and are unchanged. Part of #1873. Signed-off-by: Joey Kleingers --- ...daptiveHistogramEqualizationEngineTest.cpp | 221 ++++++++++++++++ ...veHistogramEqualizationFilterTestUtils.hpp | 240 ++++++++++++++++++ ...veHistogramEqualizationImageFilterTest.cpp | 46 ++++ .../AdaptiveHistogramEqualizationEngine.hpp | 90 +++---- 4 files changed, 546 insertions(+), 51 deletions(-) diff --git a/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationEngineTest.cpp b/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationEngineTest.cpp index 4271e2f433..c546e8c3c2 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("ImageProcessing::AdaptiveHistogramEqualizationEngine: generic plane operation-order identity", "[ImageProcessing][AdaptiveHistogramEqualizationEngine]") +{ + CheckPlaneTraversalIdentity(); +} + +TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationEngine: LUT plane operation-order identity", "[ImageProcessing][AdaptiveHistogramEqualizationEngine]") +{ + CheckPlaneTraversalIdentity(); +} + +TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationEngine: generic 2D block operation-order identity", "[ImageProcessing][AdaptiveHistogramEqualizationEngine]") +{ + CheckBlockTraversalIdentity(); +} + +TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationEngine: LUT 2D block operation-order identity", "[ImageProcessing][AdaptiveHistogramEqualizationEngine]") +{ + CheckBlockTraversalIdentity(); +} + +TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationEngine: bounded-store operation-order identity", "[ImageProcessing][AdaptiveHistogramEqualizationEngine]") +{ + SECTION("generic tiled route") + { + CheckBoundedTraversalIdentity(); + } + SECTION("LUT tiled route") + { + CheckBoundedTraversalIdentity(); + } +} + +TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationEngine: linear uint8 huge-radius positive control", "[ImageProcessing][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..c2ae874e51 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("ImageProcessing::AdaptiveHistogramEqualizationImageFilter: generic huge-radius clipped neighborhood", "[ImageProcessing][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("ImageProcessing::AdaptiveHistogramEqualizationImageFilter: LUT huge-radius clipped neighborhood", "[ImageProcessing][AdaptiveHistogramEqualizationImageFilter]") +{ + constexpr uint32 huge = std::numeric_limits::max(); + CheckHugeRadiusFilter(3, 3, 2, {huge, huge, huge}, {2, 2, 1}); +} diff --git a/src/simplnx/Utilities/ImageProcessing/AdaptiveHistogramEqualizationEngine.hpp b/src/simplnx/Utilities/ImageProcessing/AdaptiveHistogramEqualizationEngine.hpp index cfbc9c4061..01140e6d18 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 xi = static_cast(x); + const int64 yi = static_cast(y); + const int64 dyLo = std::max(-radiusYi, -yi); + const int64 dyHi = std::min(radiusYi, dimYi - 1 - yi); + const int64 dxLo = std::max(-radiusXi, -xi); + const int64 dxHi = std::min(radiusXi, dimXi - 1 - xi); 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 xi = static_cast(x); + const int64 yi = static_cast(y); + const int64 dyLo = std::max(-radiusYi, -yi); + const int64 dyHi = std::min(radiusYi, dimYi - 1 - yi); + const int64 dxLo = std::max(-radiusXi, -xi); + const int64 dxHi = std::min(radiusXi, dimXi - 1 - xi); 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); From e40dc90a46ac0ed9d41c92b07e8fefc917d45766 Mon Sep 17 00:00:00 2001 From: Joey Kleingers Date: Mon, 9 Nov 2026 15:31:28 -0500 Subject: [PATCH 4/6] REV: Restore the nonfinite skip rule and clear new clang-tidy findings - Coding knowledge base: Warn and Continue excludes nonfinite values from the contributing samples and counts of reductions and neighborhood operations. The nonfinite-handling rules apply to new filters and to filters a change already fixes; bringing an existing filter's output type or failure behavior in line is a breaking change that its pull request names. - Adaptive histogram equalization: rename the signed coordinates xi and yi to signedX and signedY. - Morphology and structuring-element guards: camelCase local constants, checked std::array access, a kernel parameter name in the two new layout helpers, an explicit int64 slice product and parentheses in the bounding-box extents. No behavior change. --- docs/Coding_Knowledge_Base.md | 6 ++- .../AdaptiveHistogramEqualizationEngine.hpp | 24 ++++----- .../ImageProcessing/MorphologyEngine.hpp | 50 +++++++++---------- .../ImageProcessing/StructuringElement.hpp | 6 +-- 4 files changed, 45 insertions(+), 41 deletions(-) diff --git a/docs/Coding_Knowledge_Base.md b/docs/Coding_Knowledge_Base.md index 3e3d2225b0..2f6f86aed6 100644 --- a/docs/Coding_Knowledge_Base.md +++ b/docs/Coding_Knowledge_Base.md @@ -692,7 +692,8 @@ error and the clipping warning of `SmoothingRecursiveGaussianImageFilter` and `C 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. + 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 @@ -702,6 +703,9 @@ error and the clipping warning of `SmoothingRecursiveGaussianImageFilter` and `C - **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 diff --git a/src/simplnx/Utilities/ImageProcessing/AdaptiveHistogramEqualizationEngine.hpp b/src/simplnx/Utilities/ImageProcessing/AdaptiveHistogramEqualizationEngine.hpp index 01140e6d18..0c7994bcd1 100644 --- a/src/simplnx/Utilities/ImageProcessing/AdaptiveHistogramEqualizationEngine.hpp +++ b/src/simplnx/Utilities/ImageProcessing/AdaptiveHistogramEqualizationEngine.hpp @@ -701,12 +701,12 @@ struct AdaptiveHistogramEqualization2DBlockBody const usize localY = tuple / outputWidth; const usize x = outputXBegin + localX; const usize y = outputYBegin + localY; - const int64 xi = static_cast(x); - const int64 yi = static_cast(y); - const int64 dyLo = std::max(-radiusYi, -yi); - const int64 dyHi = std::min(radiusYi, dimYi - 1 - yi); - const int64 dxLo = std::max(-radiusXi, -xi); - const int64 dxHi = std::min(radiusXi, dimXi - 1 - xi); + 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; @@ -773,12 +773,12 @@ struct AdaptiveHistogramEqualizationLut2DBlockBody const usize localY = tuple / outputWidth; const usize x = outputXBegin + localX; const usize y = outputYBegin + localY; - const int64 xi = static_cast(x); - const int64 yi = static_cast(y); - const int64 dyLo = std::max(-radiusYi, -yi); - const int64 dyHi = std::min(radiusYi, dimYi - 1 - yi); - const int64 dxLo = std::max(-radiusXi, -xi); - const int64 dxHi = std::min(radiusXi, dimXi - 1 - xi); + 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; diff --git a/src/simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp b/src/simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp index cf43dba00c..aeca6618ef 100644 --- a/src/simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp +++ b/src/simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp @@ -88,36 +88,36 @@ inline Result<> ValidateMorphologyLayout(const SizeVec3& dims, nonstd::span(std::numeric_limits::max()); + 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] > k_SignedMax - static_cast(radius[axis]) - 1) + 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[axis], k_SignedMax)); + StringUtilities::formatDimensions3D(dims), radius[0], radius[1], radius[2], paddedDims[axis], radius[axis], axes.at(axis), signedMax)); } } - if(paddedDims[0] != 0 && paddedDims[1] > k_SignedMax / paddedDims[0]) + 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], k_SignedMax)); + 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] > k_SignedMax / plane) + 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], k_SignedMax)); + 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) @@ -133,15 +133,15 @@ inline Result<> ValidateMorphologyLayout(const SizeVec3& dims, nonstd::span ValidateMorphologyLayout(const SizeVec3& dims, const StructuringElement& se, bool safeBorder, usize elementBytes) +inline Result<> ValidateMorphologyLayout(const SizeVec3& dims, const StructuringElement& kernel, bool safeBorder, usize elementBytes) { - const std::array radius = {static_cast(std::max(0, se.radius[0])), static_cast(std::max(0, se.radius[1])), - static_cast(std::max(0, se.radius[2]))}; + 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); } @@ -207,23 +207,23 @@ 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 se Rasterized offsets. + * @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& se) +inline bool MorphologyFlatFoldIsRepresentable(const SizeVec3& dims, const StructuringElement& kernel) { - constexpr uint64 k_Max = static_cast(std::numeric_limits::max()); - if(dims[0] > k_Max || dims[1] > k_Max || dims[2] > k_Max || (dims[0] != 0 && dims[1] > k_Max / dims[0])) + 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] > k_Max / slice) + if(slice != 0 && dims[2] > signedMax / slice) { return false; } const uint64 volume = slice * dims[2]; - for(const SEOffset& offset : se.offsets) + for(const SEOffset& offset : kernel.offsets) { const std::array values = {offset.dx, offset.dy, offset.dz}; const std::array strides = {1, dims[0], slice}; @@ -231,12 +231,12 @@ inline bool MorphologyFlatFoldIsRepresentable(const SizeVec3& dims, const Struct for(usize step = 0; step < 3; ++step) { const usize axis = 2 - step; - const uint64 magnitude = static_cast(values[axis] < 0 ? -values[axis] : values[axis]); - if(magnitude != 0 && strides[axis] > k_Max / magnitude) + 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[axis] < 0 ? -static_cast(magnitude * strides[axis]) : static_cast(magnitude * strides[axis]); + 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; @@ -244,7 +244,7 @@ inline bool MorphologyFlatFoldIsRepresentable(const SizeVec3& dims, const Struct delta += product; } const uint64 magnitude = delta < 0 ? static_cast(-(delta + 1)) + 1 : static_cast(delta); - if(magnitude > k_Max - volume) + if(magnitude > signedMax - volume) { return false; } @@ -1401,7 +1401,7 @@ inline std::vector MakeMorphologyFlatFoldOffsets(const { assert(MorphologyFlatFoldIsRepresentable(dims, se)); const int64 dimX = static_cast(dims[0]); - const int64 sliceValues = static_cast(dims[0] * dims[1]); + 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) @@ -2052,8 +2052,8 @@ bool PackBinaryMorphologyStagedPlanes(const T* stagedInput, BinaryMorphWord* pac */ inline int64 MorphologyPackedWordEnd(int64 xStart, int64 rowEnd) { - constexpr int64 k_WordBits = std::numeric_limits::digits; - return xStart > std::numeric_limits::max() - k_WordBits ? rowEnd : std::min(rowEnd, xStart + k_WordBits); + constexpr int64 wordBits = std::numeric_limits::digits; + return xStart > std::numeric_limits::max() - wordBits ? rowEnd : std::min(rowEnd, xStart + wordBits); } /** diff --git a/src/simplnx/Utilities/ImageProcessing/StructuringElement.hpp b/src/simplnx/Utilities/ImageProcessing/StructuringElement.hpp index 5160e93a47..3829187fbd 100644 --- a/src/simplnx/Utilities/ImageProcessing/StructuringElement.hpp +++ b/src/simplnx/Utilities/ImageProcessing/StructuringElement.hpp @@ -83,13 +83,13 @@ inline Result<> ValidateKernelRadius(nonstd::span radius) { if(radius[axis] > k_MaxKernelRadius) { - return MakeErrorResult(k_KernelRadiusRangeError, fmt::format("Kernel Radius {}={} exceeds the maximum {} cells. Reduce this radius.", axes[axis], 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; + const uint64 extent = (2 * static_cast(value)) + 1; if(count > std::numeric_limits::max() / extent) { return MakeErrorResult(k_KernelRadiusCountOverflowError, @@ -186,7 +186,7 @@ inline StructuringElement MakeStructuringElement(KernelType type, const std::arr bool boundFits = true; for(const int32 value : radius) { - const uint64 extent = 2 * static_cast(value) + 1; + const uint64 extent = (2 * static_cast(value)) + 1; if(extent > std::numeric_limits::max() || bound > std::numeric_limits::max() / extent) { boundFits = false; From 31aee9fc69ba85062ef1cd6332744dc2aa3e0458 Mon Sep 17 00:00:00 2001 From: Joey Kleingers Date: Wed, 11 Nov 2026 15:03:33 -0500 Subject: [PATCH 5/6] REV: Check kernel radii only in preflight Filter preflight is the one place a filter's inputs are checked; the shared morphology helpers do not repeat those checks. - MakeCheckedStructuringElement() and ValidateMorphologyLayout() no longer re-run ValidateKernelRadius(); they document a validated radius as a precondition. The structuring element still converts allocation failures to an error, and the layout checks on the final geometry dimensions still run in preflight and execute. - The kernel-radius tests also execute each filter with an invalid radius and check that it fails with the preflight code, creates no output and leaves the input unchanged. The test that called the helper directly with an invalid radius is removed. Signed-off-by: Joey Kleingers --- .../test/MorphologyFilterTestUtils.hpp | 10 ++++++++++ .../ImageProcessing/MorphologyEngine.hpp | 11 ++++------- .../ImageProcessing/StructuringElement.hpp | 13 +++++-------- test/StructuringElementValidationTest.cpp | 15 --------------- 4 files changed, 19 insertions(+), 30 deletions(-) diff --git a/src/Plugins/NXImageProcessing/test/MorphologyFilterTestUtils.hpp b/src/Plugins/NXImageProcessing/test/MorphologyFilterTestUtils.hpp index 37c8834a25..cf9408e749 100644 --- a/src/Plugins/NXImageProcessing/test/MorphologyFilterTestUtils.hpp +++ b/src/Plugins/NXImageProcessing/test/MorphologyFilterTestUtils.hpp @@ -809,6 +809,16 @@ void RequireKernelRadiusPreflight() 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") diff --git a/src/simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp b/src/simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp index aeca6618ef..74ac05fe56 100644 --- a/src/simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp +++ b/src/simplnx/Utilities/ImageProcessing/MorphologyEngine.hpp @@ -69,16 +69,12 @@ inline constexpr int32 k_MorphologyByteCountError = -88009; * @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. - * @return Radius or layout error if counts, coordinates or typed byte counts are unrepresentable. + * @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) { - auto radiusResult = ValidateKernelRadius(radius); - if(radiusResult.invalid()) - { - return radiusResult; - } SizeVec3 paddedDims = dims; constexpr std::array axes = {"X", "Y", "Z"}; for(usize axis = 0; axis < 3; ++axis) @@ -136,7 +132,8 @@ inline Result<> ValidateMorphologyLayout(const SizeVec3& dims, nonstd::span ValidateMorphologyLayout(const SizeVec3& dims, const StructuringElement& kernel, bool safeBorder, usize elementBytes) { diff --git a/src/simplnx/Utilities/ImageProcessing/StructuringElement.hpp b/src/simplnx/Utilities/ImageProcessing/StructuringElement.hpp index 3829187fbd..e861d8bc1d 100644 --- a/src/simplnx/Utilities/ImageProcessing/StructuringElement.hpp +++ b/src/simplnx/Utilities/ImageProcessing/StructuringElement.hpp @@ -250,16 +250,12 @@ namespace detail * @param type Kernel shape passed to build. * @param radius User-supplied radii in cells. * @param build Construction callable. Tests can inject allocation exceptions here. - * @return Constructed element, radius error or construction error. + * @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) { - auto validation = ValidateKernelRadius(radius); - if(validation.invalid()) - { - return ConvertInvalidResult(std::move(validation)); - } try { return {std::forward(build)(type, radius)}; @@ -277,10 +273,11 @@ Result MakeCheckedStructuringElementWith(KernelType type, no } // namespace detail /** - * @brief Validates user radii and constructs a structuring element with checked allocation failure handling. + * @brief Constructs a structuring element with checked allocation failure handling. * @param type Kernel shape. * @param radius X, Y and Z radii in cells. - * @return Constructed element, radius error or construction error. + * @pre radius has exactly three components and satisfies ValidateKernelRadius(). + * @return Constructed element or construction error. */ inline Result MakeCheckedStructuringElement(KernelType type, nonstd::span radius) { diff --git a/test/StructuringElementValidationTest.cpp b/test/StructuringElementValidationTest.cpp index cda750e223..15e467bf90 100644 --- a/test/StructuringElementValidationTest.cpp +++ b/test/StructuringElementValidationTest.cpp @@ -118,21 +118,6 @@ TEST_CASE("simplnx::StructuringElement: Checked construction failures", "[simpln SIMPLNX_RESULT_REQUIRE_INVALID(result); REQUIRE(result.errors().front().code == k_KernelConstructionError); } - SECTION("Invalid radius returns before invoking build") - { - bool invoked = false; - const std::array invalid = {std::numeric_limits::max(), 0, 0}; - auto result = ImageProcessing::detail::MakeCheckedStructuringElementWith(KernelType::Box, invalid, [&invoked](KernelType, nonstd::span) { - invoked = true; - return StructuringElement{}; - }); - SIMPLNX_RESULT_REQUIRE_INVALID(result); - REQUIRE(result.errors().front().code == k_KernelRadiusRangeError); - REQUIRE_FALSE(invoked); - auto publicResult = MakeCheckedStructuringElement(KernelType::Box, invalid); - SIMPLNX_RESULT_REQUIRE_INVALID(publicResult); - REQUIRE(publicResult.errors().front().code == k_KernelRadiusRangeError); - } } TEST_CASE("simplnx::StructuringElement: Ordered offset oracles", "[simplnx][StructuringElement]") From 54424d4857ea05331a9a922516038760406c431e Mon Sep 17 00:00:00 2001 From: Michael Jackson Date: Thu, 12 Nov 2026 19:10:24 -0500 Subject: [PATCH 6/6] TEST: Use the NXImageProcessing plugin names after the rebase Signed-off-by: Michael Jackson --- .../test/AdaptiveHistogramEqualizationEngineTest.cpp | 12 ++++++------ .../AdaptiveHistogramEqualizationImageFilterTest.cpp | 4 ++-- .../test/BinaryDilateImageFilterTest.cpp | 4 ++-- .../test/BinaryErodeImageFilterTest.cpp | 4 ++-- .../BinaryMorphologicalClosingImageFilterTest.cpp | 6 +++--- .../BinaryMorphologicalOpeningImageFilterTest.cpp | 4 ++-- .../BinaryOpeningByReconstructionImageFilterTest.cpp | 4 ++-- .../test/BlackTopHatImageFilterTest.cpp | 4 ++-- .../test/ClosingByReconstructionImageFilterTest.cpp | 4 ++-- .../test/DilateObjectMorphologyImageFilterTest.cpp | 4 ++-- .../test/ErodeObjectMorphologyImageFilterTest.cpp | 4 ++-- .../test/GrayscaleDilateImageFilterTest.cpp | 4 ++-- .../test/GrayscaleErodeImageFilterTest.cpp | 4 ++-- .../GrayscaleMorphologicalClosingImageFilterTest.cpp | 6 +++--- .../GrayscaleMorphologicalOpeningImageFilterTest.cpp | 4 ++-- .../test/MorphologicalGradientImageFilterTest.cpp | 4 ++-- .../NXImageProcessing/test/MorphologyEngineTest.cpp | 4 ++-- .../test/OpeningByReconstructionImageFilterTest.cpp | 4 ++-- .../test/WhiteTopHatImageFilterTest.cpp | 4 ++-- 19 files changed, 44 insertions(+), 44 deletions(-) diff --git a/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationEngineTest.cpp b/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationEngineTest.cpp index c546e8c3c2..cf9118494e 100644 --- a/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationEngineTest.cpp +++ b/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationEngineTest.cpp @@ -708,27 +708,27 @@ void CheckBoundedTraversalIdentity() } } // namespace -TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationEngine: generic plane operation-order identity", "[ImageProcessing][AdaptiveHistogramEqualizationEngine]") +TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationEngine: generic plane operation-order identity", "[NXImageProcessing][AdaptiveHistogramEqualizationEngine]") { CheckPlaneTraversalIdentity(); } -TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationEngine: LUT plane operation-order identity", "[ImageProcessing][AdaptiveHistogramEqualizationEngine]") +TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationEngine: LUT plane operation-order identity", "[NXImageProcessing][AdaptiveHistogramEqualizationEngine]") { CheckPlaneTraversalIdentity(); } -TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationEngine: generic 2D block operation-order identity", "[ImageProcessing][AdaptiveHistogramEqualizationEngine]") +TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationEngine: generic 2D block operation-order identity", "[NXImageProcessing][AdaptiveHistogramEqualizationEngine]") { CheckBlockTraversalIdentity(); } -TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationEngine: LUT 2D block operation-order identity", "[ImageProcessing][AdaptiveHistogramEqualizationEngine]") +TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationEngine: LUT 2D block operation-order identity", "[NXImageProcessing][AdaptiveHistogramEqualizationEngine]") { CheckBlockTraversalIdentity(); } -TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationEngine: bounded-store operation-order identity", "[ImageProcessing][AdaptiveHistogramEqualizationEngine]") +TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationEngine: bounded-store operation-order identity", "[NXImageProcessing][AdaptiveHistogramEqualizationEngine]") { SECTION("generic tiled route") { @@ -740,7 +740,7 @@ TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationEngine: bounded-store o } } -TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationEngine: linear uint8 huge-radius positive control", "[ImageProcessing][AdaptiveHistogramEqualizationEngine]") +TEST_CASE("NXImageProcessing::AdaptiveHistogramEqualizationEngine: linear uint8 huge-radius positive control", "[NXImageProcessing][AdaptiveHistogramEqualizationEngine]") { constexpr usize huge = std::numeric_limits::max(); SECTION("3D ring") diff --git a/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationImageFilterTest.cpp index c2ae874e51..69a22113b4 100644 --- a/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/AdaptiveHistogramEqualizationImageFilterTest.cpp @@ -277,7 +277,7 @@ void CheckHugeRadiusFilter(usize dimX, usize dimY, usize dimZ, const std::vector } } // namespace -TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationImageFilter: generic huge-radius clipped neighborhood", "[ImageProcessing][AdaptiveHistogramEqualizationImageFilter]") +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. @@ -288,7 +288,7 @@ TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationImageFilter: generic hu } } -TEST_CASE("ImageProcessing::AdaptiveHistogramEqualizationImageFilter: LUT huge-radius clipped neighborhood", "[ImageProcessing][AdaptiveHistogramEqualizationImageFilter]") +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 f35e789c9a..b59c9c429d 100644 --- a/src/Plugins/NXImageProcessing/test/BinaryDilateImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/BinaryDilateImageFilterTest.cpp @@ -234,12 +234,12 @@ TEST_CASE("NXImageProcessing::BinaryDilateImageFilter: Preflight rejects non-sca morph_test::RequirePreflightRejectsNonScalar(-8460, morph_test::BinaryKernelParamSetter(1.0, 0.0, /*boundaryToForeground=*/false)); } -TEST_CASE("ImageProcessing::BinaryDilateImageFilter: Kernel Radius representability", "[ImageProcessing][BinaryDilateImageFilter]") +TEST_CASE("NXImageProcessing::BinaryDilateImageFilter: Kernel Radius representability", "[NXImageProcessing][BinaryDilateImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::BinaryDilateImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][BinaryDilateImageFilter]") +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 0d18478ebb..9e6909371f 100644 --- a/src/Plugins/NXImageProcessing/test/BinaryErodeImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/BinaryErodeImageFilterTest.cpp @@ -257,12 +257,12 @@ TEST_CASE("NXImageProcessing::BinaryErodeImageFilter: Preflight rejects non-scal morph_test::RequirePreflightRejectsNonScalar(-8440, morph_test::BinaryKernelParamSetter(1.0, 0.0, /*boundaryToForeground=*/false)); } -TEST_CASE("ImageProcessing::BinaryErodeImageFilter: Kernel Radius representability", "[ImageProcessing][BinaryErodeImageFilter]") +TEST_CASE("NXImageProcessing::BinaryErodeImageFilter: Kernel Radius representability", "[NXImageProcessing][BinaryErodeImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::BinaryErodeImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][BinaryErodeImageFilter]") +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 a41aa6706c..bcd480f01c 100644 --- a/src/Plugins/NXImageProcessing/test/BinaryMorphologicalClosingImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/BinaryMorphologicalClosingImageFilterTest.cpp @@ -243,17 +243,17 @@ TEST_CASE("NXImageProcessing::BinaryMorphologicalClosingImageFilter: Preflight r morph_test::RequirePreflightRejectsNonScalar(-8490, ClosingKernelParamSetter(1.0, /*safeBorder=*/true)); } -TEST_CASE("ImageProcessing::BinaryMorphologicalClosingImageFilter: Kernel Radius representability", "[ImageProcessing][BinaryMorphologicalClosingImageFilter]") +TEST_CASE("NXImageProcessing::BinaryMorphologicalClosingImageFilter: Kernel Radius representability", "[NXImageProcessing][BinaryMorphologicalClosingImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::BinaryMorphologicalClosingImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][BinaryMorphologicalClosingImageFilter]") +TEST_CASE("NXImageProcessing::BinaryMorphologicalClosingImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][BinaryMorphologicalClosingImageFilter]") { morph_test::RequireOrdinaryKernelRadius({5, 5, 5}); } -TEST_CASE("ImageProcessing::BinaryMorphologicalClosingImageFilter: Kernel Radius layout preflight", "[ImageProcessing][BinaryMorphologicalClosingImageFilter]") +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 38c7c66651..b70b6aaf2c 100644 --- a/src/Plugins/NXImageProcessing/test/BinaryMorphologicalOpeningImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/BinaryMorphologicalOpeningImageFilterTest.cpp @@ -235,12 +235,12 @@ TEST_CASE("NXImageProcessing::BinaryMorphologicalOpeningImageFilter: Preflight r morph_test::RequirePreflightRejectsNonScalar(-8480, OpeningKernelParamSetter(1.0, 0.0)); } -TEST_CASE("ImageProcessing::BinaryMorphologicalOpeningImageFilter: Kernel Radius representability", "[ImageProcessing][BinaryMorphologicalOpeningImageFilter]") +TEST_CASE("NXImageProcessing::BinaryMorphologicalOpeningImageFilter: Kernel Radius representability", "[NXImageProcessing][BinaryMorphologicalOpeningImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::BinaryMorphologicalOpeningImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][BinaryMorphologicalOpeningImageFilter]") +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 c7e9dc607e..5694810d82 100644 --- a/src/Plugins/NXImageProcessing/test/BinaryOpeningByReconstructionImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/BinaryOpeningByReconstructionImageFilterTest.cpp @@ -350,12 +350,12 @@ TEST_CASE("NXImageProcessing::BinaryOpeningByReconstructionImageFilter: ITK real REQUIRE(executeResult.result.errors().front().code == -8002); // the documented binary-input contract error } -TEST_CASE("ImageProcessing::BinaryOpeningByReconstructionImageFilter: Kernel Radius representability", "[ImageProcessing][BinaryOpeningByReconstructionImageFilter]") +TEST_CASE("NXImageProcessing::BinaryOpeningByReconstructionImageFilter: Kernel Radius representability", "[NXImageProcessing][BinaryOpeningByReconstructionImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::BinaryOpeningByReconstructionImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][BinaryOpeningByReconstructionImageFilter]") +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 c7060844fc..56ce2a35a0 100644 --- a/src/Plugins/NXImageProcessing/test/BlackTopHatImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/BlackTopHatImageFilterTest.cpp @@ -169,12 +169,12 @@ TEST_CASE("NXImageProcessing::BlackTopHatImageFilter: Preflight rejects non-scal morph_test::RequirePreflightRejectsNonScalar(-8420, morph_test::CompositeKernelParamSetter(/*safeBorder=*/true)); } -TEST_CASE("ImageProcessing::BlackTopHatImageFilter: Kernel Radius representability", "[ImageProcessing][BlackTopHatImageFilter]") +TEST_CASE("NXImageProcessing::BlackTopHatImageFilter: Kernel Radius representability", "[NXImageProcessing][BlackTopHatImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::BlackTopHatImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][BlackTopHatImageFilter]") +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 26bdc3342a..b10d851a73 100644 --- a/src/Plugins/NXImageProcessing/test/ClosingByReconstructionImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/ClosingByReconstructionImageFilterTest.cpp @@ -154,12 +154,12 @@ TEST_CASE("NXImageProcessing::ClosingByReconstructionImageFilter: ITK real-image }); } -TEST_CASE("ImageProcessing::ClosingByReconstructionImageFilter: Kernel Radius representability", "[ImageProcessing][ClosingByReconstructionImageFilter]") +TEST_CASE("NXImageProcessing::ClosingByReconstructionImageFilter: Kernel Radius representability", "[NXImageProcessing][ClosingByReconstructionImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::ClosingByReconstructionImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][ClosingByReconstructionImageFilter]") +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 a995a99a41..499d757fef 100644 --- a/src/Plugins/NXImageProcessing/test/DilateObjectMorphologyImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/DilateObjectMorphologyImageFilterTest.cpp @@ -388,12 +388,12 @@ TEST_CASE("NXImageProcessing::DilateObjectMorphologyImageFilter: Preflight rejec omt::RequirePreflightRejectsNonScalar(-8520, omt::DilateParamSetter(1.0)); } -TEST_CASE("ImageProcessing::DilateObjectMorphologyImageFilter: Kernel Radius representability", "[ImageProcessing][DilateObjectMorphologyImageFilter]") +TEST_CASE("NXImageProcessing::DilateObjectMorphologyImageFilter: Kernel Radius representability", "[NXImageProcessing][DilateObjectMorphologyImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::DilateObjectMorphologyImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][DilateObjectMorphologyImageFilter]") +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 63800139f5..604bd5201a 100644 --- a/src/Plugins/NXImageProcessing/test/ErodeObjectMorphologyImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/ErodeObjectMorphologyImageFilterTest.cpp @@ -389,12 +389,12 @@ TEST_CASE("NXImageProcessing::ErodeObjectMorphologyImageFilter: Preflight reject omt::RequirePreflightRejectsNonScalar(-8530, omt::ErodeParamSetter(1.0, 0.0)); } -TEST_CASE("ImageProcessing::ErodeObjectMorphologyImageFilter: Kernel Radius representability", "[ImageProcessing][ErodeObjectMorphologyImageFilter]") +TEST_CASE("NXImageProcessing::ErodeObjectMorphologyImageFilter: Kernel Radius representability", "[NXImageProcessing][ErodeObjectMorphologyImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::ErodeObjectMorphologyImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][ErodeObjectMorphologyImageFilter]") +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 13e81bccda..fcbaea70fe 100644 --- a/src/Plugins/NXImageProcessing/test/GrayscaleDilateImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/GrayscaleDilateImageFilterTest.cpp @@ -161,12 +161,12 @@ TEST_CASE("NXImageProcessing::GrayscaleDilateImageFilter: Preflight rejects non- morph_test::RequirePreflightRejectsNonScalar(-8370, morph_test::DefaultKernelParamSetter()); } -TEST_CASE("ImageProcessing::GrayscaleDilateImageFilter: Kernel Radius representability", "[ImageProcessing][GrayscaleDilateImageFilter]") +TEST_CASE("NXImageProcessing::GrayscaleDilateImageFilter: Kernel Radius representability", "[NXImageProcessing][GrayscaleDilateImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::GrayscaleDilateImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][GrayscaleDilateImageFilter]") +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 dbabd072fc..8b800b5af8 100644 --- a/src/Plugins/NXImageProcessing/test/GrayscaleErodeImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/GrayscaleErodeImageFilterTest.cpp @@ -160,12 +160,12 @@ TEST_CASE("NXImageProcessing::GrayscaleErodeImageFilter: Preflight rejects non-s morph_test::RequirePreflightRejectsNonScalar(-8360, morph_test::DefaultKernelParamSetter()); } -TEST_CASE("ImageProcessing::GrayscaleErodeImageFilter: Kernel Radius representability", "[ImageProcessing][GrayscaleErodeImageFilter]") +TEST_CASE("NXImageProcessing::GrayscaleErodeImageFilter: Kernel Radius representability", "[NXImageProcessing][GrayscaleErodeImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::GrayscaleErodeImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][GrayscaleErodeImageFilter]") +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 d70c62abc9..af93327125 100644 --- a/src/Plugins/NXImageProcessing/test/GrayscaleMorphologicalClosingImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/GrayscaleMorphologicalClosingImageFilterTest.cpp @@ -172,17 +172,17 @@ TEST_CASE("NXImageProcessing::GrayscaleMorphologicalClosingImageFilter: Prefligh -8400, morph_test::CompositeKernelParamSetter(/*safeBorder=*/true)); } -TEST_CASE("ImageProcessing::GrayscaleMorphologicalClosingImageFilter: Kernel Radius representability", "[ImageProcessing][GrayscaleMorphologicalClosingImageFilter]") +TEST_CASE("NXImageProcessing::GrayscaleMorphologicalClosingImageFilter: Kernel Radius representability", "[NXImageProcessing][GrayscaleMorphologicalClosingImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::GrayscaleMorphologicalClosingImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][GrayscaleMorphologicalClosingImageFilter]") +TEST_CASE("NXImageProcessing::GrayscaleMorphologicalClosingImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][GrayscaleMorphologicalClosingImageFilter]") { morph_test::RequireOrdinaryKernelRadius({5, 5, 5}); } -TEST_CASE("ImageProcessing::GrayscaleMorphologicalClosingImageFilter: Kernel Radius layout preflight", "[ImageProcessing][GrayscaleMorphologicalClosingImageFilter]") +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 db1507b2e9..d5a8f7d0fd 100644 --- a/src/Plugins/NXImageProcessing/test/GrayscaleMorphologicalOpeningImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/GrayscaleMorphologicalOpeningImageFilterTest.cpp @@ -187,12 +187,12 @@ TEST_CASE("NXImageProcessing::GrayscaleMorphologicalOpeningImageFilter: Prefligh -8390, morph_test::CompositeKernelParamSetter(/*safeBorder=*/true)); } -TEST_CASE("ImageProcessing::GrayscaleMorphologicalOpeningImageFilter: Kernel Radius representability", "[ImageProcessing][GrayscaleMorphologicalOpeningImageFilter]") +TEST_CASE("NXImageProcessing::GrayscaleMorphologicalOpeningImageFilter: Kernel Radius representability", "[NXImageProcessing][GrayscaleMorphologicalOpeningImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::GrayscaleMorphologicalOpeningImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][GrayscaleMorphologicalOpeningImageFilter]") +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 f7a39d6b00..bf678ac6d4 100644 --- a/src/Plugins/NXImageProcessing/test/MorphologicalGradientImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/MorphologicalGradientImageFilterTest.cpp @@ -203,12 +203,12 @@ TEST_CASE("NXImageProcessing::MorphologicalGradientImageFilter: Preflight reject morph_test::RequirePreflightRejectsNonScalar(-8380, morph_test::DefaultKernelParamSetter()); } -TEST_CASE("ImageProcessing::MorphologicalGradientImageFilter: Kernel Radius representability", "[ImageProcessing][MorphologicalGradientImageFilter]") +TEST_CASE("NXImageProcessing::MorphologicalGradientImageFilter: Kernel Radius representability", "[NXImageProcessing][MorphologicalGradientImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::MorphologicalGradientImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][MorphologicalGradientImageFilter]") +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 57fc637403..7948cfd58e 100644 --- a/src/Plugins/NXImageProcessing/test/MorphologyEngineTest.cpp +++ b/src/Plugins/NXImageProcessing/test/MorphologyEngineTest.cpp @@ -2519,7 +2519,7 @@ TEST_CASE("NXImageProcessing::MorphologyEngine: fused SafeBorder crop-subtract u REQUIRE(actual == expected); } -TEST_CASE("ImageProcessing::MorphologyEngine: Kernel Radius flat-fold representability", "[ImageProcessing][MorphologyEngine]") +TEST_CASE("NXImageProcessing::MorphologyEngine: Kernel Radius flat-fold representability", "[NXImageProcessing][MorphologyEngine]") { using namespace ImageProcessing; SECTION("Delta exceeds int64") @@ -2544,7 +2544,7 @@ TEST_CASE("ImageProcessing::MorphologyEngine: Kernel Radius flat-fold representa } } -TEST_CASE("ImageProcessing::MorphologyEngine: Kernel Radius layout before allocation", "[ImageProcessing][MorphologyEngine]") +TEST_CASE("NXImageProcessing::MorphologyEngine: Kernel Radius layout before allocation", "[NXImageProcessing][MorphologyEngine]") { const std::atomic_bool cancel = false; const IFilter::MessageHandler handler; diff --git a/src/Plugins/NXImageProcessing/test/OpeningByReconstructionImageFilterTest.cpp b/src/Plugins/NXImageProcessing/test/OpeningByReconstructionImageFilterTest.cpp index d5e1a3d9de..55bee3f3a4 100644 --- a/src/Plugins/NXImageProcessing/test/OpeningByReconstructionImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/OpeningByReconstructionImageFilterTest.cpp @@ -156,12 +156,12 @@ TEST_CASE("NXImageProcessing::OpeningByReconstructionImageFilter: ITK real-image }); } -TEST_CASE("ImageProcessing::OpeningByReconstructionImageFilter: Kernel Radius representability", "[ImageProcessing][OpeningByReconstructionImageFilter]") +TEST_CASE("NXImageProcessing::OpeningByReconstructionImageFilter: Kernel Radius representability", "[NXImageProcessing][OpeningByReconstructionImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::OpeningByReconstructionImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][OpeningByReconstructionImageFilter]") +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 8610da9c1d..a75464a830 100644 --- a/src/Plugins/NXImageProcessing/test/WhiteTopHatImageFilterTest.cpp +++ b/src/Plugins/NXImageProcessing/test/WhiteTopHatImageFilterTest.cpp @@ -169,12 +169,12 @@ TEST_CASE("NXImageProcessing::WhiteTopHatImageFilter: Preflight rejects non-scal morph_test::RequirePreflightRejectsNonScalar(-8410, morph_test::CompositeKernelParamSetter(/*safeBorder=*/true)); } -TEST_CASE("ImageProcessing::WhiteTopHatImageFilter: Kernel Radius representability", "[ImageProcessing][WhiteTopHatImageFilter]") +TEST_CASE("NXImageProcessing::WhiteTopHatImageFilter: Kernel Radius representability", "[NXImageProcessing][WhiteTopHatImageFilter]") { morph_test::RequireKernelRadiusPreflight(); } -TEST_CASE("ImageProcessing::WhiteTopHatImageFilter: Ordinary Kernel Radius control", "[ImageProcessing][WhiteTopHatImageFilter]") +TEST_CASE("NXImageProcessing::WhiteTopHatImageFilter: Ordinary Kernel Radius control", "[NXImageProcessing][WhiteTopHatImageFilter]") { morph_test::RequireOrdinaryKernelRadius({5, 0, 5}); }