From f136e8c1968c349b33dbe19d73009a48f3eab7f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jon=20Haitz=20Legarreta=20Gorro=C3=B1o?= Date: Tue, 19 Jan 2021 20:17:33 -0500 Subject: [PATCH 1/5] BUG: Fix Superclass name in RTTI macro Fix Superclass name in RTTI macro. --- .../include/itkVanHerkGilWermanErodeDilateImageFilter.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/Filtering/MathematicalMorphology/include/itkVanHerkGilWermanErodeDilateImageFilter.h b/Modules/Filtering/MathematicalMorphology/include/itkVanHerkGilWermanErodeDilateImageFilter.h index 968f0b224fd..39fb28d102d 100644 --- a/Modules/Filtering/MathematicalMorphology/include/itkVanHerkGilWermanErodeDilateImageFilter.h +++ b/Modules/Filtering/MathematicalMorphology/include/itkVanHerkGilWermanErodeDilateImageFilter.h @@ -70,7 +70,7 @@ class ITK_TEMPLATE_EXPORT VanHerkGilWermanErodeDilateImageFilter : public Kernel itkNewMacro(Self); /** Runtime information support. */ - itkTypeMacro(VanHerkGilWermanErodeDilateImageFilter, ImageToImageFilter); + itkTypeMacro(VanHerkGilWermanErodeDilateImageFilter, KernelImageFilter); /** Set/Get the boundary value. */ itkSetMacro(Boundary, InputImagePixelType); From 135141bff447e5b04f34e5d6a72ee20fff142802 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jon=20Haitz=20Legarreta=20Gorro=C3=B1o?= Date: Sun, 24 Jan 2021 19:33:38 -0500 Subject: [PATCH 2/5] COMP: Remove duplicate include file Remove duplicate include file. --- .../include/itkDisplacementFieldJacobianDeterminantFilter.hxx | 1 - 1 file changed, 1 deletion(-) diff --git a/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.hxx b/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.hxx index ea9d4f2a487..03a6d092e67 100644 --- a/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.hxx +++ b/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.hxx @@ -26,7 +26,6 @@ #include "itkTotalProgressReporter.h" #include "itkCastImageFilter.h" -#include "itkMath.h" #include "itkMath.h" namespace itk From f5688353059d552af1163166f59fce609f40af62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jon=20Haitz=20Legarreta=20Gorro=C3=B1o?= Date: Sun, 24 Jan 2021 20:25:26 -0500 Subject: [PATCH 3/5] ENH: Print all member variables. Print all member variables. Take advantage of the commit to - Use the `itk::NumericTraits::PrintType` definition, the `print_helper`-enabled overload for array-like types, and the `itkPrintSelfObjectMacro` macro to improve how the ivars and objects that can be null pointers are printed. - Print the member variables in the same order they were declared for the sake of consistency. - Print the member variable names verbatim to conform to the ITK SW Guide. --- ...lacementFieldJacobianDeterminantFilter.hxx | 29 +++++------- ...tkDirectedHausdorffDistanceImageFilter.hxx | 20 ++++++-- .../itkVectorGradientMagnitudeImageFilter.hxx | 29 +++++------- .../itkImagePCAShapeModelEstimator.hxx | 46 ++++++------------- .../include/itkAnchorOpenCloseImageFilter.hxx | 5 ++ Modules/IO/MINC/src/itkMINCImageIO.cxx | 6 ++- Modules/IO/MRC/src/itkMRCImageIO.cxx | 2 + Modules/IO/MeshBYU/src/itkBYUMeshIO.cxx | 3 ++ Modules/IO/NIFTI/src/itkNiftiImageIO.cxx | 6 +++ Modules/IO/NRRD/src/itkNrrdImageIO.cxx | 2 + ...phaseSparseFiniteDifferenceImageFilter.hxx | 36 ++++++++++++--- .../include/itkSyNImageRegistrationMethod.hxx | 24 ++++++---- .../itkImageGaussianModelEstimator.hxx | 18 +++----- .../include/itkImageKmeansModelEstimator.hxx | 36 ++++++++++----- .../itkScalarImageKmeansImageFilter.hxx | 12 +++-- ...dMaximumConnectedComponentsImageFilter.hxx | 19 ++++++-- .../itkNarrowBandLevelSetImageFilter.hxx | 9 +++- 17 files changed, 183 insertions(+), 119 deletions(-) diff --git a/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.hxx b/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.hxx index 03a6d092e67..58a0b9a80b1 100644 --- a/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.hxx +++ b/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.hxx @@ -27,6 +27,7 @@ #include "itkCastImageFilter.h" #include "itkMath.h" +#include "itkPrintHelper.h" namespace itk { @@ -233,25 +234,19 @@ void DisplacementFieldJacobianDeterminantFilter::PrintSelf(std::ostream & os, Indent indent) const { - unsigned int i; + using namespace print_helper; Superclass::PrintSelf(os, indent); - os << indent << "m_UseImageSpacing = " << m_UseImageSpacing << std::endl; - os << indent << "m_RequestedNumberOfThreads = " << m_RequestedNumberOfThreads << std::endl; - os << indent << "m_DerivativeWeights = "; - for (i = 0; i < ImageDimension; i++) - { - os << m_DerivativeWeights[i] << " "; - } - os << std::endl; - os << indent << "m_HalfDerivativeWeights = "; - for (i = 0; i < ImageDimension; i++) - { - os << m_HalfDerivativeWeights[i] << " "; - } - os << std::endl; - os << indent << "m_NeighborhoodRadius = " << m_NeighborhoodRadius << std::endl; - os << indent << "m_RealValuedInputImage = " << m_RealValuedInputImage.GetPointer() << std::endl; + + os << indent << "DerivativeWeights: " << m_DerivativeWeights << std::endl; + os << indent << "HalfDerivativeWeights: " << m_HalfDerivativeWeights << std::endl; + os << indent << "UseImageSpacing: " << m_UseImageSpacing << std::endl; + os << indent << "RequestedNumberOfThreads: " + << static_cast::PrintType>(m_RequestedNumberOfThreads) << std::endl; + os << indent << "RealValuedInputImage: " << m_RealValuedInputImage.GetPointer() << std::endl; + os << indent + << "NeighborhoodRadius: " << static_cast::PrintType>(m_NeighborhoodRadius) + << std::endl; } } // end namespace itk diff --git a/Modules/Filtering/DistanceMap/include/itkDirectedHausdorffDistanceImageFilter.hxx b/Modules/Filtering/DistanceMap/include/itkDirectedHausdorffDistanceImageFilter.hxx index b9cf2df8d27..d5a156e2c77 100644 --- a/Modules/Filtering/DistanceMap/include/itkDirectedHausdorffDistanceImageFilter.hxx +++ b/Modules/Filtering/DistanceMap/include/itkDirectedHausdorffDistanceImageFilter.hxx @@ -24,6 +24,7 @@ #include "itkProgressReporter.h" #include "itkMacro.h" #include "itkMath.h" +#include "itkPrintHelper.h" namespace itk { @@ -213,11 +214,24 @@ template void DirectedHausdorffDistanceImageFilter::PrintSelf(std::ostream & os, Indent indent) const { + using namespace print_helper; + Superclass::PrintSelf(os, indent); - os << indent << "DirectedHausdorffDistance: " << m_DirectedHausdorffDistance << std::endl; - os << indent << "AverageHausdorffDistance: " << m_AverageHausdorffDistance << std::endl; - os << indent << "Use Image Spacing : " << m_UseImageSpacing << std::endl; + os << indent << "DistanceMap: " << m_DistanceMap << std::endl; + os << indent << "MaxDistance: " << m_MaxDistance << std::endl; + os << indent << "PixelCount:" << m_PixelCount << std::endl; + os << indent << "Sum: "; + for (auto const & elem : m_Sum) + { + std::cout << elem.GetSum() << " "; + } + os << std::endl; + os << indent << "DirectedHausdorffDistance: " + << static_cast::PrintType>(m_DirectedHausdorffDistance) << std::endl; + os << indent << "AverageHausdorffDistance: " + << static_cast::PrintType>(m_AverageHausdorffDistance) << std::endl; + os << indent << "UseImageSpacing : " << m_UseImageSpacing << std::endl; } } // end namespace itk #endif diff --git a/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.hxx b/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.hxx index 0c61e0d2ad9..4f1ce1bfc4e 100644 --- a/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.hxx +++ b/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.hxx @@ -27,6 +27,7 @@ #include "itkCastImageFilter.h" #include "itkMath.h" +#include "itkPrintHelper.h" namespace itk { @@ -56,25 +57,19 @@ void VectorGradientMagnitudeImageFilter::PrintSelf(std::ostream & os, Indent indent) const { - unsigned i; + using namespace print_helper; Superclass::PrintSelf(os, indent); - os << indent << "m_UseImageSpacing = " << m_UseImageSpacing << std::endl; - os << indent << "m_UsePrincipleComponents = " << m_UsePrincipleComponents << std::endl; - os << indent << "m_RequestedNumberOfThreads = " << m_RequestedNumberOfThreads << std::endl; - os << indent << "m_DerivativeWeights = "; - for (i = 0; i < ImageDimension; i++) - { - os << m_DerivativeWeights[i] << " "; - } - os << std::endl; - os << indent << "m_ComponentWeights = "; - for (i = 0; i < VectorDimension; i++) - { - os << m_ComponentWeights[i] << " "; - } - os << std::endl; - os << indent << "m_RealValuedInputImage = " << m_RealValuedInputImage.GetPointer() << std::endl; + + os << indent << "DerivativeWeights: " << m_DerivativeWeights << std::endl; + os << indent << "ComponentWeights: " << m_ComponentWeights << std::endl; + os << indent << "SqrtComponentWeights: " << m_SqrtComponentWeights << std::endl; + os << indent << "UseImageSpacing: " << m_UseImageSpacing << std::endl; + os << indent << "UsePrincipleComponents: " << m_UsePrincipleComponents << std::endl; + os << indent << "RequestedNumberOfThreads: " + << static_cast::PrintType>(m_RequestedNumberOfThreads) << std::endl; + + itkPrintSelfObjectMacro(RealValuedInputImage); } template diff --git a/Modules/Filtering/ImageStatistics/include/itkImagePCAShapeModelEstimator.hxx b/Modules/Filtering/ImageStatistics/include/itkImagePCAShapeModelEstimator.hxx index ff087d0ace5..e8176a1d6c6 100644 --- a/Modules/Filtering/ImageStatistics/include/itkImagePCAShapeModelEstimator.hxx +++ b/Modules/Filtering/ImageStatistics/include/itkImagePCAShapeModelEstimator.hxx @@ -19,6 +19,7 @@ #define itkImagePCAShapeModelEstimator_hxx #include "itkImagePCAShapeModelEstimator.h" +#include "itkPrintHelper.h" namespace itk { @@ -38,41 +39,22 @@ template void ImagePCAShapeModelEstimator::PrintSelf(std::ostream & os, Indent indent) const { - os << indent << " " << std::endl; - os << indent << "Shape Models " << std::endl; - os << indent << "Results printed in the superclass " << std::endl; - os << indent << " " << std::endl; + using namespace print_helper; Superclass::PrintSelf(os, indent); - itkDebugMacro(<< " "); - itkDebugMacro(<< "Results of the shape model algorithms"); - itkDebugMacro(<< "===================================="); - - itkDebugMacro(<< "The eigen values new method are: "); - - itkDebugMacro(<< m_EigenValues); - itkDebugMacro(<< m_EigenVectorNormalizedEnergy); - - itkDebugMacro(<< " "); - itkDebugMacro(<< "================== "); - - itkDebugMacro(<< "The eigen vectors new method are: "); - - for (unsigned int i = 0; i < m_EigenValues.size(); i++) - { - itkDebugMacro(<< m_EigenVectors.get_row(i)); - } - - itkDebugMacro(<< " "); - itkDebugMacro(<< "+++++++++++++++++++++++++"); - - // Print out ivars - os << indent << "NumberOfPrincipalComponentsRequired: "; - os << m_NumberOfPrincipalComponentsRequired << std::endl; - os << indent << "NumberOfTrainingImages: "; - os << m_NumberOfTrainingImages << std::endl; -} // end PrintSelf + os << indent << "InputImageIteratorArray size: " << m_InputImageIteratorArray.size() << std::endl; + os << indent << "Means: " << m_Means << std::endl; + os << indent << "InnerProduct: " << m_InnerProduct << std::endl; + os << indent << "EigenVectors: " << m_EigenVectors << std::endl; + os << indent << "EigenValues: " << m_EigenValues << std::endl; + os << indent << "EigenVectorNormalizedEnergy: " << m_EigenVectorNormalizedEnergy << std::endl; + os << indent << "InputImageSize: " << static_cast::PrintType>(m_InputImageSize) + << std::endl; + os << indent << "NumberOfPixels: " << m_NumberOfPixels << std::endl; + os << indent << "NumberOfTrainingImages: " << m_NumberOfTrainingImages << std::endl; + os << indent << "NumberOfPrincipalComponentsRequired: " << m_NumberOfPrincipalComponentsRequired << std::endl; +} /** * Enlarge the output requested region to the largest possible region. diff --git a/Modules/Filtering/MathematicalMorphology/include/itkAnchorOpenCloseImageFilter.hxx b/Modules/Filtering/MathematicalMorphology/include/itkAnchorOpenCloseImageFilter.hxx index 05ac4fc011f..ad289158cfe 100644 --- a/Modules/Filtering/MathematicalMorphology/include/itkAnchorOpenCloseImageFilter.hxx +++ b/Modules/Filtering/MathematicalMorphology/include/itkAnchorOpenCloseImageFilter.hxx @@ -217,6 +217,11 @@ void AnchorOpenCloseImageFilter::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); + + os << indent << "Boundary1: " << static_cast::PrintType>(m_Boundary1) + << std::endl; + os << indent << "Boundary2: " << static_cast::PrintType>(m_Boundary2) + << std::endl; } } // end namespace itk diff --git a/Modules/IO/MINC/src/itkMINCImageIO.cxx b/Modules/IO/MINC/src/itkMINCImageIO.cxx index 3cb139e0f8f..be9bde4e289 100644 --- a/Modules/IO/MINC/src/itkMINCImageIO.cxx +++ b/Modules/IO/MINC/src/itkMINCImageIO.cxx @@ -22,6 +22,7 @@ #include "vnl/vnl_vector.h" #include "itkMetaDataObject.h" #include "itkArray.h" +#include "itkPrintHelper.h" #include @@ -263,9 +264,12 @@ MINCImageIO::~MINCImageIO() void MINCImageIO::PrintSelf(std::ostream & os, Indent indent) const { + using namespace print_helper; + Superclass::PrintSelf(os, indent); - os << indent << "NDims: " << this->m_MINCPImpl->m_NDims << std::endl; + os << indent << "MINCPImpl: " << m_MINCPImpl << std::endl; + os << indent << "DirectionCosines: " << m_DirectionCosines << std::endl; } void diff --git a/Modules/IO/MRC/src/itkMRCImageIO.cxx b/Modules/IO/MRC/src/itkMRCImageIO.cxx index b11f1268c33..45cf8958b97 100644 --- a/Modules/IO/MRC/src/itkMRCImageIO.cxx +++ b/Modules/IO/MRC/src/itkMRCImageIO.cxx @@ -51,6 +51,8 @@ void MRCImageIO::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); + + itkPrintSelfObjectMacro(MRCHeader); } bool diff --git a/Modules/IO/MeshBYU/src/itkBYUMeshIO.cxx b/Modules/IO/MeshBYU/src/itkBYUMeshIO.cxx index 6cc3d6dfc90..9a0be483c3d 100644 --- a/Modules/IO/MeshBYU/src/itkBYUMeshIO.cxx +++ b/Modules/IO/MeshBYU/src/itkBYUMeshIO.cxx @@ -528,6 +528,9 @@ void BYUMeshIO ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); + + os << indent << "FilePosition: " << static_cast::PrintType>(m_FilePosition) + << std::endl; os << indent << "PartId: " << m_PartId << std::endl; os << indent << "First Cell Id: " << m_FirstCellId << std::endl; os << indent << "Last Cell Id: " << m_LastCellId << std::endl; diff --git a/Modules/IO/NIFTI/src/itkNiftiImageIO.cxx b/Modules/IO/NIFTI/src/itkNiftiImageIO.cxx index 619fb5b5bec..bcb48af0fe6 100644 --- a/Modules/IO/NIFTI/src/itkNiftiImageIO.cxx +++ b/Modules/IO/NIFTI/src/itkNiftiImageIO.cxx @@ -471,6 +471,12 @@ void NiftiImageIO ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); + + os << indent << "NiftiImageHolder: " << *(this->m_NiftiImageHolder).get() << std::endl; + os << indent << "NiftiImage: " << this->m_NiftiImage << std::endl; + os << indent << "RescaleSlope: " << this->m_RescaleSlope << std::endl; + os << indent << "RescaleIntercept: " << this->m_RescaleIntercept << std::endl; + os << indent << "OnDiskComponentType: " << this->m_OnDiskComponentType << std::endl; os << indent << "LegacyAnalyze75Mode: " << this->m_LegacyAnalyze75Mode << std::endl; } diff --git a/Modules/IO/NRRD/src/itkNrrdImageIO.cxx b/Modules/IO/NRRD/src/itkNrrdImageIO.cxx index 6496083023a..6a6980d6efd 100644 --- a/Modules/IO/NRRD/src/itkNrrdImageIO.cxx +++ b/Modules/IO/NRRD/src/itkNrrdImageIO.cxx @@ -63,6 +63,8 @@ void NrrdImageIO::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); + + os << indent << "NrrdCompressionEncoding: " << m_NrrdCompressionEncoding << std::endl; } void diff --git a/Modules/Nonunit/Review/include/itkMultiphaseSparseFiniteDifferenceImageFilter.hxx b/Modules/Nonunit/Review/include/itkMultiphaseSparseFiniteDifferenceImageFilter.hxx index 0ff810ab3bc..c463c12aa9c 100644 --- a/Modules/Nonunit/Review/include/itkMultiphaseSparseFiniteDifferenceImageFilter.hxx +++ b/Modules/Nonunit/Review/include/itkMultiphaseSparseFiniteDifferenceImageFilter.hxx @@ -19,6 +19,8 @@ #define itkMultiphaseSparseFiniteDifferenceImageFilter_hxx #include "itkMultiphaseSparseFiniteDifferenceImageFilter.h" +#include "itkPrintHelper.h" + namespace itk { @@ -1390,10 +1392,35 @@ MultiphaseSparseFiniteDifferenceImageFilterm_IsoSurfaceValue << std::endl; - os << indent << "m_BoundsCheckingActive: " << m_BoundsCheckingActive; + os << indent << "ConstantGradientValue: " << m_ConstantGradientValue << std::endl; + os << indent << "ValueOne: " << static_cast::PrintType>(m_ValueOne) << std::endl; + os << indent << "ValueZero: " << static_cast::PrintType>(m_ValueZero) << std::endl; + os << indent << "StatusChanging: " << static_cast::PrintType>(m_StatusChanging) + << std::endl; + os << indent << "StatusActiveChangingUp: " + << static_cast::PrintType>(m_StatusActiveChangingUp) << std::endl; + os << indent << "StatusActiveChangingDown: " + << static_cast::PrintType>(m_StatusActiveChangingDown) << std::endl; + os << indent + << "StatusBoundaryPixel: " << static_cast::PrintType>(m_StatusBoundaryPixel) + << std::endl; + os << indent << "StatusNull: " << static_cast::PrintType>(m_StatusNull) + << std::endl; + os << indent << "SparseData: " << m_SparseData << std::endl; + os << indent << "NumberOfLayers: " << m_NumberOfLayers << std::endl; + os << indent << "IsoSurfaceValue: " << static_cast::PrintType>(m_IsoSurfaceValue) + << std::endl; + os << indent << "BackgroundValue: " << static_cast::PrintType>(m_BackgroundValue) + << std::endl; + os << indent << "InterpolateSurfaceLocation: " << m_InterpolateSurfaceLocation << std::endl; + os << indent << "CurrentFunctionIndex: " << m_CurrentFunctionIndex << std::endl; + os << indent << "RMSSum: " << m_RMSSum << std::endl; + os << indent << "RMSCounter: " << m_RMSCounter << std::endl; + os << indent << "BoundsCheckingActive: " << m_BoundsCheckingActive << std::endl; for (IdCellType i = 0; i < this->m_FunctionCount; i++) { @@ -1409,11 +1436,6 @@ MultiphaseSparseFiniteDifferenceImageFilter::PrintType>(m_ValueZero) << std::endl; - os << indent << "Value One " << static_cast::PrintType>(m_ValueOne) << std::endl; } } // end namespace itk diff --git a/Modules/Registration/RegistrationMethodsv4/include/itkSyNImageRegistrationMethod.hxx b/Modules/Registration/RegistrationMethodsv4/include/itkSyNImageRegistrationMethod.hxx index 47b415fdba6..8531ebd7efb 100644 --- a/Modules/Registration/RegistrationMethodsv4/include/itkSyNImageRegistrationMethod.hxx +++ b/Modules/Registration/RegistrationMethodsv4/include/itkSyNImageRegistrationMethod.hxx @@ -888,15 +888,23 @@ SyNImageRegistrationMethodm_NumberOfIterationsPerLevel << std::endl; - os << indent << "Learning rate: " << this->m_LearningRate << std::endl; - os << indent << "Convergence threshold: " << this->m_ConvergenceThreshold << std::endl; - os << indent << "Convergence window size: " << this->m_ConvergenceWindowSize << std::endl; - os << indent - << "Gaussian smoothing variance for the update field: " << this->m_GaussianSmoothingVarianceForTheUpdateField + os << indent << "LearningRate: " << static_cast::PrintType>(this->m_LearningRate) << std::endl; - os << indent - << "Gaussian smoothing variance for the total field: " << this->m_GaussianSmoothingVarianceForTheTotalField + os << indent << "ConvergenceThreshold: " + << static_cast::PrintType>(this->m_ConvergenceThreshold) << std::endl; + os << indent << "ConvergenceWindowSize: " << this->m_ConvergenceWindowSize << std::endl; + + itkPrintSelfObjectMacro(MovingToMiddleTransform); + itkPrintSelfObjectMacro(FixedToMiddleTransform); + + os << indent << "NumberOfIterationsPerLevel: " << this->m_NumberOfIterationsPerLevel << std::endl; + os << indent << "DownsampleImagesForMetricDerivatives: " << m_DownsampleImagesForMetricDerivatives << std::endl; + os << indent << "AverageMidPointGradients: " << m_AverageMidPointGradients << std::endl; + os << indent << "GaussianSmoothingVarianceForTheUpdateField: " + << static_cast::PrintType>(this->m_GaussianSmoothingVarianceForTheUpdateField) + << std::endl; + os << indent << "GaussianSmoothingVarianceForTheTotalField: " + << static_cast::PrintType>(this->m_GaussianSmoothingVarianceForTheTotalField) << std::endl; } diff --git a/Modules/Segmentation/Classifiers/include/itkImageGaussianModelEstimator.hxx b/Modules/Segmentation/Classifiers/include/itkImageGaussianModelEstimator.hxx index 2500a1dede0..603844fd145 100644 --- a/Modules/Segmentation/Classifiers/include/itkImageGaussianModelEstimator.hxx +++ b/Modules/Segmentation/Classifiers/include/itkImageGaussianModelEstimator.hxx @@ -39,19 +39,15 @@ void ImageGaussianModelEstimator::PrintSelf(std::ostream & os, Indent indent) const { - os << indent << " " << std::endl; - os << indent << "Gaussian Models generated from the training data." << std::endl; - os << indent << "TrainingImage: "; - os << m_TrainingImage.GetPointer() << std::endl; - os << indent << "Results printed in the superclass " << std::endl; - os << indent << " " << std::endl; - Superclass::PrintSelf(os, indent); -} // end PrintSelf -/** - * Generate data (start the model building process) - */ + os << indent << "NumberOfSamples: " << m_NumberOfSamples << std::endl; + os << indent << "Means: " << m_Means << std::endl; + os << indent << "Covariance: " << m_Covariance << std::endl; + + itkPrintSelfObjectMacro(TrainingImage); +} + template void ImageGaussianModelEstimator::GenerateData() diff --git a/Modules/Segmentation/Classifiers/include/itkImageKmeansModelEstimator.hxx b/Modules/Segmentation/Classifiers/include/itkImageKmeansModelEstimator.hxx index 05ecb586929..c2e3265495a 100644 --- a/Modules/Segmentation/Classifiers/include/itkImageKmeansModelEstimator.hxx +++ b/Modules/Segmentation/Classifiers/include/itkImageKmeansModelEstimator.hxx @@ -45,20 +45,32 @@ template void ImageKmeansModelEstimator::PrintSelf(std::ostream & os, Indent indent) const { - os << indent << " " << std::endl; - os << indent << "Kmeans Models " << std::endl; - os << indent << "Results printed in the superclass " << std::endl; - os << indent << " " << std::endl; - Superclass::PrintSelf(os, indent); - os << indent << "Unsupervised Classifier / Clusterer" << std::endl; - os << indent << "Offset value for addition:" << m_OffsetAdd << std::endl; - os << indent << "Offset value for multiplication:" << m_OffsetMultiply << std::endl; - os << indent << "Maximum number of attempts to split a cluster: " << m_MaxSplitAttempts << std::endl; - os << indent << "Codebook : " << m_Codebook << std::endl; - os << indent << "Threshold value :" << m_Threshold << std::endl; -} // end PrintSelf + os << indent << "Centroid: " << m_Centroid << std::endl; + + os << indent << "Threshold: " << m_Threshold << std::endl; + os << indent << "OffsetAdd: " << m_OffsetAdd << std::endl; + os << indent << "OffsetMultiply: " << m_OffsetMultiply << std::endl; + os << indent << "MaxSplitAttempts: " << m_MaxSplitAttempts << std::endl; + + os << indent << "ValidInCodebook: " << m_ValidInCodebook << std::endl; + os << indent << "DoubleMaximum: " << m_DoubleMaximum << std::endl; + os << indent << "OutputDistortion: " << m_OutputDistortion << std::endl; + os << indent << "OutputNumberOfEmptyCells: " << m_OutputNumberOfEmptyCells << std::endl; + + os << indent + << "VectorDimension: " << static_cast::PrintType>(m_VectorDimension) + << std::endl; + os << indent + << "NumberOfCodewords: " << static_cast::PrintType>(m_NumberOfCodewords) + << std::endl; + os << indent << "CurrentNumberOfCodewords: " + << static_cast::PrintType>(m_CurrentNumberOfCodewords) << std::endl; + + os << indent << "CodewordHistogram: " << m_CodewordHistogram << std::endl; + os << indent << "CodewordDistortion: " << m_CodewordDistortion << std::endl; +} template void diff --git a/Modules/Segmentation/Classifiers/include/itkScalarImageKmeansImageFilter.hxx b/Modules/Segmentation/Classifiers/include/itkScalarImageKmeansImageFilter.hxx index 467d6de766e..400da732ddb 100644 --- a/Modules/Segmentation/Classifiers/include/itkScalarImageKmeansImageFilter.hxx +++ b/Modules/Segmentation/Classifiers/include/itkScalarImageKmeansImageFilter.hxx @@ -24,6 +24,7 @@ #include "itkDistanceToCentroidMembershipFunction.h" #include "itkProgressReporter.h" +#include "itkPrintHelper.h" namespace itk { @@ -223,12 +224,15 @@ template void ScalarImageKmeansImageFilter::PrintSelf(std::ostream & os, Indent indent) const { + using namespace print_helper; + Superclass::PrintSelf(os, indent); - os << indent << "Final Means " << m_FinalMeans << std::endl; - os << indent << "Use Contiguous Labels " << m_UseNonContiguousLabels << std::endl; - os << indent << "Image Region Defined: " << m_ImageRegionDefined << std::endl; - os << indent << "Image Region: " << m_ImageRegion << std::endl; + os << indent << "InitialMeans: " << m_InitialMeans << std::endl; + os << indent << "FinalMeans: " << m_FinalMeans << std::endl; + os << indent << "UseContiguousLabels: " << m_UseNonContiguousLabels << std::endl; + os << indent << "ImageRegion: " << m_ImageRegion << std::endl; + os << indent << "ImageRegionDefined: " << m_ImageRegionDefined << std::endl; } } // end namespace itk diff --git a/Modules/Segmentation/ConnectedComponents/include/itkThresholdMaximumConnectedComponentsImageFilter.hxx b/Modules/Segmentation/ConnectedComponents/include/itkThresholdMaximumConnectedComponentsImageFilter.hxx index 60508aa9e3b..fcc86b0455b 100644 --- a/Modules/Segmentation/ConnectedComponents/include/itkThresholdMaximumConnectedComponentsImageFilter.hxx +++ b/Modules/Segmentation/ConnectedComponents/include/itkThresholdMaximumConnectedComponentsImageFilter.hxx @@ -203,16 +203,25 @@ ThresholdMaximumConnectedComponentsImageFilter::Print { Superclass::PrintSelf(os, indent); + itkPrintSelfObjectMacro(ThresholdFilter); + itkPrintSelfObjectMacro(ConnectedComponent); + itkPrintSelfObjectMacro(LabeledComponent); + itkPrintSelfObjectMacro(MinMaxCalculator); + + os << indent << "MinimumObjectSizeInPixels: " << m_MinimumObjectSizeInPixels << std::endl; + os << indent << "OutsideValue: " << static_cast::PrintType>(m_OutsideValue) + << std::endl; os << indent << "InsideValue: " << static_cast::PrintType>(m_InsideValue) << std::endl; - os << indent << "OutsideValue: " << static_cast::PrintType>(m_OutsideValue) + os << indent << "LowerBoundary: " << static_cast::PrintType>(m_LowerBoundary) + << std::endl; + os << indent << "UpperBoundary: " << static_cast::PrintType>(m_UpperBoundary) << std::endl; - os << indent << "Lower: " << static_cast::PrintType>(m_LowerBoundary) << std::endl; - os << indent << "Upper: " << static_cast::PrintType>(m_UpperBoundary) << std::endl; os << indent << "Threshold Value: " << static_cast::PrintType>(m_ThresholdValue) << std::endl; - os << indent << "Number of Objects: " << m_NumberOfObjects << std::endl; - os << indent << "Minimum Object Size in Pixels: " << m_MinimumObjectSizeInPixels << std::endl; + os << indent + << "NumberOfObjects: " << static_cast::PrintType>(m_NumberOfObjects) + << std::endl; } } // end namespace itk diff --git a/Modules/Segmentation/LevelSets/include/itkNarrowBandLevelSetImageFilter.hxx b/Modules/Segmentation/LevelSets/include/itkNarrowBandLevelSetImageFilter.hxx index 3118faee9ab..98a3460aabe 100644 --- a/Modules/Segmentation/LevelSets/include/itkNarrowBandLevelSetImageFilter.hxx +++ b/Modules/Segmentation/LevelSets/include/itkNarrowBandLevelSetImageFilter.hxx @@ -31,8 +31,13 @@ NarrowBandLevelSetImageFilter From 84808d7531ecead163b44758b9476d824432ecfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jon=20Haitz=20Legarreta=20Gorro=C3=B1o?= Date: Sun, 7 Feb 2021 16:41:37 -0500 Subject: [PATCH 4/5] ENH: Use `itkBooleanMacro` for `ImageSpacing`, `InterpolateSurfaceLocation` Use `itkBooleanMacro` to set `ImageSpacing` and `InterpolateSurfaceLocation` boolean member variable values to On/Off: - Deprecate `Set*(On/Off)` signatures. - Test the methods. --- ...splacementFieldJacobianDeterminantFilter.h | 30 ++++++++++++------- ...mentFieldJacobianDeterminantFilterTest.cxx | 16 ++++++++++ ...tkContourDirectedMeanDistanceImageFilter.h | 3 +- .../itkDirectedHausdorffDistanceImageFilter.h | 3 +- ...ourDirectedMeanDistanceImageFilterTest.cxx | 8 +++++ .../include/itkDerivativeImageFilter.h | 15 ++++++---- .../test/itkDerivativeImageFilterTest.cxx | 14 +++++++++ .../include/itkGradientImageFilter.h | 22 +++++++++----- .../include/itkGradientMagnitudeImageFilter.h | 21 ++++++++----- .../itkVectorGradientMagnitudeImageFilter.h | 4 +-- .../test/itkGradientImageFilterTest.cxx | 10 +++++++ .../itkGradientMagnitudeImageFilterTest.cxx | 15 ++++++++++ ...ectorGradientMagnitudeImageFilterTest1.cxx | 10 +++++++ .../itkOrthogonalSwath2DPathFilterTest.cxx | 2 +- .../include/itkDiscreteGaussianImageFilter.h | 22 +++++++++----- .../itkDiscreteGaussianImageFilterTest.cxx | 14 ++++++++- ...tiphaseSparseFiniteDifferenceImageFilter.h | 13 +------- ...eSparseFiniteDifferenceImageFilterTest.cxx | 5 ++++ ...mMutualInformationImageToImageMetricv4.hxx | 2 +- .../include/itkCurvesLevelSetFunction.hxx | 2 +- ...kGeodesicActiveContourLevelSetFunction.hxx | 2 +- ...ctiveContourShapePriorLevelSetFunction.hxx | 2 +- .../itkLevelSetEquationAdvectionTerm.hxx | 2 +- 23 files changed, 177 insertions(+), 60 deletions(-) diff --git a/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.h b/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.h index 7338fa6c76a..be0af814930 100644 --- a/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.h +++ b/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.h @@ -67,10 +67,10 @@ namespace itk * itk::Image. * * \par Filter Parameters - * The method SetUseImageSpacingOn will cause derivatives in the image to be + * The method UseImageSpacingOn will cause derivatives in the image to be * scaled (inversely) with the pixel size of the input image, effectively * taking derivatives in world coordinates (versus isotropic image - * space). SetUseImageSpacingOff turns this functionality off. Default is + * space). UseImageSpacingOff turns this functionality off. Default is * UseImageSpacingOn. The parameter UseImageSpacing can * be set directly with the method SetUseImageSpacing(bool). * @@ -170,10 +170,23 @@ class ITK_TEMPLATE_EXPORT DisplacementFieldJacobianDeterminantFilter void GenerateInputRequestedRegion() override; + /** Set/Get whether or not the filter will use the spacing of the input + * image (1/spacing) in the calculation of the Jacobian determinant. Use On + * to compute the Jacobian determinant in the space in which the data was + * acquired; use Off to reset the derivative weights, ignore the image + * spacing, and to compute the Jacobian determinant in the image space. + * Default is On. */ + void + SetUseImageSpacing(bool); + itkGetConstMacro(UseImageSpacing, bool); + itkBooleanMacro(UseImageSpacing); + +#if !defined(ITK_FUTURE_LEGACY_REMOVE) /** Set the derivative weights according to the spacing of the input image (1/spacing). Use this option if you want to calculate the Jacobian determinant in the space in which the data was acquired. Default - is ImageSpacingOn. */ + is ImageSpacingOn. + \deprecated Use DisplacementFieldJacobianDeterminantFilter::UseImageSpacingOn instead. */ void SetUseImageSpacingOn() { @@ -182,19 +195,14 @@ class ITK_TEMPLATE_EXPORT DisplacementFieldJacobianDeterminantFilter /** Reset the derivative weights to ignore image spacing. Use this option if you want to calculate the Jacobian determinant in the image space. - Default is ImageSpacingOn. */ + Default is ImageSpacingOn. + \deprecated Use DisplacementFieldJacobianDeterminantFilter::UseImageSpacingOff instead. */ void SetUseImageSpacingOff() { this->SetUseImageSpacing(false); } - - /** Set/Get whether or not the filter will use the spacing of the input - image in its calculations */ - void - SetUseImageSpacing(bool); - - itkGetConstMacro(UseImageSpacing, bool); +#endif using WeightsType = FixedArray; diff --git a/Modules/Filtering/DisplacementField/test/itkDisplacementFieldJacobianDeterminantFilterTest.cxx b/Modules/Filtering/DisplacementField/test/itkDisplacementFieldJacobianDeterminantFilterTest.cxx index 8e838a6750a..1e316fa9f60 100644 --- a/Modules/Filtering/DisplacementField/test/itkDisplacementFieldJacobianDeterminantFilterTest.cxx +++ b/Modules/Filtering/DisplacementField/test/itkDisplacementFieldJacobianDeterminantFilterTest.cxx @@ -20,6 +20,8 @@ #include "itkDisplacementFieldJacobianDeterminantFilter.h" #include "itkNullImageToImageFilterDriver.hxx" #include "itkStdStreamStateSave.h" +#include "itkTestingMacros.h" + static bool TestDisplacementJacobianDeterminantValue() @@ -76,6 +78,20 @@ TestDisplacementJacobianDeterminantValue() itk::DisplacementFieldJacobianDeterminantFilter::Pointer filter = itk::DisplacementFieldJacobianDeterminantFilter::New(); + + bool useImageSpacing = true; +#if !defined(ITK_FUTURE_LEGACY_REMOVE) + if (useImageSpacing) + { + filter->SetUseImageSpacingOn(); + } + else + { + filter->SetUseImageSpacingOff(); + } +#endif + ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing); + filter->SetInput(dispacementfield); filter->Update(); itk::Image::Pointer output = filter->GetOutput(); diff --git a/Modules/Filtering/DistanceMap/include/itkContourDirectedMeanDistanceImageFilter.h b/Modules/Filtering/DistanceMap/include/itkContourDirectedMeanDistanceImageFilter.h index fb4561eab42..c7c5bd9fa0f 100644 --- a/Modules/Filtering/DistanceMap/include/itkContourDirectedMeanDistanceImageFilter.h +++ b/Modules/Filtering/DistanceMap/include/itkContourDirectedMeanDistanceImageFilter.h @@ -118,9 +118,10 @@ class ITK_TEMPLATE_EXPORT ContourDirectedMeanDistanceImageFilter : public ImageT /** Return the computed directed Mean distance. */ itkGetConstMacro(ContourDirectedMeanDistance, RealType); - /** Set if image spacing should be used in computing distances. */ + /** Set/Get if image spacing should be used in computing distances. */ itkSetMacro(UseImageSpacing, bool); itkGetConstMacro(UseImageSpacing, bool); + itkBooleanMacro(UseImageSpacing); #ifdef ITK_USE_CONCEPT_CHECKING // Begin concept checking diff --git a/Modules/Filtering/DistanceMap/include/itkDirectedHausdorffDistanceImageFilter.h b/Modules/Filtering/DistanceMap/include/itkDirectedHausdorffDistanceImageFilter.h index b23a3088af8..24c92d9b243 100644 --- a/Modules/Filtering/DistanceMap/include/itkDirectedHausdorffDistanceImageFilter.h +++ b/Modules/Filtering/DistanceMap/include/itkDirectedHausdorffDistanceImageFilter.h @@ -124,9 +124,10 @@ class ITK_TEMPLATE_EXPORT DirectedHausdorffDistanceImageFilter : public ImageToI const InputImage2Type * GetInput2(); - /** Set if image spacing should be used in computing distances. */ + /** Set/Get if image spacing should be used in computing distances. */ itkSetMacro(UseImageSpacing, bool); itkGetConstMacro(UseImageSpacing, bool); + itkBooleanMacro(UseImageSpacing); /** Return the computed directed Hausdorff distance. */ itkGetConstMacro(DirectedHausdorffDistance, RealType); diff --git a/Modules/Filtering/DistanceMap/test/itkContourDirectedMeanDistanceImageFilterTest.cxx b/Modules/Filtering/DistanceMap/test/itkContourDirectedMeanDistanceImageFilterTest.cxx index 09d8bea3443..46cd5701786 100644 --- a/Modules/Filtering/DistanceMap/test/itkContourDirectedMeanDistanceImageFilterTest.cxx +++ b/Modules/Filtering/DistanceMap/test/itkContourDirectedMeanDistanceImageFilterTest.cxx @@ -18,6 +18,7 @@ #include "itkContourDirectedMeanDistanceImageFilter.h" #include "itkSimpleFilterWatcher.h" +#include "itkTestingMacros.h" int itkContourDirectedMeanDistanceImageFilterTest(int, char *[]) @@ -78,6 +79,7 @@ itkContourDirectedMeanDistanceImageFilterTest(int, char *[]) ++it2; } + auto useImageSpacing = true; // compute the directed Mean distance h(image1,image2) { @@ -85,6 +87,9 @@ itkContourDirectedMeanDistanceImageFilterTest(int, char *[]) FilterType::Pointer filter = FilterType::New(); itk::SimpleFilterWatcher watcher(filter, "filter"); + + ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing); + filter->SetInput1(image1); filter->SetInput2(image2); filter->Update(); @@ -111,6 +116,9 @@ itkContourDirectedMeanDistanceImageFilterTest(int, char *[]) using FilterType = itk::ContourDirectedMeanDistanceImageFilter; FilterType::Pointer filter = FilterType::New(); + + ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing); + filter->SetInput1(image2); filter->SetInput2(image1); filter->Update(); diff --git a/Modules/Filtering/ImageFeature/include/itkDerivativeImageFilter.h b/Modules/Filtering/ImageFeature/include/itkDerivativeImageFilter.h index 846fc33e8dc..cbfe48c9c31 100644 --- a/Modules/Filtering/ImageFeature/include/itkDerivativeImageFilter.h +++ b/Modules/Filtering/ImageFeature/include/itkDerivativeImageFilter.h @@ -92,6 +92,15 @@ class ITK_TEMPLATE_EXPORT DerivativeImageFilter : public ImageToImageFilterSetUseImageSpacing(false); } - - /** Set/Get whether or not the filter will use the spacing of the input - image in its calculations */ - itkSetMacro(UseImageSpacing, bool); - itkGetConstMacro(UseImageSpacing, bool); +#endif /** DerivativeImageFilter needs a larger input requested region than * the output requested region (larger in the direction of the diff --git a/Modules/Filtering/ImageFeature/test/itkDerivativeImageFilterTest.cxx b/Modules/Filtering/ImageFeature/test/itkDerivativeImageFilterTest.cxx index 986268406b4..014da05ad6b 100644 --- a/Modules/Filtering/ImageFeature/test/itkDerivativeImageFilterTest.cxx +++ b/Modules/Filtering/ImageFeature/test/itkDerivativeImageFilterTest.cxx @@ -62,6 +62,20 @@ itkDerivativeImageFilterTest(int argc, char * argv[]) filter->SetOrder(std::stoi(argv[3])); filter->SetDirection(std::stoi(argv[4])); + auto useImageSpacing = true; +#if !defined(ITK_FUTURE_LEGACY_REMOVE) + if (useImageSpacing) + { + filter->SetUseImageSpacingOn(); + } + else + { + filter->SetUseImageSpacingOff(); + } +#endif + ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing); + + itk::SimpleFilterWatcher watcher(filter, "Derivative"); // wire the pipeline diff --git a/Modules/Filtering/ImageGradient/include/itkGradientImageFilter.h b/Modules/Filtering/ImageGradient/include/itkGradientImageFilter.h index c9632dc4906..7e3ba149152 100644 --- a/Modules/Filtering/ImageGradient/include/itkGradientImageFilter.h +++ b/Modules/Filtering/ImageGradient/include/itkGradientImageFilter.h @@ -107,8 +107,19 @@ class ITK_TEMPLATE_EXPORT GradientImageFilter : public ImageToImageFilterSetUseImageSpacing(false); } +#endif - /** Set/Get whether or not the filter will use the spacing of the input - image in its calculations */ - itkSetMacro(UseImageSpacing, bool); - itkGetConstMacro(UseImageSpacing, bool); - itkBooleanMacro(UseImageSpacing); /** Allows to change the default boundary condition */ void OverrideBoundaryCondition(ImageBoundaryCondition * boundaryCondition); diff --git a/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeImageFilter.h b/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeImageFilter.h index 91f2b67fbc5..596340d812e 100644 --- a/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeImageFilter.h +++ b/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeImageFilter.h @@ -86,8 +86,18 @@ class ITK_TEMPLATE_EXPORT GradientMagnitudeImageFilter : public ImageToImageFilt void GenerateInputRequestedRegion() override; + /** Set/Get whether or not the filter will use the spacing of the input + * image in the computation of the derivatives. Use On to compute the + * gradient in physical space; use Off to ignore image spacing and to + * compute the gradient in isotropic voxel space. Default is On. */ + itkSetMacro(UseImageSpacing, bool); + itkGetConstMacro(UseImageSpacing, bool); + itkBooleanMacro(UseImageSpacing); + +#if !defined(ITK_FUTURE_LEGACY_REMOVE) /** Use the image spacing information in calculations. Use this option if you - * want derivatives in physical space. Default is UseImageSpacingOn. */ + * want derivatives in physical space. Default is UseImageSpacingOn. + \deprecated Use GradientMagnitudeImageFilter::UseImageSpacingOn instead. */ void SetUseImageSpacingOn() { @@ -95,17 +105,14 @@ class ITK_TEMPLATE_EXPORT GradientMagnitudeImageFilter : public ImageToImageFilt } /** Ignore the image spacing. Use this option if you want derivatives in - isotropic pixel space. Default is UseImageSpacingOn. */ + isotropic pixel space. Default is UseImageSpacingOn. + \deprecated Use GradientMagnitudeImageFilter::UseImageSpacingOff instead. */ void SetUseImageSpacingOff() { this->SetUseImageSpacing(false); } - - /** Set/Get whether or not the filter will use the spacing of the input - image in its calculations */ - itkSetMacro(UseImageSpacing, bool); - itkGetConstMacro(UseImageSpacing, bool); +#endif #ifdef ITK_USE_CONCEPT_CHECKING // Begin concept checking diff --git a/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.h b/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.h index 3b8f3417646..042e12705fc 100644 --- a/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.h +++ b/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.h @@ -82,10 +82,10 @@ namespace itk * SetUsePrincipleComponentsOn/Off determine controls the calculation mode that * is used. * - * The method SetUseImageSpacingOn will cause derivatives in the image to be + * The method UseImageSpacingOn will cause derivatives in the image to be * scaled (inversely) with the pixel size of the input image, effectively * taking derivatives in world coordinates (versus isotropic image - * space). SetUseImageSpacingOff turns this functionality off. Default is + * space). UseImageSpacingOff turns this functionality off. Default is * UseImageSpacingOn. The parameter UseImageSpacing can be set * directly with the method SetUseImageSpacing(bool). * diff --git a/Modules/Filtering/ImageGradient/test/itkGradientImageFilterTest.cxx b/Modules/Filtering/ImageGradient/test/itkGradientImageFilterTest.cxx index 0346e2b48d2..ce92a06e3d6 100644 --- a/Modules/Filtering/ImageGradient/test/itkGradientImageFilterTest.cxx +++ b/Modules/Filtering/ImageGradient/test/itkGradientImageFilterTest.cxx @@ -53,6 +53,16 @@ itkGradientImageFilterTest(int argc, char * argv[]) auto useImageSpacing = static_cast(std::stoi(argv[1])); +#if !defined(ITK_FUTURE_LEGACY_REMOVE) + if (useImageSpacing) + { + filter1->SetUseImageSpacingOn(); + } + else + { + filter1->SetUseImageSpacingOff(); + } +#endif ITK_TEST_SET_GET_BOOLEAN(filter1, UseImageSpacing, useImageSpacing); auto useImageDirection = static_cast(std::stoi(argv[2])); diff --git a/Modules/Filtering/ImageGradient/test/itkGradientMagnitudeImageFilterTest.cxx b/Modules/Filtering/ImageGradient/test/itkGradientMagnitudeImageFilterTest.cxx index 70617b28edd..86ae7622779 100644 --- a/Modules/Filtering/ImageGradient/test/itkGradientMagnitudeImageFilterTest.cxx +++ b/Modules/Filtering/ImageGradient/test/itkGradientMagnitudeImageFilterTest.cxx @@ -19,6 +19,8 @@ #include #include "itkGradientMagnitudeImageFilter.h" #include "itkNullImageToImageFilterDriver.hxx" +#include "itkTestingMacros.h" + inline std::ostream & operator<<(std::ostream & o, const itk::Vector & v) @@ -38,6 +40,19 @@ itkGradientMagnitudeImageFilterTest(int, char *[]) itk::GradientMagnitudeImageFilter::Pointer filter = itk::GradientMagnitudeImageFilter::New(); + bool useImageSpacing = true; +#if !defined(ITK_FUTURE_LEGACY_REMOVE) + if (useImageSpacing) + { + filter->SetUseImageSpacingOn(); + } + else + { + filter->SetUseImageSpacingOff(); + } +#endif + ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing); + // Run Test itk::Size<2> sz; sz[0] = 100; diff --git a/Modules/Filtering/ImageGradient/test/itkVectorGradientMagnitudeImageFilterTest1.cxx b/Modules/Filtering/ImageGradient/test/itkVectorGradientMagnitudeImageFilterTest1.cxx index 0deb54e913e..846cfda064c 100644 --- a/Modules/Filtering/ImageGradient/test/itkVectorGradientMagnitudeImageFilterTest1.cxx +++ b/Modules/Filtering/ImageGradient/test/itkVectorGradientMagnitudeImageFilterTest1.cxx @@ -61,6 +61,16 @@ itkVectorGradientMagnitudeImageFilterTest1(int argc, char * argv[]) filter->SetInput(adaptor); auto useImageSpacing = static_cast(std::stoi(argv[3])); +#if !defined(ITK_FUTURE_LEGACY_REMOVE) + if (useImageSpacing) + { + filter->SetUseImageSpacingOn(); + } + else + { + filter->SetUseImageSpacingOff(); + } +#endif ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing); auto derivativeWeightsValue = static_cast(std::stod(argv[4])); diff --git a/Modules/Filtering/Path/test/itkOrthogonalSwath2DPathFilterTest.cxx b/Modules/Filtering/Path/test/itkOrthogonalSwath2DPathFilterTest.cxx index 817530d46b8..f4571bf296e 100644 --- a/Modules/Filtering/Path/test/itkOrthogonalSwath2DPathFilterTest.cxx +++ b/Modules/Filtering/Path/test/itkOrthogonalSwath2DPathFilterTest.cxx @@ -152,7 +152,7 @@ itkOrthogonalSwath2DPathFilterTest(int, char *[]) // kernel, and so setting the maximum error to 1.0 (no limit) will make it // stop growing the kernel at the desired 3x3 size. double maxError = 0.9; - smoothFilter->SetUseImageSpacingOff(); + smoothFilter->UseImageSpacingOff(); smoothFilter->SetVariance(gaussianVariance); smoothFilter->SetMaximumError(maxError); diff --git a/Modules/Filtering/Smoothing/include/itkDiscreteGaussianImageFilter.h b/Modules/Filtering/Smoothing/include/itkDiscreteGaussianImageFilter.h index 0e3a94a274d..021d759ff94 100644 --- a/Modules/Filtering/Smoothing/include/itkDiscreteGaussianImageFilter.h +++ b/Modules/Filtering/Smoothing/include/itkDiscreteGaussianImageFilter.h @@ -251,9 +251,20 @@ class ITK_TEMPLATE_EXPORT DiscreteGaussianImageFilter : public ImageToImageFilte this->SetMaximumError(dv); } + /** Set/Get whether or not the filter will use the spacing of the input + * image in its calculations. Use On to take the image spacing information + * into account and to specify the Gaussian variance in real world units; + * use Off to gnore the image spacing and to specify the Gaussian variance + * in voxel units. Default is On. */ + itkSetMacro(UseImageSpacing, bool); + itkGetConstMacro(UseImageSpacing, bool); + itkBooleanMacro(UseImageSpacing); + +#if !defined(ITK_FUTURE_LEGACY_REMOVE) /** Use the image spacing information in calculations. Use this option if you * want to specify Gaussian variance in real world units. Default is - * ImageSpacingOn. */ + * ImageSpacingOn. + * \deprecated Use DiscreteGaussianImageFilter::UseImageSpacingOn instead. */ void SetUseImageSpacingOn() { @@ -261,17 +272,14 @@ class ITK_TEMPLATE_EXPORT DiscreteGaussianImageFilter : public ImageToImageFilte } /** Ignore the image spacing. Use this option if you want to specify Gaussian - variance in pixels. Default is ImageSpacingOn. */ + variance in pixels. Default is ImageSpacingOn. + \deprecated Use DiscreteGaussianImageFilter::UseImageSpacingOff instead. */ void SetUseImageSpacingOff() { this->SetUseImageSpacing(false); } - - /** Set/Get whether or not the filter will use the spacing of the input - image in its calculations */ - itkSetMacro(UseImageSpacing, bool); - itkGetConstMacro(UseImageSpacing, bool); +#endif /** \brief Set/Get number of pieces to divide the input for the * internal composite pipeline. The upstream pipeline will not be diff --git a/Modules/Filtering/Smoothing/test/itkDiscreteGaussianImageFilterTest.cxx b/Modules/Filtering/Smoothing/test/itkDiscreteGaussianImageFilterTest.cxx index fd9d97cbb52..855e61974ef 100644 --- a/Modules/Filtering/Smoothing/test/itkDiscreteGaussianImageFilterTest.cxx +++ b/Modules/Filtering/Smoothing/test/itkDiscreteGaussianImageFilterTest.cxx @@ -72,7 +72,19 @@ itkDiscreteGaussianImageFilterTest(int, char *[]) filter->SetMaximumError(.01); filter->SetMaximumKernelWidth(32); filter->SetFilterDimensionality(Dimension); - filter->SetUseImageSpacing(true); + + bool useImageSpacing = true; +#if !defined(ITK_FUTURE_LEGACY_REMOVE) + if (useImageSpacing) + { + filter->SetUseImageSpacingOn(); + } + else + { + filter->SetUseImageSpacingOff(); + } +#endif + ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing); // Test some functions ArrayType varReturned = filter->GetVariance(); diff --git a/Modules/Nonunit/Review/include/itkMultiphaseSparseFiniteDifferenceImageFilter.h b/Modules/Nonunit/Review/include/itkMultiphaseSparseFiniteDifferenceImageFilter.h index 733a3dbcf7b..5f6395284f6 100644 --- a/Modules/Nonunit/Review/include/itkMultiphaseSparseFiniteDifferenceImageFilter.h +++ b/Modules/Nonunit/Review/include/itkMultiphaseSparseFiniteDifferenceImageFilter.h @@ -292,18 +292,7 @@ class ITK_TEMPLATE_EXPORT MultiphaseSparseFiniteDifferenceImageFilter * applications may not use this value and can safely turn the flag off. */ itkSetMacro(InterpolateSurfaceLocation, bool); itkGetConstMacro(InterpolateSurfaceLocation, bool); - - /** See Get/SetInterpolateSurfaceLocation */ - void - InterpolateSurfaceLocationOn() - { - this->SetInterpolateSurfaceLocation(true); - } - void - InterpolateSurfaceLocationOff() - { - this->SetInterpolateSurfaceLocation(false); - } + itkBooleanMacro(InterpolateSurfaceLocation); void SetFunctionCount(const IdCellType & n) diff --git a/Modules/Nonunit/Review/test/itkMultiphaseSparseFiniteDifferenceImageFilterTest.cxx b/Modules/Nonunit/Review/test/itkMultiphaseSparseFiniteDifferenceImageFilterTest.cxx index 142162d8ecd..1a5fd010712 100644 --- a/Modules/Nonunit/Review/test/itkMultiphaseSparseFiniteDifferenceImageFilterTest.cxx +++ b/Modules/Nonunit/Review/test/itkMultiphaseSparseFiniteDifferenceImageFilterTest.cxx @@ -18,6 +18,7 @@ #include "itkMultiphaseSparseFiniteDifferenceImageFilter.h" #include "itkScalarChanAndVeseLevelSetFunction.h" +#include "itkTestingMacros.h" namespace itk { @@ -107,5 +108,9 @@ itkMultiphaseSparseFiniteDifferenceImageFilterTest(int, char *[]) filter->Print(std::cout); + bool interpolateSurfaceLocation = true; + ITK_TEST_SET_GET_BOOLEAN(filter, InterpolateSurfaceLocation, interpolateSurfaceLocation); + + return EXIT_SUCCESS; } diff --git a/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationImageToImageMetricv4.hxx b/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationImageToImageMetricv4.hxx index aa88b3589ca..234b5b91376 100644 --- a/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationImageToImageMetricv4.hxx +++ b/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationImageToImageMetricv4.hxx @@ -264,7 +264,7 @@ JointHistogramMutualInformationImageToImageMetricv4SetInput(this->m_JointPDF); dg->SetVariance(this->m_VarianceForJointPDFSmoothing); - dg->SetUseImageSpacingOff(); + dg->UseImageSpacingOff(); dg->SetMaximumError(.01f); dg->Update(); this->m_JointPDF = (dg->GetOutput()); diff --git a/Modules/Segmentation/LevelSets/include/itkCurvesLevelSetFunction.hxx b/Modules/Segmentation/LevelSets/include/itkCurvesLevelSetFunction.hxx index cc54038207f..464bc33dfcd 100644 --- a/Modules/Segmentation/LevelSets/include/itkCurvesLevelSetFunction.hxx +++ b/Modules/Segmentation/LevelSets/include/itkCurvesLevelSetFunction.hxx @@ -75,7 +75,7 @@ CurvesLevelSetFunction::CalculateAdvectionImage() typename DerivativeFilterType::Pointer derivative = DerivativeFilterType::New(); derivative->SetInput(this->GetFeatureImage()); - derivative->SetUseImageSpacingOn(); + derivative->UseImageSpacingOn(); derivative->Update(); using DerivativeOutputImageType = typename DerivativeFilterType::OutputImageType; diff --git a/Modules/Segmentation/LevelSets/include/itkGeodesicActiveContourLevelSetFunction.hxx b/Modules/Segmentation/LevelSets/include/itkGeodesicActiveContourLevelSetFunction.hxx index 7f7bf4a1b57..cf8416ac774 100644 --- a/Modules/Segmentation/LevelSets/include/itkGeodesicActiveContourLevelSetFunction.hxx +++ b/Modules/Segmentation/LevelSets/include/itkGeodesicActiveContourLevelSetFunction.hxx @@ -64,7 +64,7 @@ GeodesicActiveContourLevelSetFunction::CalculateA typename DerivativeFilterType::Pointer derivative = DerivativeFilterType::New(); derivative->SetInput(this->GetFeatureImage()); - derivative->SetUseImageSpacingOn(); + derivative->UseImageSpacingOn(); derivative->Update(); using DerivativeOutputImageType = typename DerivativeFilterType::OutputImageType; diff --git a/Modules/Segmentation/LevelSets/include/itkGeodesicActiveContourShapePriorLevelSetFunction.hxx b/Modules/Segmentation/LevelSets/include/itkGeodesicActiveContourShapePriorLevelSetFunction.hxx index d457c5309b8..d917951540a 100644 --- a/Modules/Segmentation/LevelSets/include/itkGeodesicActiveContourShapePriorLevelSetFunction.hxx +++ b/Modules/Segmentation/LevelSets/include/itkGeodesicActiveContourShapePriorLevelSetFunction.hxx @@ -63,7 +63,7 @@ GeodesicActiveContourShapePriorLevelSetFunction:: typename DerivativeFilterType::Pointer derivative = DerivativeFilterType::New(); derivative->SetInput(this->GetFeatureImage()); - derivative->SetUseImageSpacingOn(); + derivative->UseImageSpacingOn(); derivative->Update(); using DerivativeOutputImageType = typename DerivativeFilterType::OutputImageType; diff --git a/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEquationAdvectionTerm.hxx b/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEquationAdvectionTerm.hxx index 4b528675e19..21703e6bcd4 100644 --- a/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEquationAdvectionTerm.hxx +++ b/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEquationAdvectionTerm.hxx @@ -91,7 +91,7 @@ LevelSetEquationAdvectionTerm::GenerateAdvectionImag typename DerivativeFilterType::Pointer derivative = DerivativeFilterType::New(); derivative->SetInput(this->m_Input); - derivative->SetUseImageSpacingOn(); + derivative->UseImageSpacingOn(); derivative->Update(); using DerivativeOutputImageType = typename DerivativeFilterType::OutputImageType; From c19e8fa7464e156e38e8e27216d4932fdbe00bcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jon=20Haitz=20Legarreta=20Gorro=C3=B1o?= Date: Mon, 8 Feb 2021 21:22:30 -0500 Subject: [PATCH 5/5] ENH: Increase code coverage Increase the code coverage: - Add new unit tests for untested classes, including the corresponding baseline hash files. - Exercise the basic object methods using the `ITK_EXERCISE_BASIC_OBJECT_METHODS` macro. - Test the Set/Get methods using the `ITK_TEST_SET_GET_VALUE` macro. - Test the boolean ivars using the `ITK_TEST_SET_GET_BOOLEAN` macro. - Add the corresponding test arguments to the appropriate `CMakeLists.txt` test driver command. - Remove the global `try/catch` blocks and use the `ITK_TRY_EXPECT_NO_EXCEPTION` macro around the statement that is liable to throw an exception to avoid boilerplate code and to improve readability. - Test the exceptions. - Remove explicit calls to the `Print` method and rely on the basic method exercising macro call. - Improve slightly the test style to make them more consistent (e.g. input argument checking, test finishing message, make the types and variables dwell closer to the place where they are instantiated, define the image dimension as a constant; use aliases for the pixel types, etc.). - Remove unnecessary print messages. --- ...tkN4BiasFieldCorrectionImageFilterTest.cxx | 75 +++++++----- ...ClosingByReconstructionImageFilterTest.cxx | 61 ++++++---- .../DisplacementField/test/CMakeLists.txt | 2 +- ...mentFieldJacobianDeterminantFilterTest.cxx | 42 +++++-- ...kTimeVaryingVelocityFieldTransformTest.cxx | 30 ++++- ...TransformToDisplacementFieldFilterTest.cxx | 60 ++++----- ...ransformToDisplacementFieldFilterTest1.cxx | 86 ++++++------- .../Filtering/DistanceMap/test/CMakeLists.txt | 9 +- ...ourDirectedMeanDistanceImageFilterTest.cxx | 17 +-- ...tkDanielssonDistanceMapImageFilterTest.cxx | 61 ++++------ ...kDanielssonDistanceMapImageFilterTest1.cxx | 33 ++++- ...kDanielssonDistanceMapImageFilterTest2.cxx | 21 +++- ...rectedHausdorffDistanceImageFilterTest.cxx | 94 +++++++++++++++ .../ImageFeature/test/CMakeLists.txt | 13 +- .../test/itkDerivativeImageFilterTest.cxx | 30 +++-- .../test/itkLaplacianImageFilterTest.cxx | 114 +++++++++++------- .../itkGradientMagnitudeImageFilterTest.cxx | 16 ++- .../itkImagePCAShapeModelEstimatorTest.cxx | 37 ++---- .../Filtering/LabelMap/test/CMakeLists.txt | 6 + .../itkBinaryFillholeImageFilterTest1.cxx | 57 ++++++--- .../itkBinaryImageToLabelMapFilterTest.cxx | 33 +++-- .../test/itkBinaryNotImageFilterTest.cxx | 85 +++++++++++++ ...tkStatisticsRelabelLabelMapFilterTest1.cxx | 29 ++--- .../test/CMakeLists.txt | 25 +++- .../itkAnchorErodeDilateImageFilterTest.cxx | 48 ++++++++ .../itkAnchorOpenCloseImageFilterTest.cxx | 44 +++++++ ...ayscaleConnectedClosingImageFilterTest.cxx | 9 +- ...ayscaleConnectedOpeningImageFilterTest.cxx | 11 +- ...vingHistogramMorphologyImageFilterTest.cxx | 48 ++++++++ ...erkGilWermanErodeDilateImageFilterTest.cxx | 47 ++++++++ .../itkDiscreteGaussianImageFilterTest.cxx | 35 +++++- .../itkBinaryThresholdImageFilterTest.cxx | 9 ++ Modules/IO/LSM/test/itkLSMImageIOTest.cxx | 55 ++++----- Modules/IO/MINC/test/itkMINCImageIOTest2.cxx | 23 ++-- .../MeshBYU/test/itkMeshFileReadWriteTest.cxx | 58 ++++++++- Modules/IO/Meta/test/CMakeLists.txt | 2 +- Modules/IO/Meta/test/itkMetaImageIOTest.cxx | 57 +++++---- Modules/IO/Meta/test/testMetaArray.cxx | 8 +- Modules/IO/NIFTI/test/itkNiftiImageIOTest.cxx | 16 ++- Modules/IO/NRRD/test/itkNrrdImageIOTest.h | 51 ++++---- Modules/IO/RAW/test/itkRawImageIOTest.cxx | 78 ++++++------ Modules/IO/RAW/test/itkRawImageIOTest2.cxx | 14 ++- ...tkPolygonGroupSpatialObjectXMLFileTest.cxx | 17 ++- ...eSparseFiniteDifferenceImageFilterTest.cxx | 24 +++- .../Numerics/Statistics/test/CMakeLists.txt | 2 +- ...ormRandomSpatialNeighborSubsamplerTest.cxx | 73 +++++------ ...VectorContainerToListSampleAdaptorTest.cxx | 38 +++++- ...tkLevelSetMotionRegistrationFilterTest.cxx | 32 +++-- .../test/itkSyNImageRegistrationTest.cxx | 20 +-- .../itkScalarImageKmeansImageFilterTest.cxx | 52 +++----- ...imumConnectedComponentsImageFilterTest.cxx | 61 ++++------ ...arrowBandCurvesLevelSetImageFilterTest.cxx | 59 ++++----- 52 files changed, 1351 insertions(+), 676 deletions(-) create mode 100644 Modules/Filtering/DistanceMap/test/itkDirectedHausdorffDistanceImageFilterTest.cxx create mode 100644 Modules/Filtering/LabelMap/test/itkBinaryNotImageFilterTest.cxx create mode 100644 Modules/Filtering/MathematicalMorphology/test/itkAnchorErodeDilateImageFilterTest.cxx create mode 100644 Modules/Filtering/MathematicalMorphology/test/itkAnchorOpenCloseImageFilterTest.cxx create mode 100644 Modules/Filtering/MathematicalMorphology/test/itkMovingHistogramMorphologyImageFilterTest.cxx create mode 100644 Modules/Filtering/MathematicalMorphology/test/itkVanHerkGilWermanErodeDilateImageFilterTest.cxx diff --git a/Modules/Filtering/BiasCorrection/test/itkN4BiasFieldCorrectionImageFilterTest.cxx b/Modules/Filtering/BiasCorrection/test/itkN4BiasFieldCorrectionImageFilterTest.cxx index dac309345d3..be788091e68 100644 --- a/Modules/Filtering/BiasCorrection/test/itkN4BiasFieldCorrectionImageFilterTest.cxx +++ b/Modules/Filtering/BiasCorrection/test/itkN4BiasFieldCorrectionImageFilterTest.cxx @@ -128,7 +128,7 @@ N4(int argc, char * argv[]) ImagePointer inputImage = reader->GetOutput(); inputImage->DisconnectPipeline(); - // handle the mask image + // Handle the mask image using MaskImageType = itk::Image; typename MaskImageType::Pointer maskImage = nullptr; @@ -164,15 +164,44 @@ N4(int argc, char * argv[]) maskImage->DisconnectPipeline(); } - // instantiate N4 and assign variables not exposed to the user in this test. + // Instantiate N4 and assign variables not exposed to the user in this test. using CorrecterType = itk::N4BiasFieldCorrectionImageFilter; typename CorrecterType::Pointer correcter = CorrecterType::New(); - correcter->SetSplineOrder(3); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(correcter, N4BiasFieldCorrectionImageFilter, ImageToImageFilter); + + + unsigned int splineOrder = 3; + correcter->SetSplineOrder(splineOrder); + ITK_TEST_SET_GET_VALUE(splineOrder, correcter->GetSplineOrder()); + correcter->SetWienerFilterNoise(0.01); - correcter->SetBiasFieldFullWidthAtHalfMaximum(0.15); - correcter->SetConvergenceThreshold(0.0000001); - // handle the number of iterations + typename CorrecterType::RealType biasFieldFullWidthAtHalfMaximum = 0.15; + correcter->SetBiasFieldFullWidthAtHalfMaximum(biasFieldFullWidthAtHalfMaximum); + ITK_TEST_SET_GET_VALUE(biasFieldFullWidthAtHalfMaximum, correcter->GetBiasFieldFullWidthAtHalfMaximum()); + + typename CorrecterType::RealType convergenceThreshold = 0.0000001; + correcter->SetConvergenceThreshold(convergenceThreshold); + ITK_TEST_SET_GET_VALUE(convergenceThreshold, correcter->GetConvergenceThreshold()); + + unsigned int numberOfHistogramBins = 200; + correcter->SetNumberOfHistogramBins(numberOfHistogramBins); + ITK_TEST_SET_GET_VALUE(numberOfHistogramBins, correcter->GetNumberOfHistogramBins()); + + typename CorrecterType::RealType wienerFilterNoise = 0.01; + correcter->SetWienerFilterNoise(wienerFilterNoise); + ITK_TEST_SET_GET_VALUE(wienerFilterNoise, correcter->GetWienerFilterNoise()); + + typename CorrecterType::MaskPixelType maskLabel = + itk::NumericTraits::OneValue(); + correcter->SetMaskLabel(maskLabel); + ITK_TEST_SET_GET_VALUE(maskLabel, correcter->GetMaskLabel()); + + bool useMaskLabel = false; + ITK_TEST_SET_GET_BOOLEAN(correcter, UseMaskLabel, useMaskLabel); + + // Handle the number of iterations std::vector numIters = ConvertVector(std::string("100x50x50")); if (argc > 5) { @@ -185,17 +214,18 @@ N4(int argc, char * argv[]) maximumNumberOfIterations[d] = numIters[d]; } correcter->SetMaximumNumberOfIterations(maximumNumberOfIterations); + ITK_TEST_SET_GET_VALUE(maximumNumberOfIterations, correcter->GetMaximumNumberOfIterations()); typename CorrecterType::ArrayType numberOfFittingLevels; numberOfFittingLevels.Fill( static_cast(numIters.size())); correcter->SetNumberOfFittingLevels(numberOfFittingLevels); + ITK_TEST_SET_GET_VALUE(numberOfFittingLevels, correcter->GetNumberOfFittingLevels()); - /* B-spline options -- we place this here to take care of the case where - * the user wants to specify things in terms of the spline distance. - * 1. need to pad the images to get as close to possible to the - * requested domain size. - */ + // B-spline options -- we place this here to take care of the case where + // the user wants to specify things in terms of the spline distance. + // 1. need to pad the images to get as close to possible to the + // requested domain size. typename ImageType::PointType newOrigin = inputImage->GetOrigin(); typename CorrecterType::ArrayType numberOfControlPoints; @@ -245,8 +275,9 @@ N4(int argc, char * argv[]) maskImage->DisconnectPipeline(); correcter->SetNumberOfControlPoints(numberOfControlPoints); + ITK_TEST_SET_GET_VALUE(numberOfControlPoints, correcter->GetNumberOfControlPoints()); - // handle the shrink factor + // Handle the shrink factor using ShrinkerType = itk::ShrinkImageFilter; typename ShrinkerType::Pointer shrinker = ShrinkerType::New(); shrinker->SetInput(inputImage); @@ -270,7 +301,7 @@ N4(int argc, char * argv[]) maskImage = maskshrinker->GetOutput(); maskImage->DisconnectPipeline(); - // set the input image and mask image + // Set the input image and mask image correcter->SetInput(inputImage); correcter->SetMaskImage(maskImage); @@ -278,18 +309,8 @@ N4(int argc, char * argv[]) typename CommandType::Pointer observer = CommandType::New(); correcter->AddObserver(itk::IterationEvent(), observer); - try - { - correcter->Update(); - } - catch (const itk::ExceptionObject & excep) - { - std::cerr << "Exception caught !" << std::endl; - std::cerr << excep << std::endl; - return EXIT_FAILURE; - } + ITK_TRY_EXPECT_NO_EXCEPTION(correcter->Update()); - correcter->Print(std::cout, 3); // Test the reconstruction of the log bias field ImagePointer originalInputImage = reader->GetOutput(); @@ -300,7 +321,7 @@ N4(int argc, char * argv[]) correcter->ReconstructBiasField(correcter->GetLogBiasFieldControlPointLattice()); WriteImage(biasField.GetPointer(), (std::string(argv[3]) + "-LogBiasField.nrrd").c_str()); - // output the log bias field control point lattice + // Output the log bias field control point lattice WriteImage(correcter->GetLogBiasFieldControlPointLattice(), argv[3]); return EXIT_SUCCESS; @@ -315,7 +336,7 @@ itkN4BiasFieldCorrectionImageFilterTest(int argc, char * argv[]) << "outputLogControlPointLattice [shrinkFactor,default=1] " << "[numberOfIterations,default=100x50x50] " << " [maskImageWithLabelEqualTo1] [splineDistance,default=200]" << std::endl; - exit(EXIT_FAILURE); + return EXIT_FAILURE; } switch (std::stoi(argv[1])) @@ -328,6 +349,6 @@ itkN4BiasFieldCorrectionImageFilterTest(int argc, char * argv[]) default: std::cerr << "Unsupported dimension" << std::endl; - exit(EXIT_FAILURE); + return EXIT_FAILURE; } } diff --git a/Modules/Filtering/BinaryMathematicalMorphology/test/itkBinaryClosingByReconstructionImageFilterTest.cxx b/Modules/Filtering/BinaryMathematicalMorphology/test/itkBinaryClosingByReconstructionImageFilterTest.cxx index 7ee546adaec..9e303bead45 100644 --- a/Modules/Filtering/BinaryMathematicalMorphology/test/itkBinaryClosingByReconstructionImageFilterTest.cxx +++ b/Modules/Filtering/BinaryMathematicalMorphology/test/itkBinaryClosingByReconstructionImageFilterTest.cxx @@ -28,42 +28,61 @@ int itkBinaryClosingByReconstructionImageFilterTest(int argc, char * argv[]) { - if (argc != 6) + if (argc < 6) { - std::cerr << "usage: " << itkNameOfTestExecutableMacro(argv) << " input output conn fg kernelSize" << std::endl; - // std::cerr << " : " << std::endl; - exit(1); + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) + << " inputFileName outputFileName fullyConnected foregroundValue kernelSize" << std::endl; + return EXIT_FAILURE; } - constexpr int dim = 2; + constexpr unsigned int Dimension = 2; - using IType = itk::Image; + using PixelType = unsigned char; - using ReaderType = itk::ImageFileReader; + using ImageType = itk::Image; + + using ReaderType = itk::ImageFileReader; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(argv[1]); - reader->Update(); - using KernelType = itk::BinaryBallStructuringElement; + ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); + + + using KernelType = itk::BinaryBallStructuringElement; KernelType ball; KernelType::SizeType ballSize; ballSize.Fill(std::stoi(argv[5])); ball.SetRadius(ballSize); ball.CreateStructuringElement(); - using I2LType = itk::BinaryClosingByReconstructionImageFilter; - I2LType::Pointer reconstruction = I2LType::New(); - reconstruction->SetInput(reader->GetOutput()); - reconstruction->SetKernel(ball); - reconstruction->SetFullyConnected(std::stoi(argv[3])); - reconstruction->SetForegroundValue(std::stoi(argv[4])); - // reconstruction->SetBackgroundValue( std::stoi(argv[6]) ); - itk::SimpleFilterWatcher watcher(reconstruction, "filter"); + using FilterType = itk::BinaryClosingByReconstructionImageFilter; + FilterType::Pointer reconstructionFilter = FilterType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(reconstructionFilter, BinaryClosingByReconstructionImageFilter, KernelImageFilter); + + + itk::SimpleFilterWatcher watcher(reconstructionFilter, "filter"); + + auto fullyConnected = static_cast(std::stoi(argv[3])); + ITK_TEST_SET_GET_BOOLEAN(reconstructionFilter, FullyConnected, fullyConnected); - using WriterType = itk::ImageFileWriter; + typename FilterType::InputImagePixelType foregroundValue = std::stoi(argv[4]); + reconstructionFilter->SetForegroundValue(foregroundValue); + ITK_TEST_SET_GET_VALUE(foregroundValue, reconstructionFilter->GetForegroundValue()); + + reconstructionFilter->SetKernel(ball); + + reconstructionFilter->SetInput(reader->GetOutput()); + + using WriterType = itk::ImageFileWriter; WriterType::Pointer writer = WriterType::New(); - writer->SetInput(reconstruction->GetOutput()); + writer->SetInput(reconstructionFilter->GetOutput()); writer->SetFileName(argv[2]); - writer->Update(); - return 0; + + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); + + + std::cout << "Test finished." << std::endl; + return EXIT_SUCCESS; } diff --git a/Modules/Filtering/DisplacementField/test/CMakeLists.txt b/Modules/Filtering/DisplacementField/test/CMakeLists.txt index 0df3870e0ab..25131e8000b 100644 --- a/Modules/Filtering/DisplacementField/test/CMakeLists.txt +++ b/Modules/Filtering/DisplacementField/test/CMakeLists.txt @@ -80,7 +80,7 @@ itk_add_test(NAME itkTransformToDisplacementFieldFilterTest03 --compare ${ITK_TEST_OUTPUT_DIR}/transformedImage.nii ${ITK_TEST_OUTPUT_DIR}/warpedImage.nii --compareNumberOfPixelsTolerance 20 - itkTransformToDisplacementFieldFilterTest1 ${ITK_TEST_OUTPUT_DIR}/transformedImage.nii ${ITK_TEST_OUTPUT_DIR}/warpedImage.nii) + itkTransformToDisplacementFieldFilterTest1 ${ITK_TEST_OUTPUT_DIR}/transformedImage.nii ${ITK_TEST_OUTPUT_DIR}/warpedImage.nii 1) itk_add_test(NAME itkDisplacementFieldTransformCloneTest COMMAND ITKDisplacementFieldTestDriver itkDisplacementFieldTransformCloneTest) itk_add_test(NAME itkExponentialDisplacementFieldImageFilterTest diff --git a/Modules/Filtering/DisplacementField/test/itkDisplacementFieldJacobianDeterminantFilterTest.cxx b/Modules/Filtering/DisplacementField/test/itkDisplacementFieldJacobianDeterminantFilterTest.cxx index 1e316fa9f60..173828da477 100644 --- a/Modules/Filtering/DisplacementField/test/itkDisplacementFieldJacobianDeterminantFilterTest.cxx +++ b/Modules/Filtering/DisplacementField/test/itkDisplacementFieldJacobianDeterminantFilterTest.cxx @@ -35,7 +35,6 @@ TestDisplacementJacobianDeterminantValue() // In this case, the image to be warped is also a vector field. using VectorImageType = FieldType; - //============================================================= std::cout << "Create the dispacementfield image pattern." << std::endl; VectorImageType::RegionType region; @@ -63,7 +62,7 @@ TestDisplacementJacobianDeterminantValue() // std::cout << "Setting: " << values << " at " << inIter.GetIndex() << std::endl; } - // displacementfield: + // Displacement field: //|-------------------------------------------| //| [0.25;0.5] | [0.375;0.75] | [0.75;1] | //|-------------------------------------------| @@ -74,9 +73,12 @@ TestDisplacementJacobianDeterminantValue() // // J(1,1) = [ (.625-.125)/2 (.5-.25)/2; (.375-.125)/2 (.75-0.0)/2] =[ .25 .125; .125 .375] // det((J+I)(1,1))=((.25+1.0)*(.375+1.0))-(.125*.125) = 1.703125; - const float KNOWN_ANSWER = (((.25 + 1.0) * (.375 + 1.0)) - (.125 * .125)); - itk::DisplacementFieldJacobianDeterminantFilter::Pointer filter = - itk::DisplacementFieldJacobianDeterminantFilter::New(); + const float expectedJacobianDeterminant = (((.25 + 1.0) * (.375 + 1.0)) - (.125 * .125)); + + using FilterType = itk::DisplacementFieldJacobianDeterminantFilter; + FilterType::Pointer filter = FilterType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, DisplacementFieldJacobianDeterminantFilter, ImageToImageFilter); bool useImageSpacing = true; @@ -94,15 +96,23 @@ TestDisplacementJacobianDeterminantValue() filter->SetInput(dispacementfield); filter->Update(); + + itk::Image::Pointer output = filter->GetOutput(); VectorImageType::IndexType index; index[0] = 1; index[1] = 1; + float jacobianDeterminant = output->GetPixel(index); // std::cout << "Output " << output->GetPixel(index) << std::endl; - if (std::abs(output->GetPixel(index) - KNOWN_ANSWER) > 1e-13) + double epsilon = 1e-13; + if (std::abs(jacobianDeterminant - expectedJacobianDeterminant) > epsilon) { - std::cout << "Test failed." << KNOWN_ANSWER << "!=" << output->GetPixel(index) << std::endl; + std::cerr << "Test failed!" << std::endl; + std::cerr << "Error in pixel value at index [" << index << "]" << std::endl; + std::cerr << "Expected value " << jacobianDeterminant << std::endl; + std::cerr << " differs from " << expectedJacobianDeterminant; + std::cerr << " by more than " << epsilon << std::endl; testPassed = false; } else @@ -132,9 +142,11 @@ itkDisplacementFieldJacobianDeterminantFilterTest(int, char *[]) using FilterType = itk::DisplacementFieldJacobianDeterminantFilter; FilterType::Pointer filter = FilterType::New(); - filter->Print(std::cout); - // Run Test + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, DisplacementFieldJacobianDeterminantFilter, ImageToImageFilter); + + + // Run the test itk::Size<3> sz; sz[0] = 100; sz[1] = 100; @@ -145,12 +157,15 @@ itkDisplacementFieldJacobianDeterminantFilterTest(int, char *[]) test1.Execute(); filter->Print(std::cout); - // Run the Test again with ImageSpacingOn - filter->SetUseImageSpacingOn(); + // Run the test again with ImageSpacingOn + bool useImageSpacing = true; + ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing); + + test1.Execute(); filter->Print(std::cout); - // Run the Test again with specified weights + // Run the test again with specified weights float weights[3] = { 1.0, 2.0, 3.0 }; filter->SetDerivativeWeights(weights); test1.Execute(); @@ -165,5 +180,8 @@ itkDisplacementFieldJacobianDeterminantFilterTest(int, char *[]) { return EXIT_FAILURE; } + + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Filtering/DisplacementField/test/itkTimeVaryingVelocityFieldTransformTest.cxx b/Modules/Filtering/DisplacementField/test/itkTimeVaryingVelocityFieldTransformTest.cxx index a954ee4366d..567ab32f907 100644 --- a/Modules/Filtering/DisplacementField/test/itkTimeVaryingVelocityFieldTransformTest.cxx +++ b/Modules/Filtering/DisplacementField/test/itkTimeVaryingVelocityFieldTransformTest.cxx @@ -17,13 +17,20 @@ *=========================================================================*/ #include "itkTimeVaryingVelocityFieldTransform.h" +#include "itkTestingMacros.h" + int itkTimeVaryingVelocityFieldTransformTest(int, char *[]) { - using VectorType = itk::Vector; - using DisplacementFieldType = itk::Image; - using TimeVaryingVelocityFieldType = itk::Image; + constexpr unsigned int ComponentDimension = 3; + constexpr unsigned int VelocityFieldDimension = 4; + + using ComponentType = double; + + using VectorType = itk::Vector; + using DisplacementFieldType = itk::Image; + using TimeVaryingVelocityFieldType = itk::Image; TimeVaryingVelocityFieldType::PointType origin; origin.Fill(0.0); @@ -95,12 +102,23 @@ itkTimeVaryingVelocityFieldTransformTest(int, char *[]) // Now test the transform - using TransformType = itk::TimeVaryingVelocityFieldTransform; + using TransformType = itk::TimeVaryingVelocityFieldTransform; TransformType::Pointer transform = TransformType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(transform, TimeVaryingVelocityFieldTransform, VelocityFieldTransform); + transform->SetLowerTimeBound(0.0); transform->SetUpperTimeBound(1.0); + + ITK_TRY_EXPECT_EXCEPTION(transform->IntegrateVelocityField()); + + transform->SetVelocityField(timeVaryingVelocityField); - transform->IntegrateVelocityField(); + ITK_TEST_SET_GET_VALUE(timeVaryingVelocityField, transform->GetModifiableTimeVaryingVelocityField()); + ITK_TEST_SET_GET_VALUE(timeVaryingVelocityField, transform->GetTimeVaryingVelocityField()); + + ITK_TRY_EXPECT_NO_EXCEPTION(transform->IntegrateVelocityField()); + // Now Clone the Transform and test transform again TransformType::Pointer clone = transform->Clone(); @@ -155,5 +173,7 @@ itkTimeVaryingVelocityFieldTransformTest(int, char *[]) transform->Print(std::cout, 3); + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Filtering/DisplacementField/test/itkTransformToDisplacementFieldFilterTest.cxx b/Modules/Filtering/DisplacementField/test/itkTransformToDisplacementFieldFilterTest.cxx index 5372fdd35a9..a2914649e23 100644 --- a/Modules/Filtering/DisplacementField/test/itkTransformToDisplacementFieldFilterTest.cxx +++ b/Modules/Filtering/DisplacementField/test/itkTransformToDisplacementFieldFilterTest.cxx @@ -25,12 +25,13 @@ int itkTransformToDisplacementFieldFilterTest(int argc, char * argv[]) { - /** Check command line arguments. */ + if (argc < 3) { + std::cerr << "Missing Parameters." << std::endl; std::cerr << "Usage: "; std::cerr << itkNameOfTestExecutableMacro(argv) - << " [bSplineParametersFile]" << std::endl; + << " transformName displacementFieldFileName [bSplineParametersFile]" << std::endl; return EXIT_FAILURE; } @@ -42,7 +43,7 @@ itkTransformToDisplacementFieldFilterTest(int argc, char * argv[]) bSplineParametersFile = argv[3]; } - /** Typedefs. */ + // Typedefs. constexpr unsigned int Dimension = 2; using ScalarPixelType = float; using CoordRepresentationType = double; @@ -69,7 +70,7 @@ itkTransformToDisplacementFieldFilterTest(int argc, char * argv[]) using IndexType = DisplacementFieldGeneratorType::IndexType; using WriterType = itk::ImageFileWriter; - /** Create output information. */ + // Create output information. SizeType size; size.Fill(20); IndexType index; @@ -79,18 +80,18 @@ itkTransformToDisplacementFieldFilterTest(int argc, char * argv[]) OriginType origin; origin.Fill(-10.0); - /** Create transforms. */ + // Create transforms. AffineTransformType::Pointer affineTransform = AffineTransformType::New(); BSplineTransformType::Pointer bSplineTransform = BSplineTransformType::New(); if (transformName == "Affine") { - /** Set the options. */ + // Set the options. OriginType centerOfRotation; centerOfRotation[0] = -3.0; centerOfRotation[1] = -3.0; affineTransform->SetCenter(centerOfRotation); - /** Create and set parameters. */ + // Create and set parameters. ParametersType parameters(affineTransform->GetNumberOfParameters()); parameters[0] = 1.1; parameters[1] = 0.1; @@ -102,7 +103,7 @@ itkTransformToDisplacementFieldFilterTest(int argc, char * argv[]) } else if (transformName == "BSpline") { - /** Set the options. */ + // Set the options. BSplineTransformType::PhysicalDimensionsType dimensions; for (unsigned int d = 0; d < Dimension; ++d) @@ -121,7 +122,7 @@ itkTransformToDisplacementFieldFilterTest(int argc, char * argv[]) bSplineTransform->SetTransformDomainMeshSize(meshSize); bSplineTransform->SetTransformDomainDirection(direction); - /** Create and set parameters. */ + // Create and set parameters. ParametersType parameters(bSplineTransform->GetNumberOfParameters()); std::ifstream input(bSplineParametersFile.c_str()); if (input.is_open()) @@ -145,20 +146,28 @@ itkTransformToDisplacementFieldFilterTest(int argc, char * argv[]) return EXIT_FAILURE; } - /** Create an setup displacement field generator. */ + // Create an setup displacement field generator. DisplacementFieldGeneratorType::Pointer defGenerator = DisplacementFieldGeneratorType::New(); - std::cout << "Name of Class: " << defGenerator->GetNameOfClass() << std::endl; + + ITK_EXERCISE_BASIC_OBJECT_METHODS(defGenerator, TransformToDisplacementFieldFilter, ImageSource); + + defGenerator->SetSize(size); + ITK_TEST_SET_GET_VALUE(size, defGenerator->GetSize()); + defGenerator->SetOutputSpacing(spacing); + ITK_TEST_SET_GET_VALUE(spacing, defGenerator->GetOutputSpacing()); + defGenerator->SetOutputOrigin(origin); + ITK_TEST_SET_GET_VALUE(origin, defGenerator->GetOutputOrigin()); + defGenerator->SetOutputStartIndex(index); - // - // for coverage, exercise access methods - spacing = defGenerator->GetOutputSpacing(); - origin = defGenerator->GetOutputOrigin(); - DisplacementFieldGeneratorType::DirectionType direction = defGenerator->GetOutputDirection(); - std::cout << "Spacing " << spacing << " Origin " << origin << std::endl << "Direction " << direction << std::endl; - // defGenerator->SetOutputDirection( direction ); + ITK_TEST_SET_GET_VALUE(index, defGenerator->GetOutputStartIndex()); + + DisplacementFieldGeneratorType::DirectionType direction; + direction.SetIdentity(); + ITK_TEST_SET_GET_VALUE(direction, defGenerator->GetOutputDirection()); + if (transformName == "Affine") { defGenerator->SetTransform(affineTransform); @@ -169,21 +178,14 @@ itkTransformToDisplacementFieldFilterTest(int argc, char * argv[]) } std::cout << "Transform: " << defGenerator->GetTransform() << std::endl; - /** Write displacement field to disk. */ + // Write displacement field to disk. WriterType::Pointer writer = WriterType::New(); writer->SetInput(defGenerator->GetOutput()); writer->SetFileName(fileName.c_str()); - try - { - writer->Update(); - } - catch (const itk::ExceptionObject & err) - { - std::cerr << "Exception detected while generating displacement field" << fileName << std::endl; - std::cerr << " : " << err << std::endl; - return EXIT_FAILURE; - } + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Filtering/DisplacementField/test/itkTransformToDisplacementFieldFilterTest1.cxx b/Modules/Filtering/DisplacementField/test/itkTransformToDisplacementFieldFilterTest1.cxx index a2f82fb05b0..58f076375d6 100644 --- a/Modules/Filtering/DisplacementField/test/itkTransformToDisplacementFieldFilterTest1.cxx +++ b/Modules/Filtering/DisplacementField/test/itkTransformToDisplacementFieldFilterTest1.cxx @@ -28,20 +28,24 @@ #include "itkEuler3DTransform.h" #include "itkResampleImageFilter.h" #include "itkWarpImageFilter.h" +#include "itkTestingMacros.h" + int itkTransformToDisplacementFieldFilterTest1(int argc, char * argv[]) { - if (argc < 2) + if (argc < 3) { + std::cerr << "Missing Parameters." << std::endl; std::cerr << "Usage: "; - std::cerr << argv[0] << " " << std::endl; + std::cerr << itkNameOfTestExecutableMacro(argv) + << " resampledImageFileName displacementFieldFileName useReferenceImage" << std::endl; return EXIT_FAILURE; } const char * resampledImageFileName = argv[1]; const char * displacementFieldFileName = argv[2]; - /** Typedefs. */ + // Typedefs. constexpr unsigned int Dimension = 3; using ScalarPixelType = float; using CoordRepresentationType = double; @@ -67,7 +71,7 @@ itkTransformToDisplacementFieldFilterTest1(int argc, char * argv[]) using DirectionType = ImageType::DirectionType; - /** Create input image. */ + // Create input image. SizeType size; size.Fill(24); IndexType index; @@ -131,7 +135,7 @@ itkTransformToDisplacementFieldFilterTest1(int argc, char * argv[]) } } - /** Set Output information. */ + // Set Output information. IndexType outputIndex; outputIndex.Fill(0); SpacingType outputSpacing; @@ -149,17 +153,17 @@ itkTransformToDisplacementFieldFilterTest1(int argc, char * argv[]) outputOrigin[2] = -60; DirectionType outputDirection = inputDirection; - /** Create transforms. */ + // Create transforms. TransformType::Pointer eulerTransform = TransformType::New(); { - /** Set the options. */ + // Set the options. IndexType imageCenter; imageCenter.Fill(11); PointType centerPoint; image->TransformIndexToPhysicalPoint(imageCenter, centerPoint); eulerTransform->SetCenter(centerPoint); - /** Create and set parameters. */ + // Create and set parameters. ParametersType parameters(eulerTransform->GetNumberOfParameters()); parameters[0] = 9.0 * (itk::Math::pi) / 180.0; parameters[1] = 6.0 * (itk::Math::pi) / 180.0; @@ -170,7 +174,7 @@ itkTransformToDisplacementFieldFilterTest1(int argc, char * argv[]) eulerTransform->SetParameters(parameters); } - /** Use ResampleImageFilter to get transformed image. */ + // Use ResampleImageFilter to get transformed image. using ResampleImageFilter = itk::ResampleImageFilter; ResampleImageFilter::Pointer resample = ResampleImageFilter::New(); resample->SetInput(image); @@ -186,33 +190,23 @@ itkTransformToDisplacementFieldFilterTest1(int argc, char * argv[]) WriterType::Pointer writer1 = WriterType::New(); writer1->SetInput(resample->GetOutput()); writer1->SetFileName(resampledImageFileName); - try - { - writer1->Update(); - } - catch (const itk::ExceptionObject & err) - { - std::cerr << "Exception detected while writing image " << resampledImageFileName; - std::cerr << " : " << err << std::endl; - return EXIT_FAILURE; - } - /** Create an setup deformation field generator. */ + ITK_TRY_EXPECT_NO_EXCEPTION(writer1->Update()); + + + // Create an setup deformation field generator. DisplacementFieldGeneratorType::Pointer defGenerator = DisplacementFieldGeneratorType::New(); - defGenerator->UseReferenceImageOn(); + + auto useReferenceImage = static_cast(std::stoi(argv[3])); + ITK_TEST_SET_GET_BOOLEAN(defGenerator, UseReferenceImage, useReferenceImage); + defGenerator->SetReferenceImage(resample->GetOutput()); defGenerator->SetTransform(eulerTransform); - try - { - defGenerator->Update(); - } - catch (const itk::ExceptionObject & err) - { - std::cerr << "Exception detected while generating deformation field"; - std::cerr << " : " << err << std::endl; - return EXIT_FAILURE; - } - /** Use WarpImageFilter with deformation field. */ + + ITK_TRY_EXPECT_NO_EXCEPTION(defGenerator->Update()); + + + // Use WarpImageFilter with deformation field. WarpImageType::Pointer warper = WarpImageType::New(); warper->SetOutputSize(outputRegion.GetSize()); warper->SetOutputStartIndex(outputRegion.GetIndex()); @@ -221,29 +215,17 @@ itkTransformToDisplacementFieldFilterTest1(int argc, char * argv[]) warper->SetOutputDirection(outputDirection); warper->SetDisplacementField(defGenerator->GetOutput()); warper->SetInput(image); - try - { - warper->Update(); - } - catch (const itk::ExceptionObject & err) - { - std::cerr << "Exception detected while warping image"; - std::cerr << " : " << err << std::endl; - return EXIT_FAILURE; - } + + ITK_TRY_EXPECT_NO_EXCEPTION(warper->Update()); + + WriterType::Pointer writer2 = WriterType::New(); writer2->SetInput(warper->GetOutput()); writer2->SetFileName(displacementFieldFileName); - try - { - writer2->Update(); - } - catch (const itk::ExceptionObject & err) - { - std::cerr << "Exception detected while writing image " << displacementFieldFileName; - std::cerr << " : " << err << std::endl; - return EXIT_FAILURE; - } + ITK_TRY_EXPECT_NO_EXCEPTION(writer2->Update()); + + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Filtering/DistanceMap/test/CMakeLists.txt b/Modules/Filtering/DistanceMap/test/CMakeLists.txt index 0dbb1cb4194..bb645319272 100644 --- a/Modules/Filtering/DistanceMap/test/CMakeLists.txt +++ b/Modules/Filtering/DistanceMap/test/CMakeLists.txt @@ -3,6 +3,7 @@ set(ITKDistanceMapTests itkDanielssonDistanceMapImageFilterTest.cxx itkDanielssonDistanceMapImageFilterTest1.cxx itkDanielssonDistanceMapImageFilterTest2.cxx +itkDirectedHausdorffDistanceImageFilterTest.cxx itkSignedDanielssonDistanceMapImageFilterTest.cxx itkSignedDanielssonDistanceMapImageFilterTest1.cxx itkSignedDanielssonDistanceMapImageFilterTest2.cxx @@ -32,12 +33,18 @@ itk_add_test(NAME itkDanielssonDistanceMapImageFilterTest1 COMMAND ITKDistanceMapTestDriver --compare DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/itkDanielssonDistanceMapImageFilterTest1.mhd,itkDanielssonDistanceMapImageFilterTest1.zraw} ${ITK_TEST_OUTPUT_DIR}/itkDanielssonDistanceMapImageFilterTest1.mhd - itkDanielssonDistanceMapImageFilterTest1 DATA{${ITK_DATA_ROOT}/Input/BinaryImageWithVariousShapes01.png} ${ITK_TEST_OUTPUT_DIR}/itkDanielssonDistanceMapImageFilterTest1.mhd) + itkDanielssonDistanceMapImageFilterTest1 DATA{${ITK_DATA_ROOT}/Input/BinaryImageWithVariousShapes01.png} ${ITK_TEST_OUTPUT_DIR}/itkDanielssonDistanceMapImageFilterTest1.mhd 0 0 1) itk_add_test(NAME itkDanielssonDistanceMapImageFilterTest2 COMMAND ITKDistanceMapTestDriver --compare DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/itkDanielssonDistanceMapImageFilterTest2.png} ${ITK_TEST_OUTPUT_DIR}/itkDanielssonDistanceMapImageFilterTest2.png itkDanielssonDistanceMapImageFilterTest2 DATA{${ITK_DATA_ROOT}/Input/BinaryImageWithVariousShapes01.png} ${ITK_TEST_OUTPUT_DIR}/itkDanielssonDistanceMapImageFilterTest2.png) +itk_add_test(NAME itkDirectedHausdorffDistanceImageFilterTest + COMMAND ITKDistanceMapTestDriver + --compare DATA{Baseline/itkDirectedHausdorffDistanceImageFilterTest.png} + ${ITK_TEST_OUTPUT_DIR}/itkDirectedHausdorffDistanceImageFilterTest.png + itkDirectedHausdorffDistanceImageFilterTest DATA{${ITK_DATA_ROOT}/Input/BinaryImageWithVariousShapes01.png} + DATA{${ITK_DATA_ROOT}/Input/BinaryImageWithVariousShapes01.png} ${ITK_TEST_OUTPUT_DIR}/itkDirectedHausdorffDistanceImageFilterTest.png) itk_add_test(NAME itkSignedDanielssonDistanceMapImageFilterTest COMMAND ITKDistanceMapTestDriver itkSignedDanielssonDistanceMapImageFilterTest) itk_add_test(NAME itkSignedDanielssonDistanceMapImageFilterTest1 diff --git a/Modules/Filtering/DistanceMap/test/itkContourDirectedMeanDistanceImageFilterTest.cxx b/Modules/Filtering/DistanceMap/test/itkContourDirectedMeanDistanceImageFilterTest.cxx index 46cd5701786..191ca94905e 100644 --- a/Modules/Filtering/DistanceMap/test/itkContourDirectedMeanDistanceImageFilterTest.cxx +++ b/Modules/Filtering/DistanceMap/test/itkContourDirectedMeanDistanceImageFilterTest.cxx @@ -81,10 +81,13 @@ itkContourDirectedMeanDistanceImageFilterTest(int, char *[]) auto useImageSpacing = true; - // compute the directed Mean distance h(image1,image2) + // Compute the directed Mean distance h(image1,image2) { using FilterType = itk::ContourDirectedMeanDistanceImageFilter; - FilterType::Pointer filter = FilterType::New(); + FilterType::Pointer filter = FilterType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, ContourDirectedMeanDistanceImageFilter, ImageToImageFilter); + itk::SimpleFilterWatcher watcher(filter, "filter"); @@ -93,10 +96,8 @@ itkContourDirectedMeanDistanceImageFilterTest(int, char *[]) filter->SetInput1(image1); filter->SetInput2(image2); filter->Update(); - filter->Print(std::cout); - - // check results + // Check results FilterType::RealType trueDistance = 8.37831; FilterType::RealType distance = filter->GetContourDirectedMeanDistance(); @@ -111,11 +112,13 @@ itkContourDirectedMeanDistanceImageFilterTest(int, char *[]) } } - // compute the directed Mean distance h(image2,image1) + // Compute the directed Mean distance h(image2,image1) { using FilterType = itk::ContourDirectedMeanDistanceImageFilter; FilterType::Pointer filter = FilterType::New(); + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, ContourDirectedMeanDistanceImageFilter, ImageToImageFilter); + ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing); @@ -124,7 +127,7 @@ itkContourDirectedMeanDistanceImageFilterTest(int, char *[]) filter->Update(); - // check results + // Check results FilterType::RealType trueDistance = 4.2053; FilterType::RealType distance = filter->GetContourDirectedMeanDistance(); diff --git a/Modules/Filtering/DistanceMap/test/itkDanielssonDistanceMapImageFilterTest.cxx b/Modules/Filtering/DistanceMap/test/itkDanielssonDistanceMapImageFilterTest.cxx index 8239c4e01bb..b43649e7263 100644 --- a/Modules/Filtering/DistanceMap/test/itkDanielssonDistanceMapImageFilterTest.cxx +++ b/Modules/Filtering/DistanceMap/test/itkDanielssonDistanceMapImageFilterTest.cxx @@ -19,6 +19,7 @@ #include "itkShowDistanceMap.h" #include "itkDanielssonDistanceMapImageFilter.h" #include "itkStdStreamStateSave.h" +#include "itkTestingMacros.h" int itkDanielssonDistanceMapImageFilterTest(int, char *[]) @@ -49,11 +50,10 @@ itkDanielssonDistanceMapImageFilterTest(int, char *[]) inputImage2D->SetRequestedRegion(region2D); inputImage2D->Allocate(true); - /* Set pixel (4,4) with the value 1 - * and pixel (1,6) with the value 2 - * The Danielsson Distance is performed for each pixel with a value > 0 - * The ClosestPoints computation is based on the value of the pixel. - */ + // Set pixel (4,4) with the value 1 + // and pixel (1,6) with the value 2 + // The Danielsson Distance is performed for each pixel with a value > 0 + // The ClosestPoints computation is based on the value of the pixel. index2D[0] = 4; index2D[1] = 4; @@ -62,11 +62,14 @@ itkDanielssonDistanceMapImageFilterTest(int, char *[]) index2D[1] = 6; inputImage2D->SetPixel(index2D, 2); - /* Create Danielsson Distance Map filter */ + // Create Danielsson Distance Map filter using myFilterType2D = itk::DanielssonDistanceMapImageFilter; myFilterType2D::Pointer filter2D = myFilterType2D::New(); + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter2D, DanielssonDistanceMapImageFilter, ImageToImageFilter); + + filter2D->SetInput(inputImage2D); myImageType2D2::Pointer outputDistance2D = filter2D->GetOutput(); @@ -77,13 +80,14 @@ itkDanielssonDistanceMapImageFilterTest(int, char *[]) myFilterType2D::VectorImagePointer outputComponents = filter2D->GetVectorDistanceMap(); - filter2D->Update(); + ITK_TRY_EXPECT_NO_EXCEPTION(filter2D->Update()); + ShowDistanceMap(outputDistance2D); std::cout << "Voronoi Map Image 2D" << std::endl << std::endl; ShowDistanceMap(outputVoronoi2D); - /* Show VectorsComponents Points map */ + // Show VectorsComponents Points map std::cout << std::endl << std::endl; std::cout << "Components Map Image 2D" << std::endl << std::endl; @@ -119,22 +123,17 @@ itkDanielssonDistanceMapImageFilterTest(int, char *[]) } - /* Test Squared Distance functionality */ + // Test Squared Distance functionality myImageType2D2::IndexType index; index[0] = 0; index[1] = 0; const double distance1 = outputDistance2D->GetPixel(index); - filter2D->SquaredDistanceOn(); + bool squaredDistance = true; + ITK_TEST_SET_GET_BOOLEAN(filter2D, SquaredDistance, squaredDistance); - if (filter2D->GetSquaredDistance() != true) - { - std::cerr << "filter2D->GetSquaredDistance() != true" << std::endl; - return EXIT_FAILURE; - } + ITK_TRY_EXPECT_NO_EXCEPTION(filter2D->Update()); - filter2D->SetSquaredDistance(true); - filter2D->Update(); const double distance2 = outputDistance2D->GetPixel(index); const myImageType2D2::PixelType epsilon = 1e-5; @@ -148,7 +147,7 @@ itkDanielssonDistanceMapImageFilterTest(int, char *[]) ShowDistanceMap(outputDistance2D); - /* Test for images with anisotropic spacing */ + // Test for images with anisotropic spacing myImageType2D1::SpacingType anisotropicSpacing; anisotropicSpacing[0] = 1.0; @@ -163,25 +162,14 @@ itkDanielssonDistanceMapImageFilterTest(int, char *[]) inputImage2D->SetPixel(index2D, 1); filter2D->SetInput(inputImage2D); - filter2D->SetInputIsBinary(true); - - if (filter2D->GetInputIsBinary() != true) - { - std::cerr << "filter2D->GetInputIsBinary() != true" << std::endl; - return EXIT_FAILURE; - } + bool inputIsBinary = true; + ITK_TEST_SET_GET_BOOLEAN(filter2D, InputIsBinary, inputIsBinary); - filter2D->UseImageSpacingOn(); - - if (filter2D->GetUseImageSpacing() != true) - { - std::cerr << "filter2D->GetUseImageSpacing() != true" << std::endl; - return EXIT_FAILURE; - } + bool useImageSpacing = true; + ITK_TEST_SET_GET_BOOLEAN(filter2D, UseImageSpacing, useImageSpacing); - filter2D->SetUseImageSpacing(true); - filter2D->Update(); + ITK_TRY_EXPECT_NO_EXCEPTION(filter2D->Update()); index2D[1] = 5; auto expectedValue = static_cast(anisotropicSpacing[1]); @@ -237,7 +225,10 @@ itkDanielssonDistanceMapImageFilterTest(int, char *[]) myFilterType3D::Pointer filter3D = myFilterType3D::New(); filter3D->SetInput(inputImage3D); - filter3D->Update(); + ITK_TRY_EXPECT_NO_EXCEPTION(filter3D->Update()); + + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Filtering/DistanceMap/test/itkDanielssonDistanceMapImageFilterTest1.cxx b/Modules/Filtering/DistanceMap/test/itkDanielssonDistanceMapImageFilterTest1.cxx index bbd82a9ac64..2d33562a176 100644 --- a/Modules/Filtering/DistanceMap/test/itkDanielssonDistanceMapImageFilterTest1.cxx +++ b/Modules/Filtering/DistanceMap/test/itkDanielssonDistanceMapImageFilterTest1.cxx @@ -19,14 +19,17 @@ #include "itkImageFileWriter.h" #include "itkDanielssonDistanceMapImageFilter.h" +#include "itkTestingMacros.h" int itkDanielssonDistanceMapImageFilterTest1(int argc, char * argv[]) { - if (argc < 3) + if (argc < 6) { - std::cerr << "Usage: " << argv[0] << " InputImage OutputImage\n"; - return -1; + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) + << " InputImage OutputImage squaredDistance inputIsBinary useImageSpacing" << std::endl; + return EXIT_FAILURE; } constexpr unsigned int ImageDimension = 2; @@ -41,19 +44,37 @@ itkDanielssonDistanceMapImageFilterTest1(int argc, char * argv[]) ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(argv[1]); - reader->Update(); + + ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); using FilterType = itk::DanielssonDistanceMapImageFilter; FilterType::Pointer filter = FilterType::New(); + + auto squaredDistance = static_cast(std::stoi(argv[3])); + ITK_TEST_SET_GET_BOOLEAN(filter, SquaredDistance, squaredDistance); + + auto inputIsBinary = static_cast(std::stoi(argv[4])); + ITK_TEST_SET_GET_BOOLEAN(filter, InputIsBinary, inputIsBinary); + + auto useImageSpacing = static_cast(std::stoi(argv[5])); + ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing); + + filter->SetInput(reader->GetOutput()); - filter->Update(); + + ITK_TRY_EXPECT_NO_EXCEPTION(filter->Update()); + + filter->Print(std::cout); WriterType::Pointer writer = WriterType::New(); writer->SetInput(filter->GetOutput()); writer->SetFileName(argv[2]); writer->UseCompressionOn(); - writer->Update(); + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); + + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Filtering/DistanceMap/test/itkDanielssonDistanceMapImageFilterTest2.cxx b/Modules/Filtering/DistanceMap/test/itkDanielssonDistanceMapImageFilterTest2.cxx index 30ed93748bb..e283a4114f5 100644 --- a/Modules/Filtering/DistanceMap/test/itkDanielssonDistanceMapImageFilterTest2.cxx +++ b/Modules/Filtering/DistanceMap/test/itkDanielssonDistanceMapImageFilterTest2.cxx @@ -21,14 +21,17 @@ #include "itkRescaleIntensityImageFilter.h" #include "itkDanielssonDistanceMapImageFilter.h" +#include "itkTestingMacros.h" + int itkDanielssonDistanceMapImageFilterTest2(int argc, char * argv[]) { if (argc < 3) { - std::cerr << "Usage: " << argv[0] << " InputImage OutputImage\n"; - return -1; + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " InputImage OutputImage" << std::endl; + return EXIT_FAILURE; } constexpr unsigned int ImageDimension = 2; @@ -43,7 +46,9 @@ itkDanielssonDistanceMapImageFilterTest2(int argc, char * argv[]) ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(argv[1]); - reader->Update(); + + ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); + using ConnectedType = itk::ConnectedComponentImageFilter; ConnectedType::Pointer connectedComponents = ConnectedType::New(); @@ -52,7 +57,10 @@ itkDanielssonDistanceMapImageFilterTest2(int argc, char * argv[]) using FilterType = itk::DanielssonDistanceMapImageFilter; FilterType::Pointer filter = FilterType::New(); filter->SetInput(connectedComponents->GetOutput()); - filter->Update(); + + ITK_TRY_EXPECT_NO_EXCEPTION(filter->Update()); + + filter->Print(std::cout); // Extract the Voronoi map from the distance map filter, rescale it, @@ -67,7 +75,10 @@ itkDanielssonDistanceMapImageFilterTest2(int argc, char * argv[]) writer->SetInput(rescaler->GetOutput()); writer->SetFileName(argv[2]); writer->UseCompressionOn(); - writer->Update(); + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); + + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Filtering/DistanceMap/test/itkDirectedHausdorffDistanceImageFilterTest.cxx b/Modules/Filtering/DistanceMap/test/itkDirectedHausdorffDistanceImageFilterTest.cxx new file mode 100644 index 00000000000..e25b9ab7856 --- /dev/null +++ b/Modules/Filtering/DistanceMap/test/itkDirectedHausdorffDistanceImageFilterTest.cxx @@ -0,0 +1,94 @@ +/*========================================================================= + * + * Copyright NumFOCUS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ + +#include "itkImageFileWriter.h" +#include "itkImageFileReader.h" +#include "itkDirectedHausdorffDistanceImageFilter.h" +#include "itkTestingMacros.h" +#include "itkPrintHelper.h" + +using namespace itk::print_helper; + + +int +itkDirectedHausdorffDistanceImageFilterTest(int argc, char * argv[]) +{ + if (argc < 5) + { + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) + << " inputFileName1 inputFileName2 outputFileName useImageSpacing" << std::endl; + return EXIT_FAILURE; + } + + constexpr unsigned int Dimension = 2; + + using PixelType = float; + using ImageType = itk::Image; + + using ReaderType = itk::ImageFileReader; + + typename ReaderType::Pointer reader1 = ReaderType::New(); + typename ReaderType::Pointer reader2 = ReaderType::New(); + reader1->SetFileName(argv[1]); + + ITK_TRY_EXPECT_NO_EXCEPTION(reader1->Update()); + + reader2->SetFileName(argv[2]); + + ITK_TRY_EXPECT_NO_EXCEPTION(reader2->Update()); + + + using FilterType = itk::DirectedHausdorffDistanceImageFilter; + typename FilterType::Pointer filter = FilterType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, DirectedHausdorffDistanceImageFilter, ImageToImageFilter); + + + typename ImageType::Pointer image1 = reader1->GetOutput(); + filter->SetInput1(image1); + ITK_TEST_SET_GET_VALUE(image1, filter->GetInput1()); + + typename ImageType::Pointer image2 = reader2->GetOutput(); + filter->SetInput2(image2); + ITK_TEST_SET_GET_VALUE(image2, filter->GetInput2()); + + auto useImageSpacing = static_cast(std::stoi(argv[4])); + ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing); + + ITK_TRY_EXPECT_NO_EXCEPTION(filter->Update()); + + + double expecteDirectedHausdorffDistance = 0; + ITK_TEST_EXPECT_EQUAL(expecteDirectedHausdorffDistance, filter->GetDirectedHausdorffDistance()); + + double expecteAverageHausdorffDistance = 0; + ITK_TEST_EXPECT_EQUAL(expecteAverageHausdorffDistance, filter->GetAverageHausdorffDistance()); + + + using WriterType = itk::ImageFileWriter; + typename WriterType::Pointer writer = WriterType::New(); + writer->SetInput(filter->GetOutput()); + writer->SetFileName(argv[3]); + + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); + + + std::cout << "Test finished." << std::endl; + return EXIT_SUCCESS; +} diff --git a/Modules/Filtering/ImageFeature/test/CMakeLists.txt b/Modules/Filtering/ImageFeature/test/CMakeLists.txt index 79472ca46ef..9d324b17515 100644 --- a/Modules/Filtering/ImageFeature/test/CMakeLists.txt +++ b/Modules/Filtering/ImageFeature/test/CMakeLists.txt @@ -34,7 +34,10 @@ set(TEMP ${ITK_TEST_OUTPUT_DIR}) itk_add_test(NAME itkZeroCrossingBasedEdgeDetectionImageFilterTest COMMAND ITKImageFeatureTestDriver itkZeroCrossingBasedEdgeDetectionImageFilterTest 1.0 0.01) itk_add_test(NAME itkLaplacianImageFilterTest - COMMAND ITKImageFeatureTestDriver itkLaplacianImageFilterTest) + COMMAND ITKImageFeatureTestDriver + --compare DATA{Baseline/itkLaplacianImageFilterTest.png} + ${ITK_TEST_OUTPUT_DIR}/itkLaplacianImageFilterTest.png + itkLaplacianImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/itkLaplacianImageFilterTest.png 1) itk_add_test(NAME itkSobelEdgeDetectionImageFilterTest COMMAND ITKImageFeatureTestDriver itkSobelEdgeDetectionImageFilterTest) itk_add_test(NAME itkUnsharpMaskImageFilterTestSimple @@ -136,22 +139,22 @@ itk_add_test(NAME itkDerivativeImageFilterTest1x COMMAND ITKImageFeatureTestDriver --compare DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/itkDerivativeImageFilterTest1x.png} ${ITK_TEST_OUTPUT_DIR}/itkDerivativeImageFilterTest1x.png - itkDerivativeImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/itkDerivativeImageFilterTest1x.png 1 0) + itkDerivativeImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/itkDerivativeImageFilterTest1x.png 1 0 1) itk_add_test(NAME itkDerivativeImageFilterTest1y COMMAND ITKImageFeatureTestDriver --compare DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/itkDerivativeImageFilterTest1y.png} ${ITK_TEST_OUTPUT_DIR}/itkDerivativeImageFilterTest1y.png - itkDerivativeImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/itkDerivativeImageFilterTest1y.png 1 1) + itkDerivativeImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/itkDerivativeImageFilterTest1y.png 1 1 1) itk_add_test(NAME itkDerivativeImageFilterTest2x COMMAND ITKImageFeatureTestDriver --compare DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/itkDerivativeImageFilterTest2x.png} ${ITK_TEST_OUTPUT_DIR}/itkDerivativeImageFilterTest2x.png - itkDerivativeImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/itkDerivativeImageFilterTest2x.png 2 0) + itkDerivativeImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/itkDerivativeImageFilterTest2x.png 2 0 1) itk_add_test(NAME itkDerivativeImageFilterTest2y COMMAND ITKImageFeatureTestDriver --compare DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/itkDerivativeImageFilterTest2y.png} ${ITK_TEST_OUTPUT_DIR}/itkDerivativeImageFilterTest2y.png - itkDerivativeImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/itkDerivativeImageFilterTest2y.png 2 1) + itkDerivativeImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/itkDerivativeImageFilterTest2y.png 2 1 1) itk_add_test(NAME itkLaplacianRecursiveGaussianImageFilterTest COMMAND ITKImageFeatureTestDriver --compare DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/LaplacianRecursiveGaussianImageFilterTest.png,:} diff --git a/Modules/Filtering/ImageFeature/test/itkDerivativeImageFilterTest.cxx b/Modules/Filtering/ImageFeature/test/itkDerivativeImageFilterTest.cxx index 014da05ad6b..7aa254f6ba4 100644 --- a/Modules/Filtering/ImageFeature/test/itkDerivativeImageFilterTest.cxx +++ b/Modules/Filtering/ImageFeature/test/itkDerivativeImageFilterTest.cxx @@ -27,11 +27,12 @@ int itkDerivativeImageFilterTest(int argc, char * argv[]) { - if (argc < 5) + if (argc < 6) { + std::cerr << "Missing Parameters." << std::endl; std::cerr << "Usage: " << std::endl; - std::cerr << itkNameOfTestExecutableMacro(argv) << " inputImageFile normalizedOutputImageFile "; - std::cerr << " derivativeOrder direction" << std::endl; + std::cerr << itkNameOfTestExecutableMacro(argv) << " inputImageFile normalizedOutputImageFile " + << " derivativeOrder direction useImageSpacing" << std::endl; return EXIT_FAILURE; } @@ -46,11 +47,8 @@ itkDerivativeImageFilterTest(int argc, char * argv[]) using InputImageType = itk::Image; using OutputImageType = itk::Image; - using ReaderType = itk::ImageFileReader; - ReaderType::Pointer reader = ReaderType::New(); - reader->SetFileName(argv[1]); // Define the filter @@ -58,11 +56,18 @@ itkDerivativeImageFilterTest(int argc, char * argv[]) FilterType::Pointer filter = FilterType::New(); - // setup the filter - filter->SetOrder(std::stoi(argv[3])); - filter->SetDirection(std::stoi(argv[4])); + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, DerivativeImageFilter, ImageToImageFilter); + + // Set up the filter + unsigned int order = std::stoi(argv[3]); + filter->SetOrder(order); + ITK_TEST_SET_GET_VALUE(order, filter->GetOrder()); - auto useImageSpacing = true; + unsigned int direction = std::stoi(argv[4]); + filter->SetDirection(direction); + ITK_TEST_SET_GET_VALUE(direction, filter->GetDirection()); + + auto useImageSpacing = static_cast(std::stoi(argv[5])); #if !defined(ITK_FUTURE_LEGACY_REMOVE) if (useImageSpacing) { @@ -98,7 +103,10 @@ itkDerivativeImageFilterTest(int argc, char * argv[]) normalizer->SetOutputMaximum(255); normalizedWriter->SetFileName(argv[2]); - normalizedWriter->Update(); + ITK_TRY_EXPECT_NO_EXCEPTION(normalizedWriter->Update()); + + + std::cout << "Test finished" << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Filtering/ImageFeature/test/itkLaplacianImageFilterTest.cxx b/Modules/Filtering/ImageFeature/test/itkLaplacianImageFilterTest.cxx index 250f3abbea8..36e3bd5b1a2 100644 --- a/Modules/Filtering/ImageFeature/test/itkLaplacianImageFilterTest.cxx +++ b/Modules/Filtering/ImageFeature/test/itkLaplacianImageFilterTest.cxx @@ -17,9 +17,14 @@ *=========================================================================*/ #include +#include "itkImageFileReader.h" +#include "itkImageFileWriter.h" #include "itkLaplacianImageFilter.h" #include "itkNullImageToImageFilterDriver.hxx" +#include "itkRescaleIntensityImageFilter.h" #include "itkSimpleFilterWatcher.h" +#include "itkTestingMacros.h" + inline std::ostream & operator<<(std::ostream & o, const itk::Vector & v) @@ -29,52 +34,75 @@ operator<<(std::ostream & o, const itk::Vector & v) } int -itkLaplacianImageFilterTest(int, char *[]) +itkLaplacianImageFilterTest(int argc, char * argv[]) { - try - { - using ImageType = itk::Image; - - // Set up filter - itk::LaplacianImageFilter::Pointer filter = - itk::LaplacianImageFilter::New(); - - itk::SimpleFilterWatcher watch(filter); - - // Run Test - itk::Size<2> sz; - sz[0] = 100; - sz[1] = 100; - itk::NullImageToImageFilterDriver test1; - test1.SetImageSize(sz); - test1.SetFilter(filter); - test1.Execute(); - - // verify the fix for Bug: 788 - // The following code should throw an exception and not crash. - filter->SetInput(nullptr); - bool exceptionSeen = false; - try - { - filter->Update(); - } - catch (const itk::ExceptionObject & err) - { - exceptionSeen = true; - std::cout << "Expected exception: " << std::endl; - std::cout << err << std::endl; - std::cout << " was received OK" << std::endl; - } - if (!exceptionSeen) - { - std::cerr << "Expected exception was not thrown" << std::endl; - return EXIT_FAILURE; - } - } - catch (const itk::ExceptionObject & err) + if (argc < 4) { - (&err)->Print(std::cerr); + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " inputFileName outputFileName useImageSpacing" + << std::endl; return EXIT_FAILURE; } + + + constexpr unsigned int Dimension = 2; + + using InputPixelType = float; + using InputImageType = itk::Image; + using OutputPixelType = unsigned char; + using OutputImageType = itk::Image; + + using ReaderType = itk::ImageFileReader; + ReaderType::Pointer reader = ReaderType::New(); + reader->SetFileName(argv[1]); + + ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); + + + // Set up filter + itk::LaplacianImageFilter::Pointer filter = + itk::LaplacianImageFilter::New(); + + auto useImageSpacing = static_cast(std::stoi(argv[3])); + ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing); + + itk::SimpleFilterWatcher watch(filter); + + // Run test + itk::Size sz; + sz[0] = 100; + sz[1] = 100; + itk::NullImageToImageFilterDriver test1; + test1.SetImageSize(sz); + test1.SetFilter(filter); + + ITK_TRY_EXPECT_NO_EXCEPTION(test1.Execute()); + + // The following code should throw an exception and not crash. + filter->SetInput(nullptr); + + ITK_TRY_EXPECT_EXCEPTION(filter->Update()); + + + filter->SetInput(reader->GetOutput()); + + ITK_TRY_EXPECT_NO_EXCEPTION(filter->Update()); + + + using RescaleType = itk::RescaleIntensityImageFilter; + RescaleType::Pointer rescaler = RescaleType::New(); + rescaler->SetInput(filter->GetOutput()); + rescaler->SetOutputMinimum(itk::NumericTraits::min()); + rescaler->SetOutputMaximum(itk::NumericTraits::max()); + + using WriterType = itk::ImageFileWriter; + WriterType::Pointer writer = WriterType::New(); + writer->SetFileName(argv[2]); + writer->SetInput(rescaler->GetOutput()); + + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); + + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Filtering/ImageGradient/test/itkGradientMagnitudeImageFilterTest.cxx b/Modules/Filtering/ImageGradient/test/itkGradientMagnitudeImageFilterTest.cxx index 86ae7622779..00442d85e47 100644 --- a/Modules/Filtering/ImageGradient/test/itkGradientMagnitudeImageFilterTest.cxx +++ b/Modules/Filtering/ImageGradient/test/itkGradientMagnitudeImageFilterTest.cxx @@ -34,12 +34,19 @@ itkGradientMagnitudeImageFilterTest(int, char *[]) { try { - using ImageType = itk::Image; + constexpr unsigned int Dimension = 2; + + using PixelType = float; + + using ImageType = itk::Image; // Set up filter itk::GradientMagnitudeImageFilter::Pointer filter = itk::GradientMagnitudeImageFilter::New(); + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, GradientMagnitudeImageFilter, ImageToImageFilter); + + bool useImageSpacing = true; #if !defined(ITK_FUTURE_LEGACY_REMOVE) if (useImageSpacing) @@ -53,8 +60,8 @@ itkGradientMagnitudeImageFilterTest(int, char *[]) #endif ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing); - // Run Test - itk::Size<2> sz; + // Run test + itk::Size sz; sz[0] = 100; sz[1] = 100; itk::NullImageToImageFilterDriver test1; @@ -67,5 +74,8 @@ itkGradientMagnitudeImageFilterTest(int, char *[]) (&err)->Print(std::cerr); return EXIT_FAILURE; } + + + std::cout << "Test finished" << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Filtering/ImageStatistics/test/itkImagePCAShapeModelEstimatorTest.cxx b/Modules/Filtering/ImageStatistics/test/itkImagePCAShapeModelEstimatorTest.cxx index 38d42c7494a..33fe4696153 100644 --- a/Modules/Filtering/ImageStatistics/test/itkImagePCAShapeModelEstimatorTest.cxx +++ b/Modules/Filtering/ImageStatistics/test/itkImagePCAShapeModelEstimatorTest.cxx @@ -21,6 +21,10 @@ #include "itkTextOutput.h" #include "itkImagePCAShapeModelEstimator.h" +#include "itkPrintHelper.h" +#include "itkTestingMacros.h" + +using namespace itk::print_helper; // class to support progress feedback @@ -50,9 +54,7 @@ itkImagePCAShapeModelEstimatorTest(int, char *[]) itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer()); - //------------------------------------------------------ // Create 3 simple test images with - //------------------------------------------------------ using InputImageType = itk::Image; using OutputImageType = itk::Image; @@ -74,42 +76,35 @@ itkImagePCAShapeModelEstimatorTest(int, char *[]) region.SetSize(inputImageSize); region.SetIndex(index); - //------------------------------------------------------------------------ // Set up Image 1 first - //------------------------------------------------------------------------ image1->SetLargestPossibleRegion(region); image1->SetBufferedRegion(region); image1->Allocate(); - // setup the iterators + // Set up the iterators InputImageIterator image1It(image1, image1->GetBufferedRegion()); - //------------------------------------------------------------------------ // Set up Image 2 first - //------------------------------------------------------------------------ image2->SetLargestPossibleRegion(region); image2->SetBufferedRegion(region); image2->Allocate(); - // setup the iterators + // Set up the iterators InputImageIterator image2It(image2, image2->GetBufferedRegion()); - //------------------------------------------------------------------------ // Set up Image 3 first - //------------------------------------------------------------------------ image3->SetLargestPossibleRegion(region); image3->SetBufferedRegion(region); image3->Allocate(); - // setup the iterators + // Set up the iterators InputImageIterator image3It(image3, image3->GetBufferedRegion()); - //------------------------------------------------------------------------ // Manually create and store each vector - //------------------------------------------------------------------------ + // Image no. 1 for (int i = 0; i < 4; i++) { @@ -136,20 +131,16 @@ itkImagePCAShapeModelEstimatorTest(int, char *[]) image3It.Set(0); ++image3It; - //---------------------------------------------------------------------- // Test code for the Shape model estimator - //---------------------------------------------------------------------- - //---------------------------------------------------------------------- // Set the image model estimator - //---------------------------------------------------------------------- using ImagePCAShapeModelEstimatorType = itk::ImagePCAShapeModelEstimator; ImagePCAShapeModelEstimatorType::Pointer applyPCAShapeEstimator = ImagePCAShapeModelEstimatorType::New(); - //---------------------------------------------------------------------- + ITK_EXERCISE_BASIC_OBJECT_METHODS(applyPCAShapeEstimator, ImagePCAShapeModelEstimator, ImageShapeModelEstimatorBase); + // Set the parameters of the clusterer - //---------------------------------------------------------------------- applyPCAShapeEstimator->SetNumberOfTrainingImages(NUMTRAINIMAGES); applyPCAShapeEstimator->SetNumberOfPrincipalComponentsRequired(NUMLARGESTPC + 1); applyPCAShapeEstimator->SetNumberOfPrincipalComponentsRequired(NUMLARGESTPC); @@ -159,13 +150,6 @@ itkImagePCAShapeModelEstimatorTest(int, char *[]) applyPCAShapeEstimator->Update(); - // Test the printself function to increase coverage - applyPCAShapeEstimator->Print(std::cout); - - // Exercise TypeMacro in superclass - using GenericEstimatorType = ImagePCAShapeModelEstimatorType::Superclass; - std::cout << applyPCAShapeEstimator->GenericEstimatorType::GetNameOfClass() << std::endl; - // Print out the number of training images and the number of principal // components std::cout << "The number of training images are: " << applyPCAShapeEstimator->GetNumberOfTrainingImages() @@ -233,5 +217,6 @@ itkImagePCAShapeModelEstimatorTest(int, char *[]) } + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Filtering/LabelMap/test/CMakeLists.txt b/Modules/Filtering/LabelMap/test/CMakeLists.txt index 50170d87fb4..49af73ffd86 100644 --- a/Modules/Filtering/LabelMap/test/CMakeLists.txt +++ b/Modules/Filtering/LabelMap/test/CMakeLists.txt @@ -15,6 +15,7 @@ itkBinaryImageToLabelMapFilterTest.cxx itkBinaryImageToLabelMapFilterTest2.cxx itkBinaryImageToShapeLabelMapFilterTest1.cxx itkBinaryImageToStatisticsLabelMapFilterTest1.cxx +itkBinaryNotImageFilterTest.cxx itkBinaryReconstructionByDilationImageFilterTest.cxx itkBinaryReconstructionByErosionImageFilterTest.cxx itkBinaryReconstructionLabelMapFilterTest.cxx @@ -184,6 +185,11 @@ itk_add_test(NAME itkBinaryImageToStatisticsLabelMapFilterTest1 --compare DATA{Baseline/Spots-binaryimage-to-statisticslabel.mha} ${ITK_TEST_OUTPUT_DIR}/Spots-binaryimage-to-statisticslabel.mha itkBinaryImageToStatisticsLabelMapFilterTest1 DATA{${ITK_DATA_ROOT}/Input/Spots.png} DATA{${ITK_DATA_ROOT}/Input/Spots.png} ${ITK_TEST_OUTPUT_DIR}/Spots-binaryimage-to-statisticslabel.mha 1 0 0 1 1 1 128) +itk_add_test(NAME itkBinaryNotImageFilterTest + COMMAND ITKLabelMapTestDriver + --compare DATA{Baseline/itkBinaryNotImageFilterTest.png} + ${ITK_TEST_OUTPUT_DIR}/itkBinaryNotImageFilterTest.png + itkBinaryNotImageFilterTest DATA{${ITK_DATA_ROOT}/Input/STAPLE2.png} DATA{${ITK_DATA_ROOT}/Input/STAPLE4.png} ${ITK_TEST_OUTPUT_DIR}/itkBinaryNotImageFilterTest.png 255 0) itk_add_test(NAME itkBinaryReconstructionByDilationImageFilterTest COMMAND ITKLabelMapTestDriver --compare DATA{Baseline/itkBinaryReconstructionByDilationImageFilterTest.png} diff --git a/Modules/Filtering/LabelMap/test/itkBinaryFillholeImageFilterTest1.cxx b/Modules/Filtering/LabelMap/test/itkBinaryFillholeImageFilterTest1.cxx index 493ba0252ab..f50a5a926f4 100644 --- a/Modules/Filtering/LabelMap/test/itkBinaryFillholeImageFilterTest1.cxx +++ b/Modules/Filtering/LabelMap/test/itkBinaryFillholeImageFilterTest1.cxx @@ -20,40 +20,59 @@ #include "itkSimpleFilterWatcher.h" #include "itkBinaryFillholeImageFilter.h" +#include "itkTestingMacros.h" int itkBinaryFillholeImageFilterTest1(int argc, char * argv[]) { - if (argc != 5) + if (argc < 5) { - std::cerr << "usage: " << argv[0] << " input output conn fg" << std::endl; - // std::cerr << " : " << std::endl; - exit(1); + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) + << " inputFileName outputFileName fullyConnected foregroundValue" << std::endl; + return EXIT_FAILURE; } - constexpr int dim = 2; + constexpr unsigned int Dimension = 2; - using IType = itk::Image; + using PixelType = unsigned char; - using ReaderType = itk::ImageFileReader; + using ImageType = itk::Image; + + using ReaderType = itk::ImageFileReader; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(argv[1]); - reader->Update(); - using I2LType = itk::BinaryFillholeImageFilter; - I2LType::Pointer reconstruction = I2LType::New(); - reconstruction->SetInput(reader->GetOutput()); - reconstruction->SetFullyConnected(std::stoi(argv[3])); - reconstruction->SetForegroundValue(std::stoi(argv[4])); - // reconstruction->SetBackgroundValue( std::stoi(argv[5]) ); - itk::SimpleFilterWatcher watcher(reconstruction, "filter"); + ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); + + + using FilterType = itk::BinaryFillholeImageFilter; + FilterType::Pointer filter = FilterType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, BinaryFillholeImageFilter, ImageToImageFilter); + + + itk::SimpleFilterWatcher watcher(filter, "filter"); - using WriterType = itk::ImageFileWriter; + auto fullyConnected = static_cast(std::stoi(argv[3])); + ITK_TEST_SET_GET_BOOLEAN(filter, FullyConnected, fullyConnected); + + typename FilterType::InputImagePixelType foregroundValue = std::stoi(argv[4]); + filter->SetForegroundValue(foregroundValue); + ITK_TEST_SET_GET_VALUE(foregroundValue, filter->GetForegroundValue()); + + filter->SetInput(reader->GetOutput()); + + using WriterType = itk::ImageFileWriter; WriterType::Pointer writer = WriterType::New(); - writer->SetInput(reconstruction->GetOutput()); + writer->SetInput(filter->GetOutput()); writer->SetFileName(argv[2]); - writer->Update(); - return 0; + + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); + + + std::cout << "Test finished." << std::endl; + return EXIT_SUCCESS; } diff --git a/Modules/Filtering/LabelMap/test/itkBinaryImageToLabelMapFilterTest.cxx b/Modules/Filtering/LabelMap/test/itkBinaryImageToLabelMapFilterTest.cxx index 0a7031d50c3..1766922bed3 100644 --- a/Modules/Filtering/LabelMap/test/itkBinaryImageToLabelMapFilterTest.cxx +++ b/Modules/Filtering/LabelMap/test/itkBinaryImageToLabelMapFilterTest.cxx @@ -29,12 +29,11 @@ int itkBinaryImageToLabelMapFilterTest(int argc, char * argv[]) { - if (argc != 7) + if (argc < 7) { - std::cerr << "usage: " << itkNameOfTestExecutableMacro(argv); - std::cerr << " inputBinaryImage outputLabelImage"; - std::cerr << " fullyConnected(0/1) foregroundValue backgroundValue expectfailure"; - std::cerr << std::endl; + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " inputBinaryImage outputLabelImage" + << " fullyConnected(0/1) foregroundValue backgroundValue expectfailure" << std::endl; return EXIT_FAILURE; } @@ -54,13 +53,25 @@ itkBinaryImageToLabelMapFilterTest(int argc, char * argv[]) using ImageToLabelType = itk::BinaryImageToLabelMapFilter; ImageToLabelType::Pointer imageToLabel = ImageToLabelType::New(); - // test the behavior without input + + ITK_EXERCISE_BASIC_OBJECT_METHODS(imageToLabel, BinaryImageToLabelMapFilter, ImageToImageFilter); + + + // Test the behavior without input ITK_TRY_EXPECT_EXCEPTION(imageToLabel->Update()); + imageToLabel->ResetPipeline(); - imageToLabel->SetFullyConnected(std::stoi(argv[3])); - imageToLabel->SetInputForegroundValue(std::stoi(argv[4])); - imageToLabel->SetOutputBackgroundValue(std::stoi(argv[5])); + auto fullyConnected = static_cast(std::stoi(argv[3])); + ITK_TEST_SET_GET_BOOLEAN(imageToLabel, FullyConnected, fullyConnected); + + typename ImageToLabelType::InputPixelType inputForegroundValue = std::stoi(argv[4]); + imageToLabel->SetInputForegroundValue(inputForegroundValue); + ITK_TEST_SET_GET_VALUE(inputForegroundValue, imageToLabel->GetInputForegroundValue()); + + typename ImageToLabelType::OutputPixelType outputBackgroundValue = std::stoi(argv[5]); + imageToLabel->SetOutputBackgroundValue(outputBackgroundValue); + ITK_TEST_SET_GET_VALUE(outputBackgroundValue, imageToLabel->GetOutputBackgroundValue()); itk::SimpleFilterWatcher watcher(imageToLabel); @@ -91,9 +102,7 @@ itkBinaryImageToLabelMapFilterTest(int argc, char * argv[]) imageToLabel->GetOutput()->PrintLabelObjects(); - std::cout << imageToLabel->GetNameOfClass() << std::endl; - - imageToLabel->Print(std::cout); + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Filtering/LabelMap/test/itkBinaryNotImageFilterTest.cxx b/Modules/Filtering/LabelMap/test/itkBinaryNotImageFilterTest.cxx new file mode 100644 index 00000000000..f2b4c5a55aa --- /dev/null +++ b/Modules/Filtering/LabelMap/test/itkBinaryNotImageFilterTest.cxx @@ -0,0 +1,85 @@ +/*========================================================================= + * + * Copyright NumFOCUS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#include "itkImageFileReader.h" +#include "itkImageFileWriter.h" +#include "itkBinaryNotImageFilter.h" +#include "itkTestingMacros.h" + +int +itkBinaryNotImageFilterTest(int argc, char * argv[]) +{ + if (argc < 6) + { + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) + << " inputFileName1 inputFileName2 outputFileName backgroundValue foregroundValue" << std::endl; + return EXIT_FAILURE; + } + + constexpr unsigned int Dimension = 2; + + using PixelType = unsigned char; + using ImageType = itk::Image; + + using ReaderType = itk::ImageFileReader; + + typename ReaderType::Pointer reader1 = ReaderType::New(); + reader1->SetFileName(argv[1]); + + ITK_TRY_EXPECT_NO_EXCEPTION(reader1->Update()); + + + typename ReaderType::Pointer reader2 = ReaderType::New(); + reader2->SetFileName(argv[2]); + + ITK_TRY_EXPECT_NO_EXCEPTION(reader2->Update()); + + + using FilterType = itk::BinaryNotImageFilter; + typename FilterType::Pointer filter = FilterType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, BinaryNotImageFilter, UnaryFunctorImageFilter); + + + auto foregroundValue = static_cast(std::stoi(argv[4])); + filter->SetForegroundValue(foregroundValue); + ITK_TEST_SET_GET_VALUE(foregroundValue, filter->GetForegroundValue()); + + + auto backgroundValue = static_cast(std::stoi(argv[5])); + filter->SetBackgroundValue(backgroundValue); + ITK_TEST_SET_GET_VALUE(backgroundValue, filter->GetBackgroundValue()); + + + filter->SetInput(reader1->GetOutput()); + filter->SetInput(reader2->GetOutput()); + + ITK_TRY_EXPECT_NO_EXCEPTION(filter->Update()); + + + using WriterType = itk::ImageFileWriter; + typename WriterType::Pointer writer = WriterType::New(); + writer->SetInput(filter->GetOutput()); + writer->SetFileName(argv[3]); + + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); + + + std::cout << "Test finished." << std::endl; + return EXIT_SUCCESS; +} diff --git a/Modules/Filtering/LabelMap/test/itkStatisticsRelabelLabelMapFilterTest1.cxx b/Modules/Filtering/LabelMap/test/itkStatisticsRelabelLabelMapFilterTest1.cxx index 0a8be706fd9..5e2f235ae9c 100644 --- a/Modules/Filtering/LabelMap/test/itkStatisticsRelabelLabelMapFilterTest1.cxx +++ b/Modules/Filtering/LabelMap/test/itkStatisticsRelabelLabelMapFilterTest1.cxx @@ -29,20 +29,21 @@ int itkStatisticsRelabelLabelMapFilterTest1(int argc, char * argv[]) { - if (argc != 6) + if (argc < 6) { - std::cerr << "usage: " << argv[0] << " input feature output"; - std::cerr << "background reverseOrdering attribute" << std::endl; + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " input feature output" + << "background reverseOrdering attribute" << std::endl; return EXIT_FAILURE; } - constexpr unsigned int dim = 2; + constexpr unsigned int Dimension = 2; using PixelType = unsigned char; - using ImageType = itk::Image; + using ImageType = itk::Image; - using StatisticsLabelObjectType = itk::StatisticsLabelObject; + using StatisticsLabelObjectType = itk::StatisticsLabelObject; using LabelMapType = itk::LabelMap; // Reading Image File @@ -62,19 +63,13 @@ itkStatisticsRelabelLabelMapFilterTest1(int argc, char * argv[]) using RelabelType = itk::StatisticsRelabelLabelMapFilter; RelabelType::Pointer relabel = RelabelType::New(); - // testing get and set macros for ReverseOrdering - bool reverseOrdering = std::stoi(argv[4]); - relabel->SetReverseOrdering(reverseOrdering); - ITK_TEST_SET_GET_VALUE(reverseOrdering, relabel->GetReverseOrdering()); + ITK_EXERCISE_BASIC_OBJECT_METHODS(relabel, StatisticsRelabelLabelMapFilter, ShapeRelabelLabelMapFilter); - // testing boolean macro for ReverseOrdering - relabel->ReverseOrderingOff(); - ITK_TEST_SET_GET_VALUE(false, relabel->GetReverseOrdering()); - relabel->ReverseOrderingOn(); - ITK_TEST_SET_GET_VALUE(true, relabel->GetReverseOrdering()); + bool reverseOrdering = std::stoi(argv[4]); + relabel->SetReverseOrdering(reverseOrdering); + ITK_TEST_SET_GET_BOOLEAN(relabel, ReverseOrdering, reverseOrdering); - // testing get and set macros for Attribute unsigned int attribute = std::stoi(argv[5]); relabel->SetAttribute(attribute); ITK_TEST_SET_GET_VALUE(attribute, relabel->GetAttribute()); @@ -99,5 +94,7 @@ itkStatisticsRelabelLabelMapFilterTest1(int argc, char * argv[]) ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Filtering/MathematicalMorphology/test/CMakeLists.txt b/Modules/Filtering/MathematicalMorphology/test/CMakeLists.txt index 360c951e645..65691e56503 100644 --- a/Modules/Filtering/MathematicalMorphology/test/CMakeLists.txt +++ b/Modules/Filtering/MathematicalMorphology/test/CMakeLists.txt @@ -1,5 +1,7 @@ itk_module_test() set(ITKMathematicalMorphologyTests +itkAnchorErodeDilateImageFilterTest.cxx +itkAnchorOpenCloseImageFilterTest.cxx itkClosingByReconstructionImageFilterTest.cxx itkFlatStructuringElementTest.cxx itkFlatStructuringElementTest2.cxx @@ -20,6 +22,7 @@ itkHMaximaImageFilterTest.cxx itkHMinimaImageFilterTest.cxx itkHMaximaMinimaImageFilterTest.cxx itkMorphologicalGradientImageFilterTest.cxx +itkMovingHistogramMorphologyImageFilterTest.cxx itkOpeningByReconstructionImageFilterTest.cxx itkOpeningByReconstructionImageFilterTest2.cxx itkDoubleThresholdImageFilterTest.cxx @@ -45,10 +48,18 @@ itkMaskedRankImageFilterTest.cxx itkRankImageFilterTest.cxx itkMapMaskedRankImageFilterTest.cxx itkMapRankImageFilterTest.cxx +itkVanHerkGilWermanErodeDilateImageFilterTest.cxx ) CreateTestDriver(ITKMathematicalMorphology "${ITKMathematicalMorphology-Test_LIBRARIES}" "${ITKMathematicalMorphologyTests}") + +itk_add_test(NAME itkAnchorErodeDilateImageFilterTest + COMMAND ITKMathematicalMorphologyTestDriver + itkAnchorErodeDilateImageFilterTest) +itk_add_test(NAME itkAnchorOpenCloseImageFilterTest + COMMAND ITKMathematicalMorphologyTestDriver + itkAnchorOpenCloseImageFilterTest) itk_add_test(NAME itkClosingByReconstructionImageFilterTest COMMAND ITKMathematicalMorphologyTestDriver --compare DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/ClosingByReconstructionImageFilterTest.png} @@ -87,22 +98,22 @@ itk_add_test(NAME itkGrayscaleConnectedClosingImageFilterTest COMMAND ITKMathematicalMorphologyTestDriver --compare DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/GrayscaleConnectedClosingImageFilterTest.png} ${ITK_TEST_OUTPUT_DIR}/GrayscaleConnectedClosingImageFilterTest.png - itkGrayscaleConnectedClosingImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/GrayscaleConnectedClosingImageFilterTest.png 174 214) + itkGrayscaleConnectedClosingImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/GrayscaleConnectedClosingImageFilterTest.png 174 214 0) itk_add_test(NAME itkGrayscaleConnectedClosingImageFilterTest2 COMMAND ITKMathematicalMorphologyTestDriver --compare DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/GrayscaleConnectedClosingImageFilterTest2.png} ${ITK_TEST_OUTPUT_DIR}/GrayscaleConnectedClosingImageFilterTest2.png - itkGrayscaleConnectedClosingImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/GrayscaleConnectedClosingImageFilterTest2.png 150 169) + itkGrayscaleConnectedClosingImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/GrayscaleConnectedClosingImageFilterTest2.png 150 169 0) itk_add_test(NAME itkGrayscaleConnectedOpeningImageFilterTest COMMAND ITKMathematicalMorphologyTestDriver --compare DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/GrayscaleConnectedOpeningImageFilterTest.png} ${ITK_TEST_OUTPUT_DIR}/GrayscaleConnectedOpeningImageFilterTest.png - itkGrayscaleConnectedOpeningImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/GrayscaleConnectedOpeningImageFilterTest.png 174 214) + itkGrayscaleConnectedOpeningImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/GrayscaleConnectedOpeningImageFilterTest.png 174 214 0) itk_add_test(NAME itkGrayscaleConnectedOpeningImageFilterTest2 COMMAND ITKMathematicalMorphologyTestDriver --compare DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/GrayscaleConnectedOpeningImageFilterTest2.png} ${ITK_TEST_OUTPUT_DIR}/GrayscaleConnectedOpeningImageFilterTest2.png - itkGrayscaleConnectedOpeningImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/GrayscaleConnectedOpeningImageFilterTest2.png 150 169) + itkGrayscaleConnectedOpeningImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/GrayscaleConnectedOpeningImageFilterTest2.png 150 169 0) itk_add_test(NAME itkGrayscaleFillholeImageFilterTestFullyConnectedOff COMMAND ITKMathematicalMorphologyTestDriver --compare-MD5 ${ITK_TEST_OUTPUT_DIR}/itkGrayscaleFillholeImageFilterTestFullyConnectedOff.png @@ -208,6 +219,9 @@ itk_add_test(NAME itkMorphologicalGradientImageFilterTest2 --compare DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/MorphologicalGradientImageFilterTest.png} ${ITK_TEST_OUTPUT_DIR}/MorphologicalGradientImageFilterTest2.png itkMorphologicalGradientImageFilterTest2 DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/MorphologicalGradientImageFilterTest2.png) +itk_add_test(NAME itkMovingHistogramMorphologyImageFilterTest + COMMAND ITKMathematicalMorphologyTestDriver + itkMovingHistogramMorphologyImageFilterTest) itk_add_test(NAME itkOpeningByReconstructionImageFilterTest COMMAND ITKMathematicalMorphologyTestDriver --compare DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/OpeningByReconstructionImageFilterTest.png} @@ -533,3 +547,6 @@ itk_add_test(NAME itkRankImageFilterTest10 --compare DATA{Baseline/itkRankImageFilter10.png} ${ITK_TEST_OUTPUT_DIR}/itkRankImageFilter10.png itkRankImageFilterTest DATA{${ITK_DATA_ROOT}/Input/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/itkRankImageFilter10.png 10) +itk_add_test(NAME itkVanHerkGilWermanErodeDilateImageFilterTest + COMMAND ITKMathematicalMorphologyTestDriver + itkVanHerkGilWermanErodeDilateImageFilterTest) diff --git a/Modules/Filtering/MathematicalMorphology/test/itkAnchorErodeDilateImageFilterTest.cxx b/Modules/Filtering/MathematicalMorphology/test/itkAnchorErodeDilateImageFilterTest.cxx new file mode 100644 index 00000000000..87b62159c82 --- /dev/null +++ b/Modules/Filtering/MathematicalMorphology/test/itkAnchorErodeDilateImageFilterTest.cxx @@ -0,0 +1,48 @@ +/*========================================================================= + * + * Copyright NumFOCUS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ + +#include "itkAnchorErodeDilateImageFilter.h" +#include "itkFlatStructuringElement.h" +#include "itkTestingMacros.h" + + +int +itkAnchorErodeDilateImageFilterTest(int, char ** const) +{ + constexpr unsigned int Dimension = 2; + + using PixelType = float; + + using ImageType = itk::Image; + using KernelType = itk::FlatStructuringElement; + using FunctionType = std::less; + + using FilterType = itk::AnchorErodeDilateImageFilter; + typename FilterType::Pointer filter = FilterType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, AnchorErodeDilateImageFilter, KernelImageFilter); + + + typename FilterType::InputImagePixelType boundary = 255; + filter->SetBoundary(boundary); + ITK_TEST_SET_GET_VALUE(boundary, filter->GetBoundary()); + + + std::cout << "Test finished." << std::endl; + return EXIT_SUCCESS; +} diff --git a/Modules/Filtering/MathematicalMorphology/test/itkAnchorOpenCloseImageFilterTest.cxx b/Modules/Filtering/MathematicalMorphology/test/itkAnchorOpenCloseImageFilterTest.cxx new file mode 100644 index 00000000000..dda51fefb08 --- /dev/null +++ b/Modules/Filtering/MathematicalMorphology/test/itkAnchorOpenCloseImageFilterTest.cxx @@ -0,0 +1,44 @@ +/*========================================================================= + * + * Copyright NumFOCUS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ + +#include "itkAnchorOpenCloseImageFilter.h" +#include "itkFlatStructuringElement.h" +#include "itkTestingMacros.h" + + +int +itkAnchorOpenCloseImageFilterTest(int, char ** const) +{ + constexpr unsigned int Dimension = 2; + + using PixelType = float; + + using ImageType = itk::Image; + using KernelType = itk::FlatStructuringElement; + using CompateType1 = std::less; + using CompateType2 = std::greater; + + using FilterType = itk::AnchorOpenCloseImageFilter; + typename FilterType::Pointer filter = FilterType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, AnchorOpenCloseImageFilter, KernelImageFilter); + + + std::cout << "Test finished." << std::endl; + return EXIT_SUCCESS; +} diff --git a/Modules/Filtering/MathematicalMorphology/test/itkGrayscaleConnectedClosingImageFilterTest.cxx b/Modules/Filtering/MathematicalMorphology/test/itkGrayscaleConnectedClosingImageFilterTest.cxx index 142f4010b04..55fffa6d68b 100644 --- a/Modules/Filtering/MathematicalMorphology/test/itkGrayscaleConnectedClosingImageFilterTest.cxx +++ b/Modules/Filtering/MathematicalMorphology/test/itkGrayscaleConnectedClosingImageFilterTest.cxx @@ -32,8 +32,8 @@ itkGrayscaleConnectedClosingImageFilterTest(int argc, char * argv[]) if (argc < 5) { std::cerr << "Usage: " << std::endl; - std::cerr << itkNameOfTestExecutableMacro(argv) << " inputImageFile "; - std::cerr << " outputImageFile seedX seedY " << std::endl; + std::cerr << itkNameOfTestExecutableMacro(argv) << " inputImageFile outputImageFile seedX seedY fullyConnected" + << std::endl; return EXIT_FAILURE; } @@ -71,7 +71,10 @@ itkGrayscaleConnectedClosingImageFilterTest(int argc, char * argv[]) ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); - // Setup the connectedopening method + // Set up the ConnectedClosing filter + auto fullyConnected = static_cast(std::stoi(argv[5])); + ITK_TEST_SET_GET_BOOLEAN(connectedClosing, FullyConnected, fullyConnected); + connectedClosing->SetInput(reader->GetOutput()); InputImageType::IndexType seed; diff --git a/Modules/Filtering/MathematicalMorphology/test/itkGrayscaleConnectedOpeningImageFilterTest.cxx b/Modules/Filtering/MathematicalMorphology/test/itkGrayscaleConnectedOpeningImageFilterTest.cxx index 4d879928bda..6d336d0ca79 100644 --- a/Modules/Filtering/MathematicalMorphology/test/itkGrayscaleConnectedOpeningImageFilterTest.cxx +++ b/Modules/Filtering/MathematicalMorphology/test/itkGrayscaleConnectedOpeningImageFilterTest.cxx @@ -29,11 +29,11 @@ int itkGrayscaleConnectedOpeningImageFilterTest(int argc, char * argv[]) { - if (argc < 5) + if (argc < 6) { std::cerr << "Missing Parameters " << std::endl; - std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " inputImageFile" - << " outputImageFile seedX seedY " << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) + << " inputImageFile outputImageFile seedX seedY fullyConnected" << std::endl; return EXIT_FAILURE; } @@ -72,7 +72,10 @@ itkGrayscaleConnectedOpeningImageFilterTest(int argc, char * argv[]) ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); - // Setup the connected opening method + // Set up the ConnectedOpening filter + auto fullyConnected = static_cast(std::stoi(argv[5])); + ITK_TEST_SET_GET_BOOLEAN(connectedOpening, FullyConnected, fullyConnected); + connectedOpening->SetInput(reader->GetOutput()); InputImageType::IndexType seed; diff --git a/Modules/Filtering/MathematicalMorphology/test/itkMovingHistogramMorphologyImageFilterTest.cxx b/Modules/Filtering/MathematicalMorphology/test/itkMovingHistogramMorphologyImageFilterTest.cxx new file mode 100644 index 00000000000..d729d9db419 --- /dev/null +++ b/Modules/Filtering/MathematicalMorphology/test/itkMovingHistogramMorphologyImageFilterTest.cxx @@ -0,0 +1,48 @@ +/*========================================================================= + * + * Copyright NumFOCUS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ + +#include "itkBinaryBallStructuringElement.h" +#include "itkMorphologyHistogram.h" +#include "itkMovingHistogramMorphologyImageFilter.h" +#include "itkTestingMacros.h" + + +int +itkMovingHistogramMorphologyImageFilterTest(int, char ** const) +{ + constexpr unsigned int Dimension = 2; + + using PixelType = float; + using ImageType = itk::Image; + using KernelType = itk::BinaryBallStructuringElement; + using HistogramType = itk::Function::MorphologyHistogram>; + + using FilterType = itk::MovingHistogramMorphologyImageFilter; + typename FilterType::Pointer filter = FilterType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, MovingHistogramMorphologyImageFilter, MovingHistogramImageFilter); + + + typename FilterType::InputImagePixelType boundary = 255; + filter->SetBoundary(boundary); + ITK_TEST_SET_GET_VALUE(boundary, filter->GetBoundary()); + + + std::cout << "Test finished." << std::endl; + return EXIT_SUCCESS; +} diff --git a/Modules/Filtering/MathematicalMorphology/test/itkVanHerkGilWermanErodeDilateImageFilterTest.cxx b/Modules/Filtering/MathematicalMorphology/test/itkVanHerkGilWermanErodeDilateImageFilterTest.cxx new file mode 100644 index 00000000000..157a9975e5e --- /dev/null +++ b/Modules/Filtering/MathematicalMorphology/test/itkVanHerkGilWermanErodeDilateImageFilterTest.cxx @@ -0,0 +1,47 @@ +/*========================================================================= + * + * Copyright NumFOCUS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ + +#include "itkFlatStructuringElement.h" +#include "itkVanHerkGilWermanErodeDilateImageFilter.h" +#include "itkTestingMacros.h" + + +int +itkVanHerkGilWermanErodeDilateImageFilterTest(int, char ** const) +{ + constexpr unsigned int Dimension = 2; + + using PixelType = float; + using ImageType = itk::Image; + using KernelType = itk::FlatStructuringElement; + using FunctionType = std::less; + + using FilterType = itk::VanHerkGilWermanErodeDilateImageFilter; + typename FilterType::Pointer filter = FilterType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, VanHerkGilWermanErodeDilateImageFilter, KernelImageFilter); + + + typename FilterType::InputImagePixelType boundary = 255; + filter->SetBoundary(boundary); + ITK_TEST_SET_GET_VALUE(boundary, filter->GetBoundary()); + + + std::cout << "Test finished." << std::endl; + return EXIT_SUCCESS; +} diff --git a/Modules/Filtering/Smoothing/test/itkDiscreteGaussianImageFilterTest.cxx b/Modules/Filtering/Smoothing/test/itkDiscreteGaussianImageFilterTest.cxx index 855e61974ef..a9a864d24b5 100644 --- a/Modules/Filtering/Smoothing/test/itkDiscreteGaussianImageFilterTest.cxx +++ b/Modules/Filtering/Smoothing/test/itkDiscreteGaussianImageFilterTest.cxx @@ -29,13 +29,20 @@ itkDiscreteGaussianImageFilterTest(int, char *[]) try { constexpr unsigned int Dimension = 3; - using ImageType = itk::Image; + + using PixelType = float; + + using ImageType = itk::Image; // Set up filter using FilterType = itk::DiscreteGaussianImageFilter; using ArrayType = FilterType::ArrayType; - FilterType::Pointer filter = FilterType::New(); + FilterType::Pointer filter = FilterType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, DiscreteGaussianImageFilter, ImageToImageFilter); + + itk::SimpleFilterWatcher watcher(filter); // Test other set/get functions @@ -67,11 +74,25 @@ itkDiscreteGaussianImageFilterTest(int, char *[]) filter->SetRealBoundaryCondition(&constantBoundaryCondition); ITK_TEST_SET_GET_VALUE(&constantBoundaryCondition, filter->GetRealBoundaryCondition()); - // set some parameters - filter->SetVariance(1.0); - filter->SetMaximumError(.01); - filter->SetMaximumKernelWidth(32); + // Set other filter properties + FilterType::ArrayType::ValueType varianceValue = 1.0; + FilterType::ArrayType variance; + variance.Fill(varianceValue); + filter->SetVariance(variance); + ITK_TEST_SET_GET_VALUE(variance, filter->GetVariance()); + + FilterType::ArrayType::ValueType maximumErrorValue = 0.01; + FilterType::ArrayType maximumError; + maximumError.Fill(maximumErrorValue); + filter->SetMaximumError(maximumError); + ITK_TEST_SET_GET_VALUE(maximumError, filter->GetMaximumError()); + + int maximumKernelWidth = 32; + filter->SetMaximumKernelWidth(maximumKernelWidth); + ITK_TEST_SET_GET_VALUE(maximumKernelWidth, filter->GetMaximumKernelWidth()); + filter->SetFilterDimensionality(Dimension); + ITK_TEST_SET_GET_VALUE(Dimension, filter->GetFilterDimensionality()); bool useImageSpacing = true; #if !defined(ITK_FUTURE_LEGACY_REMOVE) @@ -143,5 +164,7 @@ itkDiscreteGaussianImageFilterTest(int, char *[]) return EXIT_FAILURE; } + + std::cout << "Test finished" << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Filtering/Thresholding/test/itkBinaryThresholdImageFilterTest.cxx b/Modules/Filtering/Thresholding/test/itkBinaryThresholdImageFilterTest.cxx index 5a4a43e18b9..a980cbf05b1 100644 --- a/Modules/Filtering/Thresholding/test/itkBinaryThresholdImageFilterTest.cxx +++ b/Modules/Filtering/Thresholding/test/itkBinaryThresholdImageFilterTest.cxx @@ -127,6 +127,15 @@ itkBinaryThresholdImageFilterTest(int, char *[]) return EXIT_FAILURE; } + // Exercise the const variants + FilterType::ConstPointer constFilter = (const FilterType *)(filter.GetPointer()); + + const typename FilterType::InputPixelObjectType * lowerThresholdInput = constFilter->GetLowerThresholdInput(); + ITK_TEST_SET_GET_VALUE(lowerThresholdInput->Get(), lowerThreshold2->Get()); + + const typename FilterType::InputPixelObjectType * upperThresholdInput = constFilter->GetUpperThresholdInput(); + ITK_TEST_SET_GET_VALUE(upperThresholdInput->Get(), upperThreshold2->Get()); + // Deliberately cause an exception by setting lower threshold to be // greater than the upper threshold diff --git a/Modules/IO/LSM/test/itkLSMImageIOTest.cxx b/Modules/IO/LSM/test/itkLSMImageIOTest.cxx index 6d2da8d515e..ca7424efb56 100644 --- a/Modules/IO/LSM/test/itkLSMImageIOTest.cxx +++ b/Modules/IO/LSM/test/itkLSMImageIOTest.cxx @@ -28,53 +28,50 @@ itkLSMImageIOTest(int argc, char * argv[]) { if (argc < 3) { - std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " LSM.lsm OutputImage.lsm\n"; + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " inputFileName(*.lsm) ouputFileName(*.lsm)" + << std::endl; return EXIT_FAILURE; } + const unsigned int Dimensions = 2; + using InputPixelType = itk::RGBPixel; - using InputImageType = itk::Image; + using InputImageType = itk::Image; using ReaderType = itk::ImageFileReader; using ImageIOType = itk::LSMImageIO; - const char * filename = argv[1]; - const char * outfilename = argv[2]; - ReaderType::Pointer reader = ReaderType::New(); - reader->SetFileName(filename); + const char * inputFileName = argv[1]; + reader->SetFileName(inputFileName); ImageIOType::Pointer lsmImageIO = ImageIOType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(lsmImageIO, LSMImageIO, TIFFImageIO); + + reader->SetImageIO(lsmImageIO); - try - { - reader->Update(); - } - catch (const itk::ExceptionObject & e) - { - std::cerr << "exception in file reader " << std::endl; - std::cerr << e << std::endl; - return EXIT_FAILURE; - } + ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); + + size_t bufferSize = reader->GetImageIO()->GetImageSizeInBytes(); + auto * buffer = new InputPixelType[bufferSize]; + + lsmImageIO->Read(buffer); + + + const char * outputFileName = argv[2]; + lsmImageIO->SetFileName(outputFileName); + lsmImageIO->Write(buffer); - // using WriterType = itk::ImageFileWriter; WriterType::Pointer writer = WriterType::New(); - writer->SetFileName(outfilename); + writer->SetFileName(outputFileName); writer->SetInput(reader->GetOutput()); - try - { - writer->Update(); - } - catch (const itk::ExceptionObject & e) - { - std::cerr << "exception in file writer " << std::endl; - std::cerr << e << std::endl; - return EXIT_FAILURE; - } + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); - lsmImageIO->Print(std::cout); + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/IO/MINC/test/itkMINCImageIOTest2.cxx b/Modules/IO/MINC/test/itkMINCImageIOTest2.cxx index 1b1976f04b6..13d3e309c4a 100644 --- a/Modules/IO/MINC/test/itkMINCImageIOTest2.cxx +++ b/Modules/IO/MINC/test/itkMINCImageIOTest2.cxx @@ -23,6 +23,7 @@ #include "itkMINCImageIOFactory.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" +#include "itkTestingMacros.h" int itkMINCImageIOTest2(int argc, char * argv[]) @@ -30,15 +31,18 @@ itkMINCImageIOTest2(int argc, char * argv[]) if (argc < 3) { - std::cerr << "Missing Arguments " << std::endl; - std::cerr << "Usage: " << std::endl; - std::cerr << argv[0] << " inputfile outputfile " << std::endl; + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " inputfile outputfile " << std::endl; return EXIT_FAILURE; } using ImageType = itk::Image; itk::MINCImageIO::Pointer mincIO1 = itk::MINCImageIO::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(mincIO1, MINCImageIO, ImageIOBase); + + itk::MINCImageIO::Pointer mincIO2 = itk::MINCImageIO::New(); using ReaderType = itk::ImageFileReader; @@ -55,19 +59,14 @@ itkMINCImageIOTest2(int argc, char * argv[]) writer->SetInput(reader->GetOutput()); - try - { - writer->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); + ImageType::ConstPointer image = reader->GetOutput(); image->Print(std::cout); + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/IO/MeshBYU/test/itkMeshFileReadWriteTest.cxx b/Modules/IO/MeshBYU/test/itkMeshFileReadWriteTest.cxx index cde2a870a6f..75670bdfa0f 100644 --- a/Modules/IO/MeshBYU/test/itkMeshFileReadWriteTest.cxx +++ b/Modules/IO/MeshBYU/test/itkMeshFileReadWriteTest.cxx @@ -19,17 +19,20 @@ #include "itkQuadEdgeMesh.h" #include "itkMeshFileTestHelper.h" +#include "itkBYUMeshIO.h" +#include "itkTestingMacros.h" int itkMeshFileReadWriteTest(int argc, char * argv[]) { if (argc < 3) { - std::cerr << "Invalid commands, You need input and output mesh file name " << std::endl; + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " inputFileName outputFileName" << std::endl; return EXIT_FAILURE; } - bool IsBinary = (argc > 3); + bool isBinary = (argc > 3); constexpr unsigned int dimension = 3; using PixelType = float; @@ -39,16 +42,63 @@ itkMeshFileReadWriteTest(int argc, char * argv[]) int result = EXIT_SUCCESS; - if (test(argv[1], argv[2], IsBinary)) + if (test(argv[1], argv[2], isBinary)) { std::cerr << "Failure for itk::Mesh" << std::endl; result = EXIT_FAILURE; } - if (test(argv[1], argv[2], IsBinary)) + if (test(argv[1], argv[2], isBinary)) { std::cerr << "Failure for itk::QuadEdgeMesh" << std::endl; result = EXIT_FAILURE; } + + // Exercise other methods to improve coverage + itk::BYUMeshIO::Pointer byuMeshIO = itk::BYUMeshIO::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(byuMeshIO, BYUMeshIO, MeshIOBase); + + + std::string fileName("NotABYUMeshFile.nbyu"); + ITK_TEST_EXPECT_TRUE(!byuMeshIO->CanWriteFile(fileName.c_str())); + + fileName = "ABYUMeshFileName.byu"; + ITK_TEST_EXPECT_TRUE(byuMeshIO->CanWriteFile(fileName.c_str())); + + + ITK_TRY_EXPECT_EXCEPTION(byuMeshIO->ReadMeshInformation()); + + void * buffer = nullptr; + + ITK_TRY_EXPECT_EXCEPTION(byuMeshIO->ReadPoints(buffer)); + + ITK_TRY_EXPECT_EXCEPTION(byuMeshIO->ReadCells(buffer)); + + fileName = ""; + byuMeshIO->SetFileName(fileName); + ITK_TRY_EXPECT_EXCEPTION(byuMeshIO->WriteMeshInformation()); + + ITK_TRY_EXPECT_EXCEPTION(byuMeshIO->WritePoints(buffer)); + + ITK_TRY_EXPECT_EXCEPTION(byuMeshIO->WriteCells(buffer)); + + fileName = "/NonExistingDirectory/BYUMeshFile.byu"; + byuMeshIO->SetFileName(fileName); + ITK_TRY_EXPECT_EXCEPTION(byuMeshIO->WriteMeshInformation()); + + ITK_TRY_EXPECT_EXCEPTION(byuMeshIO->WritePoints(buffer)); + + ITK_TRY_EXPECT_EXCEPTION(byuMeshIO->WriteCells(buffer)); + + // Empty functions + byuMeshIO->ReadPointData(buffer); + byuMeshIO->ReadCellData(buffer); + + byuMeshIO->WritePointData(buffer); + byuMeshIO->WriteCellData(buffer); + + + std::cout << "Test finished." << std::endl; return result; } diff --git a/Modules/IO/Meta/test/CMakeLists.txt b/Modules/IO/Meta/test/CMakeLists.txt index 9da9b492594..36d19e565a2 100644 --- a/Modules/IO/Meta/test/CMakeLists.txt +++ b/Modules/IO/Meta/test/CMakeLists.txt @@ -53,7 +53,7 @@ itk_add_test(NAME itkMetaImageIOTest2 ${ITK_TEST_OUTPUT_DIR}/itkMetaImageIOTest2.mha) itk_add_test(NAME itkMetaImageIOShouldFailTest COMMAND ITKIOMetaTestDriver itkMetaImageIOTest - DATA{${ITK_DATA_ROOT}/Input/MetaImageError.mhd} 1) + DATA{${ITK_DATA_ROOT}/Input/MetaImageError.mhd} "OutputNotUsed" 1) itk_add_test(NAME testMetaGroup COMMAND ITKIOMetaTestDriver testMetaGroup ${ITK_TEST_OUTPUT_DIR}) diff --git a/Modules/IO/Meta/test/itkMetaImageIOTest.cxx b/Modules/IO/Meta/test/itkMetaImageIOTest.cxx index 66cb6973aa2..ecdf60aa9b9 100644 --- a/Modules/IO/Meta/test/itkMetaImageIOTest.cxx +++ b/Modules/IO/Meta/test/itkMetaImageIOTest.cxx @@ -20,16 +20,19 @@ #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkMetaImageIO.h" +#include "itkTestingMacros.h" // Specific ImageIO test int -itkMetaImageIOTest(int ac, char * av[]) +itkMetaImageIOTest(int argc, char * argv[]) { - if (ac < 3) + if (argc < 3) { - std::cerr << "Usage: " << av[0] << " Input Output [ShouldFail]\n"; + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " Input Output [expectFailureReadingInputFile]" + << std::endl; return EXIT_FAILURE; } @@ -40,45 +43,48 @@ itkMetaImageIOTest(int ac, char * av[]) itk::ImageFileReader::Pointer reader = itk::ImageFileReader::New(); - // force use of MetaIO + // Force use of MetaIO using IOType = itk::MetaImageIO; IOType::Pointer metaIn = IOType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(metaIn, MetaImageIO, ImageIOBase); + + metaIn->SetDoublePrecision(8); // Set manually for coverage reader->SetImageIO(metaIn); - // check usability of dimension (for coverage) + // Check usability of dimension (for coverage) if (!metaIn->SupportsDimension(3)) { std::cerr << "Did not support dimension 3" << std::endl; return EXIT_FAILURE; } - // test subsampling factor (change it then change it back) + // Test subsampling factor (change it then change it back) unsigned int origSubSamplingFactor = metaIn->GetSubSamplingFactor(); unsigned int subSamplingFactor = 2; metaIn->SetSubSamplingFactor(subSamplingFactor); - if (metaIn->GetSubSamplingFactor() != subSamplingFactor) + ITK_TEST_SET_GET_VALUE(subSamplingFactor, metaIn->GetSubSamplingFactor()); + + metaIn->SetSubSamplingFactor(origSubSamplingFactor); + + // Read the file + reader->SetFileName(argv[1]); + + auto expectFailureReadingInputFile = false; + if (argc > 3) { - std::cerr << "Did not set/get Sub Sampling factor correctly" << std::endl; - return EXIT_FAILURE; + expectFailureReadingInputFile = static_cast(std::stoi(argv[3])); } - metaIn->SetSubSamplingFactor(origSubSamplingFactor); - // read the file - reader->SetFileName(av[1]); - try + if (expectFailureReadingInputFile) { - reader->Update(); + ITK_TRY_EXPECT_EXCEPTION(reader->Update()); + return EXIT_SUCCESS; } - catch (const itk::ExceptionObject & e) + else { - std::cerr << "exception in file reader " << std::endl; - std::cerr << e << std::endl; - if (ac == 3) // should fail - { - return EXIT_SUCCESS; - } - return EXIT_FAILURE; + ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); } myImage::Pointer image = reader->GetOutput(); @@ -93,8 +99,11 @@ itkMetaImageIOTest(int ac, char * av[]) IOType::Pointer metaOut = IOType::New(); writer->SetImageIO(metaOut); writer->SetInput(reader->GetOutput()); - writer->SetFileName(av[2]); - writer->Update(); + writer->SetFileName(argv[2]); + + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/IO/Meta/test/testMetaArray.cxx b/Modules/IO/Meta/test/testMetaArray.cxx index 51dc4707821..5203d92be7d 100644 --- a/Modules/IO/Meta/test/testMetaArray.cxx +++ b/Modules/IO/Meta/test/testMetaArray.cxx @@ -53,8 +53,7 @@ testMetaArray(int argc, char * argv[]) ITK_TEST_SET_GET_VALUE(precision, arrayWriter->GetPrecision()); bool binary = false; - arrayWriter->SetBinary(binary); - ITK_TEST_SET_GET_VALUE(binary, arrayWriter->GetBinary()); + ITK_TEST_SET_GET_BOOLEAN(arrayWriter, Binary, binary); arrayWriter->SetInput(MET_SHORT, &arr); arrayWriter->Update(); @@ -91,8 +90,7 @@ testMetaArray(int argc, char * argv[]) ITK_TEST_SET_GET_VALUE(precision, arrayWriter->GetPrecision()); binary = true; - arrayWriter->SetBinary(binary); - ITK_TEST_SET_GET_VALUE(binary, arrayWriter->GetBinary()); + ITK_TEST_SET_GET_BOOLEAN(arrayWriter, Binary, binary); arrayWriter->SetInput(MET_FLOAT, &vec); arrayWriter->Update(); @@ -163,5 +161,7 @@ testMetaArray(int argc, char * argv[]) arrayReader->GetOutput(MET_FLOAT, &rcovec); std::cout << " covariant vector float = " << rcovec << std::endl; + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/IO/NIFTI/test/itkNiftiImageIOTest.cxx b/Modules/IO/NIFTI/test/itkNiftiImageIOTest.cxx index 818d56d998a..b3034c96edb 100644 --- a/Modules/IO/NIFTI/test/itkNiftiImageIOTest.cxx +++ b/Modules/IO/NIFTI/test/itkNiftiImageIOTest.cxx @@ -17,6 +17,7 @@ *=========================================================================*/ #include "itkNiftiImageIOTest.h" +#include "itkTestingMacros.h" // Specific ImageIO test @@ -127,13 +128,24 @@ itkNiftiImageIOTest(int ac, char * av[]) using ImageType = itk::Image; ImageType::Pointer input; itk::NiftiImageIO::Pointer imageIO = itk::NiftiImageIO::New(); - // enable old behavior of NIFTI reader + + ITK_EXERCISE_BASIC_OBJECT_METHODS(imageIO, NiftiImageIO, ImageIOBase); + + + // Enable old behavior of NIFTI reader imageIO->SetLegacyAnalyze75Mode(itk::Analyze75Flavor::AnalyzeITK4); for (int imagenameindex = 1; imagenameindex < ac; imagenameindex++) { + auto fileName = std::string(av[imagenameindex]); + + // The way the test is structured, we cannot know the expected file + // type, so just print it + typename itk::NiftiImageIO::FileType fileType = imageIO->DetermineFileType(fileName.c_str()); + std::cout << "File type: " << fileType << std::endl; + try { - input = itk::IOTestHelper::ReadImage(std::string(av[imagenameindex]), false, imageIO); + input = itk::IOTestHelper::ReadImage(fileName, false, imageIO); } catch (const itk::ExceptionObject & e) { diff --git a/Modules/IO/NRRD/test/itkNrrdImageIOTest.h b/Modules/IO/NRRD/test/itkNrrdImageIOTest.h index 32f1a52247d..bf5c5dbb52e 100644 --- a/Modules/IO/NRRD/test/itkNrrdImageIOTest.h +++ b/Modules/IO/NRRD/test/itkNrrdImageIOTest.h @@ -25,6 +25,7 @@ #include "itkNrrdImageIO.h" #include "itkImage.h" #include "itkRandomImageSource.h" +#include "itkTestingMacros.h" template typename itk::Image::Pointer @@ -63,6 +64,20 @@ itkNrrdImageIOTestReadWriteTest(std::string fn, unsigned int size, std::string i typename itk::ImageFileWriter::Pointer writer = itk::ImageFileWriter::New(); itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(io, NrrdImageIO, ImageIOBase); + + + ITK_TEST_EXPECT_TRUE(io->SupportsDimension(VImageDimension)); + + constexpr unsigned NRRD_DIM_MAX = 16; // taken from NrrdIO.h which is not in the include path + unsigned long dim = NRRD_DIM_MAX + 1; + ITK_TEST_EXPECT_TRUE(!io->SupportsDimension(dim)); + + // Binary files have no image information to read + io->WriteImageInformation(); + + reader->SetImageIO(io); writer->SetImageIO(io); @@ -73,16 +88,10 @@ itkNrrdImageIOTestReadWriteTest(std::string fn, unsigned int size, std::string i typename itk::ImageFileReader::Pointer tmpReader = itk::ImageFileReader::New(); tmpReader->SetImageIO(io); tmpReader->SetFileName(inputFile.c_str()); - try - { - tmpReader->Update(); - std::cout << "DONE READING INPUT IMAGE" << std::endl; - } - catch (const itk::ExceptionObject & e) - { - std::cerr << e << std::endl; - return EXIT_FAILURE; - } + + ITK_TRY_EXPECT_NO_EXCEPTION(tmpReader->Update()); + + std::cout << "DONE READING INPUT IMAGE" << std::endl; image = tmpReader->GetOutput(); } @@ -119,20 +128,14 @@ itkNrrdImageIOTestReadWriteTest(std::string fn, unsigned int size, std::string i image->Print(std::cout); std::cout << "----------" << std::endl; - try - { - writer->Update(); - std::cout << "DONE WRITING TEST IMAGE" << std::endl; - reader->Update(); - std::cout << "DONE READING TEST IMAGE" << std::endl; - } - catch (const itk::ExceptionObject & e) - { - std::cerr << "Exception in file reader or writer " << std::endl; - std::cerr << e.GetDescription() << std::endl; - std::cerr << e.GetLocation() << std::endl; - return EXIT_FAILURE; - } + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); + + std::cout << "DONE WRITING TEST IMAGE" << std::endl; + + + ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); + + std::cout << "DONE READING TEST IMAGE" << std::endl; // Print the image information. diff --git a/Modules/IO/RAW/test/itkRawImageIOTest.cxx b/Modules/IO/RAW/test/itkRawImageIOTest.cxx index 4969e39cb94..700adf28aa7 100644 --- a/Modules/IO/RAW/test/itkRawImageIOTest.cxx +++ b/Modules/IO/RAW/test/itkRawImageIOTest.cxx @@ -29,19 +29,23 @@ int itkRawImageIOTest(int argc, char * argv[]) { - using ImageType = itk::Image; - using PixelType = ImageType::PixelType; - using ImageIteratorType = itk::ImageRegionConstIterator; if (argc < 3) { - std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " Output1 Output2\n"; + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " Output1 Output2" << std::endl; return EXIT_FAILURE; } + constexpr unsigned int Dimension = 2; + + using ImageType = itk::Image; + using PixelType = ImageType::PixelType; + using ImageIteratorType = itk::ImageRegionConstIterator; + // Create a source object (in this case a random image generator). // The source object is templated on the output type. // - ImageType::SizeValueType size[2]; + ImageType::SizeValueType size[Dimension]; size[0] = 128; size[1] = 64; @@ -55,45 +59,53 @@ itkRawImageIOTest(int argc, char * argv[]) // Create a mapper (in this case a writer). A mapper // is templated on the input type. // - itk::RawImageIO::Pointer io; - io = itk::RawImageIO::New(); + itk::RawImageIO::Pointer io; + io = itk::RawImageIO::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(io, RawImageIO, ImageIOBase); // io->SetFileTypeToASCII(); + io->SetFileDimensionality(Dimension); + ITK_TEST_SET_GET_VALUE(Dimension, io->GetFileDimensionality()); + + ITK_TEST_EXPECT_TRUE(io->SupportsDimension(Dimension)); + + unsigned long dim = 3; + ITK_TEST_EXPECT_TRUE(!io->SupportsDimension(dim)); + + // Binary files have no image information to read + io->WriteImageInformation(); + // Write out the image + std::string filename = ""; + ITK_TEST_EXPECT_TRUE(!io->CanWriteFile(filename.c_str())); + + ITK_TRY_EXPECT_EXCEPTION(io->GetHeaderSize()); + + filename = argv[1]; + ITK_TEST_EXPECT_TRUE(io->CanWriteFile(filename.c_str())); + itk::ImageFileWriter::Pointer writer; writer = itk::ImageFileWriter::New(); writer->SetInput(random->GetOutput()); - writer->SetFileName(argv[1]); + writer->SetFileName(filename); writer->SetImageIO(io); - try - { - writer->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Error while writing the image " << argv[1] << std::endl; - std::cerr << excp << std::endl; - } + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); + // Create a source object (in this case a reader) itk::ImageFileReader::Pointer reader; reader = itk::ImageFileReader::New(); reader->SetImageIO(io); - reader->SetFileName(argv[1]); + reader->SetFileName(filename); - try - { - reader->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Error while reading the image " << argv[1] << std::endl; - std::cerr << excp << std::endl; - } + ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); + io->CanReadFile(filename.c_str()); + // Compare pixel by pixel in memory @@ -123,17 +135,9 @@ itkRawImageIOTest(int argc, char * argv[]) writer->SetFileName(argv[2]); writer->SetInput(reader->GetOutput()); - try - { - writer->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Error while writing the image " << argv[2] << std::endl; - std::cerr << excp << std::endl; - } + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); - std::cerr << "Test PASSED ! " << std::endl; + std::cout << "Test PASSED ! " << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/IO/RAW/test/itkRawImageIOTest2.cxx b/Modules/IO/RAW/test/itkRawImageIOTest2.cxx index e8748697f75..267a8caf45c 100644 --- a/Modules/IO/RAW/test/itkRawImageIOTest2.cxx +++ b/Modules/IO/RAW/test/itkRawImageIOTest2.cxx @@ -20,6 +20,7 @@ #include "itkTextOutput.h" #include "itkRawImageIO.h" #include "itkImageFileReader.h" +#include "itkTestingMacros.h" // Specific ImageIO test @@ -31,7 +32,8 @@ itkRawImageIOTest2(int argc, char * argv[]) if (argc < 2) { - itkGenericOutputMacro(<< "Need a file to process"); + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " inputFilename" << std::endl; return EXIT_FAILURE; } @@ -59,7 +61,10 @@ itkRawImageIOTest2(int argc, char * argv[]) io->SetOrigin(i, origin[i]); } io->SetHeaderSize(0); - io->SetImageMask(0x7fff); + unsigned short imageMask = 0x7fff; + io->SetImageMask(imageMask); + ITK_TEST_SET_GET_VALUE(imageMask, io->GetImageMask()); + io->SetByteOrderToLittleEndian(); io->SetPixelType(itk::IOPixelEnum::RGB); io->SetComponentType(itk::IOComponentEnum::UCHAR); @@ -72,9 +77,12 @@ itkRawImageIOTest2(int argc, char * argv[]) reader = itk::ImageFileReader::New(); reader->SetFileName(argv[1]); reader->SetImageIO(io); - reader->Update(); + + ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); + reader->GetOutput()->Print(std::cout); + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/IO/SpatialObjects/test/itkPolygonGroupSpatialObjectXMLFileTest.cxx b/Modules/IO/SpatialObjects/test/itkPolygonGroupSpatialObjectXMLFileTest.cxx index 21e7fc94b5b..576dc21b58d 100644 --- a/Modules/IO/SpatialObjects/test/itkPolygonGroupSpatialObjectXMLFileTest.cxx +++ b/Modules/IO/SpatialObjects/test/itkPolygonGroupSpatialObjectXMLFileTest.cxx @@ -19,6 +19,7 @@ #include #include "itkPolygonGroupSpatialObjectXMLFile.h" #include "itksys/SystemTools.hxx" +#include "itkTestingMacros.h" static float strandPoints[11][2] = { { 1, 1 }, { 1, 2 }, { 1.25, 2 }, { 1.25, 1.25 }, { 1.75, 1.25 }, { 1.75, 1.5 }, { 1.5, 1.5 }, { 1.5, 2 }, @@ -144,7 +145,8 @@ itkPolygonGroupSpatialObjectXMLFileTest(int ac, char * av[]) { if (ac < 2) { - std::cerr << "Usage: " << av[0] << " XMLfile\n"; + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(av) << " XMLfile" << std::endl; return EXIT_FAILURE; } @@ -163,6 +165,11 @@ itkPolygonGroupSpatialObjectXMLFileTest(int ac, char * av[]) { itk::PolygonGroupSpatialObjectXMLFileWriter::Pointer pw = itk::PolygonGroupSpatialObjectXMLFileWriter::New(); + ITK_EXERCISE_BASIC_OBJECT_METHODS(pw, PolygonGroupSpatialObjectXMLFileWriter, XMLWriterBase); + + + ITK_TEST_EXPECT_TRUE(pw->CanWriteFile("")); + pw->SetFilename(xmlfilename.c_str()); pw->SetObject(&(*PolygonGroup)); pw->WriteFile(); @@ -176,7 +183,15 @@ itkPolygonGroupSpatialObjectXMLFileTest(int ac, char * av[]) try { itk::PolygonGroupSpatialObjectXMLFileReader::Pointer p = itk::PolygonGroupSpatialObjectXMLFileReader::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(p, PolygonGroupSpatialObjectXMLFileReader, XMLReader); + + ITK_TEST_EXPECT_TRUE(!p->CanReadFile("")); + + ITK_TEST_EXPECT_TRUE(p->CanReadFile(xmlfilename.c_str())); + p->SetFilename(xmlfilename.c_str()); + p->GenerateOutputInformation(); PGroupFromFile = p->GetOutputObject(); if (PGroupFromFile.IsNull()) diff --git a/Modules/Nonunit/Review/test/itkMultiphaseSparseFiniteDifferenceImageFilterTest.cxx b/Modules/Nonunit/Review/test/itkMultiphaseSparseFiniteDifferenceImageFilterTest.cxx index 1a5fd010712..ad8530a6e18 100644 --- a/Modules/Nonunit/Review/test/itkMultiphaseSparseFiniteDifferenceImageFilterTest.cxx +++ b/Modules/Nonunit/Review/test/itkMultiphaseSparseFiniteDifferenceImageFilterTest.cxx @@ -18,6 +18,7 @@ #include "itkMultiphaseSparseFiniteDifferenceImageFilter.h" #include "itkScalarChanAndVeseLevelSetFunction.h" +#include "itkPrintHelper.h" #include "itkTestingMacros.h" namespace itk @@ -104,13 +105,32 @@ itkMultiphaseSparseFiniteDifferenceImageFilterTest(int, char *[]) FilterType::Pointer filter = FilterType::New(); - std::cout << "GetNameOfClass() = " << filter->GetNameOfClass() << std::endl; - filter->Print(std::cout); + ITK_EXERCISE_BASIC_OBJECT_METHODS( + filter, MultiphaseSparseFiniteDifferenceImageFilterTestHelper, MultiphaseFiniteDifferenceImageFilter); + // Exercise the class Set/Get methods to increase coverage + unsigned int numberOfLayers = Dimension; + filter->SetNumberOfLayers(numberOfLayers); + ITK_TEST_SET_GET_VALUE(numberOfLayers, filter->GetNumberOfLayers()); + + using ValueType = typename FilterType::ValueType; + + ValueType isoSurfaceValue = itk::NumericTraits::ZeroValue(); + filter->SetIsoSurfaceValue(isoSurfaceValue); + ITK_TEST_SET_GET_VALUE(isoSurfaceValue, filter->GetIsoSurfaceValue()); + bool interpolateSurfaceLocation = true; ITK_TEST_SET_GET_BOOLEAN(filter, InterpolateSurfaceLocation, interpolateSurfaceLocation); + ValueType valueZero = itk::NumericTraits::ZeroValue(); + ITK_TEST_SET_GET_VALUE(valueZero, filter->GetValueZero()); + + ValueType valueOne = itk::NumericTraits::OneValue(); + + ITK_TEST_SET_GET_VALUE(valueOne, filter->GetValueOne()); + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Numerics/Statistics/test/CMakeLists.txt b/Modules/Numerics/Statistics/test/CMakeLists.txt index b57de54f304..a5947447229 100644 --- a/Modules/Numerics/Statistics/test/CMakeLists.txt +++ b/Modules/Numerics/Statistics/test/CMakeLists.txt @@ -405,7 +405,7 @@ itk_add_test(NAME itkUniformRandomSpatialNeighborSubsamplerTest COMMAND ITKStatisticsTestDriver --compare DATA{Baseline/itkUniformRandomSubsamplingTest.mha} ${ITK_TEST_OUTPUT_DIR}/itkUniformRandomSubsamplingTest.mha - itkUniformRandomSpatialNeighborSubsamplerTest + itkUniformRandomSpatialNeighborSubsamplerTest 0 ${ITK_TEST_OUTPUT_DIR}/itkUniformRandomSubsamplingTest.mha) itk_add_test(NAME itkVectorContainerToListSampleAdaptorTest COMMAND ITKStatisticsTestDriver itkVectorContainerToListSampleAdaptorTest) diff --git a/Modules/Numerics/Statistics/test/itkUniformRandomSpatialNeighborSubsamplerTest.cxx b/Modules/Numerics/Statistics/test/itkUniformRandomSpatialNeighborSubsamplerTest.cxx index d0ae45e9a4d..4c8a1e03026 100644 --- a/Modules/Numerics/Statistics/test/itkUniformRandomSpatialNeighborSubsamplerTest.cxx +++ b/Modules/Numerics/Statistics/test/itkUniformRandomSpatialNeighborSubsamplerTest.cxx @@ -26,16 +26,16 @@ #include "itkZeroFluxNeumannBoundaryCondition.h" #include "itkUniformRandomSpatialNeighborSubsampler.h" +#include "itkTestingMacros.h" int itkUniformRandomSpatialNeighborSubsamplerTest(int argc, char * argv[]) { - std::cout << "UniformRandomSpatialNeighborSubsampler Test \n \n"; - - std::string outFile = ""; - if (argc > 1) + if (argc < 2) { - outFile = argv[1]; + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " useClockForSeed [outFileName]" << std::endl; + return EXIT_FAILURE; } using FloatImage = itk::Image; @@ -64,6 +64,10 @@ itkUniformRandomSpatialNeighborSubsamplerTest(int argc, char * argv[]) sample->SetImage(inImage); SamplerType::Pointer sampler_orig = SamplerType::New(); + + ITK_EXERCISE_BASIC_OBJECT_METHODS(sampler_orig, UniformRandomSpatialNeighborSubsampler, SpatialNeighborSubsampler); + + sampler_orig->SetSample(sample); sampler_orig->SetSampleRegion(region); sampler_orig->SetRadius(20); @@ -71,38 +75,18 @@ itkUniformRandomSpatialNeighborSubsamplerTest(int argc, char * argv[]) sampler_orig->SetSeed(100); sampler_orig->CanSelectQueryOff(); - // test clone mechanism + auto useClockForSeed = static_cast(std::stoi(argv[1])); + ITK_TEST_SET_GET_BOOLEAN(sampler_orig, UseClockForSeed, useClockForSeed); + + // Test clone mechanism SamplerType::Pointer sampler = sampler_orig->Clone().GetPointer(); - if (sampler->GetSample() != sampler_orig->GetSample()) - { - std::cerr << "Clone did not copy the sample correctly!" << std::endl; - return EXIT_FAILURE; - } - if (sampler->GetSampleRegion() != sampler_orig->GetSampleRegion()) - { - std::cerr << "Clone did not copy the region correctly!" << std::endl; - return EXIT_FAILURE; - } - if (sampler->GetRadius() != sampler_orig->GetRadius()) - { - std::cerr << "Clone did not copy the radius correctly!" << std::endl; - return EXIT_FAILURE; - } - if (sampler->GetNumberOfResultsRequested() != sampler_orig->GetNumberOfResultsRequested()) - { - std::cerr << "Clone did not copy the number of results requested correctly!" << std::endl; - return EXIT_FAILURE; - } - if (sampler->GetSeed() != sampler_orig->GetSeed()) - { - std::cerr << "Clone did not copy the seed correctly!" << std::endl; - return EXIT_FAILURE; - } - if (sampler->GetCanSelectQuery() != sampler_orig->GetCanSelectQuery()) - { - std::cerr << "Clone did not copy CanSelectQuery correctly!" << std::endl; - return EXIT_FAILURE; - } + + ITK_TEST_SET_GET_VALUE(sampler_orig->GetSample(), sampler->GetSample()); + ITK_TEST_SET_GET_VALUE(sampler_orig->GetSampleRegion(), sampler->GetSampleRegion()); + ITK_TEST_SET_GET_VALUE(sampler_orig->GetRadius(), sampler->GetRadius()); + ITK_TEST_SET_GET_VALUE(sampler_orig->GetNumberOfResultsRequested(), sampler->GetNumberOfResultsRequested()); + ITK_TEST_SET_GET_VALUE(sampler_orig->GetSeed(), sampler->GetSeed()); + ITK_TEST_SET_GET_VALUE(sampler_orig->GetCanSelectQuery(), sampler->GetCanSelectQuery()); SamplerType::SubsamplePointer subsample = SamplerType::SubsampleType::New(); sampler->Search(612, subsample); @@ -114,19 +98,16 @@ itkUniformRandomSpatialNeighborSubsamplerTest(int argc, char * argv[]) inImage->SetPixel(index, 255); } - if (!outFile.empty()) + + if (argc > 2) { + const std::string outFileName(argv[2]); + WriterType::Pointer writer = WriterType::New(); - writer->SetFileName(outFile); + writer->SetFileName(outFileName); writer->SetInput(inImage); - try - { - writer->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << excp << std::endl; - } + + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); } std::cout << "Test passed." << std::endl; diff --git a/Modules/Numerics/Statistics/test/itkVectorContainerToListSampleAdaptorTest.cxx b/Modules/Numerics/Statistics/test/itkVectorContainerToListSampleAdaptorTest.cxx index a20efb19674..11e450dfee2 100644 --- a/Modules/Numerics/Statistics/test/itkVectorContainerToListSampleAdaptorTest.cxx +++ b/Modules/Numerics/Statistics/test/itkVectorContainerToListSampleAdaptorTest.cxx @@ -17,11 +17,11 @@ *=========================================================================*/ #include "itkVectorContainerToListSampleAdaptor.h" +#include "itkTestingMacros.h" int itkVectorContainerToListSampleAdaptorTest(int, char *[]) { - std::cout << "VectorContainerToListSampleAdaptor Test \n \n"; using VectorType = itk::Vector; @@ -31,9 +31,45 @@ itkVectorContainerToListSampleAdaptorTest(int, char *[]) AdaptorType::Pointer adaptor = AdaptorType::New(); + ITK_EXERCISE_BASIC_OBJECT_METHODS(adaptor, VectorContainerToListSampleAdaptor, ListSample); + + // Test the exceptions + ITK_TRY_EXPECT_EXCEPTION(adaptor->Size()); + + typename AdaptorType::InstanceIdentifier instance = 0; + ITK_TRY_EXPECT_EXCEPTION(adaptor->GetMeasurementVector(instance)); + + ITK_TRY_EXPECT_EXCEPTION(adaptor->GetFrequency(instance)); + + ITK_TRY_EXPECT_EXCEPTION(adaptor->GetTotalFrequency()); + + // Set the vector container + unsigned int containerSize = 3; ContainerType::Pointer container = ContainerType::New(); + container->Reserve(containerSize); + for (unsigned int i = 0; i < container->Size(); ++i) + { + VectorType vector; + vector.Fill(std::pow(i, 2)); + container->InsertElement(i, vector); + } adaptor->SetVectorContainer(container); + ITK_TEST_SET_GET_VALUE(container, adaptor->GetVectorContainer()); + + typename AdaptorType::InstanceIdentifier expectedSize = 3; + typename AdaptorType::InstanceIdentifier size = adaptor->Size(); + ITK_TEST_EXPECT_EQUAL(expectedSize, size); + + typename AdaptorType::AbsoluteFrequencyType expectedFreq = 1; + typename AdaptorType::AbsoluteFrequencyType freq = adaptor->GetFrequency(instance); + ITK_TEST_EXPECT_EQUAL(expectedFreq, freq); + + typename AdaptorType::TotalAbsoluteFrequencyType expectedTotalFreq = 3; + typename AdaptorType::TotalAbsoluteFrequencyType totalFreq = adaptor->GetTotalFrequency(); + ITK_TEST_EXPECT_EQUAL(expectedTotalFreq, totalFreq); + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Registration/PDEDeformable/test/itkLevelSetMotionRegistrationFilterTest.cxx b/Modules/Registration/PDEDeformable/test/itkLevelSetMotionRegistrationFilterTest.cxx index 382110dd098..0437e8a4e55 100644 --- a/Modules/Registration/PDEDeformable/test/itkLevelSetMotionRegistrationFilterTest.cxx +++ b/Modules/Registration/PDEDeformable/test/itkLevelSetMotionRegistrationFilterTest.cxx @@ -23,6 +23,7 @@ #include "itkCastImageFilter.h" #include "itkImageFileWriter.h" #include "itkMath.h" +#include "itkTestingMacros.h" namespace @@ -131,7 +132,6 @@ itkLevelSetMotionRegistrationFilterTest(int argc, char * argv[]) using SizeType = ImageType::SizeType; using RegionType = ImageType::RegionType; - //-------------------------------------------------------- std::cout << "Generate input images and initial deformation field"; std::cout << std::endl; @@ -189,12 +189,14 @@ itkLevelSetMotionRegistrationFilterTest(int argc, char * argv[]) caster->SetInput(initField); caster->InPlaceOff(); - //------------------------------------------------------------- std::cout << "Run registration and warp moving" << std::endl; using RegistrationType = itk::LevelSetMotionRegistrationFilter; RegistrationType::Pointer registrator = RegistrationType::New(); + ITK_EXERCISE_BASIC_OBJECT_METHODS(registrator, LevelSetMotionRegistrationFilter, PDEDeformableRegistrationFilter); + + registrator->SetInitialDisplacementField(caster->GetOutput()); registrator->SetMovingImage(moving); registrator->SetFixedImage(fixed); @@ -203,12 +205,23 @@ itkLevelSetMotionRegistrationFilterTest(int argc, char * argv[]) registrator->SetStandardDeviations(1.0); registrator->SetMaximumError(0.08); registrator->SetMaximumKernelWidth(10); - registrator->SetIntensityDifferenceThreshold(0.001); - // turn on inplace execution + double intensityDifferenceThreshold = 0.001; + registrator->SetIntensityDifferenceThreshold(intensityDifferenceThreshold); + ITK_TEST_SET_GET_VALUE(intensityDifferenceThreshold, registrator->GetIntensityDifferenceThreshold()); + + double gradientMagnitudeThreshold = 1e-9; + registrator->SetGradientMagnitudeThreshold(gradientMagnitudeThreshold); + ITK_TEST_SET_GET_VALUE(gradientMagnitudeThreshold, registrator->GetGradientMagnitudeThreshold()); + + double alpha = 0.1; + registrator->SetAlpha(alpha); + ITK_TEST_SET_GET_VALUE(alpha, registrator->GetAlpha()); + + // Turn on inplace execution registrator->InPlaceOn(); - // turn on/off use image spacing + // Turn on/off use image spacing registrator->UseImageSpacingOn(); using FunctionType = RegistrationType::LevelSetMotionFunctionType; @@ -219,7 +232,7 @@ itkLevelSetMotionRegistrationFilterTest(int argc, char * argv[]) fptr->Print(std::cout); } - // exercise other member variables + // Exercise other member variables std::cout << "No. Iterations: " << registrator->GetNumberOfIterations() << std::endl; std::cout << "Max. kernel error: " << registrator->GetMaximumError() << std::endl; std::cout << "Max. kernel width: " << registrator->GetMaximumKernelWidth() << std::endl; @@ -241,7 +254,7 @@ itkLevelSetMotionRegistrationFilterTest(int argc, char * argv[]) registrator->AddObserver(itk::ProgressEvent(), command); - // warp moving image + // Warp moving image using WarperType = itk::WarpImageFilter; WarperType::Pointer warper = WarperType::New(); @@ -249,7 +262,6 @@ itkLevelSetMotionRegistrationFilterTest(int argc, char * argv[]) using InterpolatorType = itk::NearestNeighborInterpolateImageFunction; InterpolatorType::Pointer interpolator = InterpolatorType::New(); - warper->SetInput(moving); warper->SetDisplacementField(registrator->GetOutput()); warper->SetInterpolator(interpolator); @@ -287,10 +299,9 @@ itkLevelSetMotionRegistrationFilterTest(int argc, char * argv[]) } - // --------------------------------------------------------- std::cout << "Compare warped moving and fixed." << std::endl; - // compare the warp and fixed images + // Compare the warp and fixed images itk::ImageRegionIterator fixedIter(fixed, fixed->GetBufferedRegion()); itk::ImageRegionIterator warpedIter(warper->GetOutput(), fixed->GetBufferedRegion()); @@ -318,7 +329,6 @@ itkLevelSetMotionRegistrationFilterTest(int argc, char * argv[]) registrator->Print(std::cout); - // ----------------------------------------------------------- std::cout << "Test running registrator without initial deformation field."; std::cout << std::endl; diff --git a/Modules/Registration/RegistrationMethodsv4/test/itkSyNImageRegistrationTest.cxx b/Modules/Registration/RegistrationMethodsv4/test/itkSyNImageRegistrationTest.cxx index d15540479c2..2c089b2164b 100644 --- a/Modules/Registration/RegistrationMethodsv4/test/itkSyNImageRegistrationTest.cxx +++ b/Modules/Registration/RegistrationMethodsv4/test/itkSyNImageRegistrationTest.cxx @@ -158,16 +158,10 @@ PerformDisplacementFieldImageRegistration(int itkNotUsed(argc), char * argv[]) optimizer->SetNumberOfIterations(1); #endif - try - { - std::cout << "Affine transform" << std::endl; - affineSimple->Update(); - } - catch (const itk::ExceptionObject & e) - { - std::cerr << "Exception caught: " << e << std::endl; - return EXIT_FAILURE; - } + std::cout << "Affine transform" << std::endl; + + ITK_TRY_EXPECT_NO_EXCEPTION(affineSimple->Update()); + // // Now do the displacement field transform with gaussian smoothing using @@ -221,6 +215,9 @@ PerformDisplacementFieldImageRegistration(int itkNotUsed(argc), char * argv[]) typename DisplacementFieldRegistrationType::Pointer displacementFieldRegistration = DisplacementFieldRegistrationType::New(); + ITK_EXERCISE_BASIC_OBJECT_METHODS( + displacementFieldRegistration, SyNImageRegistrationMethod, ImageRegistrationMethodv4); + using OutputTransformType = typename DisplacementFieldRegistrationType::OutputTransformType; typename OutputTransformType::Pointer outputTransform = OutputTransformType::New(); outputTransform->SetDisplacementField(displacementField); @@ -458,5 +455,8 @@ itkSyNImageRegistrationTest(int argc, char * argv[]) std::cerr << "Unsupported dimension" << std::endl; exit(EXIT_FAILURE); } + + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Segmentation/Classifiers/test/itkScalarImageKmeansImageFilterTest.cxx b/Modules/Segmentation/Classifiers/test/itkScalarImageKmeansImageFilterTest.cxx index 66daf9fed1b..5673a726120 100644 --- a/Modules/Segmentation/Classifiers/test/itkScalarImageKmeansImageFilterTest.cxx +++ b/Modules/Segmentation/Classifiers/test/itkScalarImageKmeansImageFilterTest.cxx @@ -27,9 +27,12 @@ itkScalarImageKmeansImageFilterTest(int argc, char * argv[]) { if (argc < 5) { - std::cerr << "Usage: " << std::endl; - std::cerr << itkNameOfTestExecutableMacro(argv); - std::cerr << " inputScalarImage outputLabeledImage numberOfClasses mean1 mean2... meanN " << std::endl; + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " inputScalarImage" + << " outputLabeledImage" + << " useNonContiguousLabels" + << " numberOfClasses" + << " mean1 mean2... meanN" << std::endl; return EXIT_FAILURE; } @@ -41,28 +44,21 @@ itkScalarImageKmeansImageFilterTest(int argc, char * argv[]) using ReaderType = itk::ImageFileReader; ReaderType::Pointer reader = ReaderType::New(); - reader->SetFileName(argv[1]); - try - { - reader->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Problem encoutered while reading image file : " << argv[1] << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } + ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); using KMeansFilterType = itk::ScalarImageKmeansImageFilter; KMeansFilterType::Pointer kmeansFilter = KMeansFilterType::New(); + ITK_EXERCISE_BASIC_OBJECT_METHODS(kmeansFilter, ScalarImageKmeansImageFilter, ImageToImageFilter); + kmeansFilter->SetInput(reader->GetOutput()); - kmeansFilter->SetUseNonContiguousLabels(argv[3]); + auto useNonContiguousLabels = static_cast(std::stoi(argv[3])); + ITK_TEST_SET_GET_BOOLEAN(kmeansFilter, UseNonContiguousLabels, useNonContiguousLabels); const unsigned int numberOfInitialClasses = std::stoi(argv[4]); @@ -76,7 +72,7 @@ itkScalarImageKmeansImageFilterTest(int argc, char * argv[]) return EXIT_FAILURE; } - // before we add any mean check that an expection is thrown + // Before we add any mean check that an expection is thrown ITK_TRY_EXPECT_EXCEPTION(kmeansFilter->Update()); @@ -85,17 +81,8 @@ itkScalarImageKmeansImageFilterTest(int argc, char * argv[]) kmeansFilter->AddClassWithInitialMean(std::stod(argv[k + numberOfArgumentsBeforeMeans])); } + ITK_TRY_EXPECT_NO_EXCEPTION(kmeansFilter->Update()); - try - { - kmeansFilter->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Problem encoutered while classifying the image " << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } KMeansFilterType::ParametersType estimatedMeans = kmeansFilter->GetFinalMeans(); @@ -121,16 +108,7 @@ itkScalarImageKmeansImageFilterTest(int argc, char * argv[]) writer->SetInput(relabeler->GetOutput()); writer->SetFileName(argv[2]); - try - { - writer->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Problem encoutered while writing image file : " << argv[2] << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); using SizesType = RelabelFilterType::ObjectSizeInPixelsContainerType; @@ -149,5 +127,7 @@ itkScalarImageKmeansImageFilterTest(int argc, char * argv[]) ++sizeItr; } + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Segmentation/ConnectedComponents/test/itkThresholdMaximumConnectedComponentsImageFilterTest.cxx b/Modules/Segmentation/ConnectedComponents/test/itkThresholdMaximumConnectedComponentsImageFilterTest.cxx index 20b35453584..0dfa5ffe174 100644 --- a/Modules/Segmentation/ConnectedComponents/test/itkThresholdMaximumConnectedComponentsImageFilterTest.cxx +++ b/Modules/Segmentation/ConnectedComponents/test/itkThresholdMaximumConnectedComponentsImageFilterTest.cxx @@ -40,9 +40,9 @@ itkThresholdMaximumConnectedComponentsImageFilterTest(int argc, char * argv[]) { if (argc < 3) { - std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << std::endl; - std::cerr << " 1: InputImage Name 2:OutputImage Name" << std::endl; - std::cerr << " 3: minimumPixelArea" << std::endl; + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " inputFileName outputFileName minimumPixelArea" + << std::endl; return EXIT_FAILURE; } @@ -61,24 +61,11 @@ itkThresholdMaximumConnectedComponentsImageFilterTest(int argc, char * argv[]) using ReaderType = itk::ImageFileReader; ReaderType::Pointer reader = ReaderType::New(); - reader->SetFileName(argv[1]); - // Read the Input Image - std::cout << "About to load input image " << std::endl; + ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); - try - { - reader->Update(); - } - catch (const itk::ExceptionObject & err) - { - std::cerr << "Exception Caught!" << std::endl; - std::cerr << err << std::endl; - return EXIT_FAILURE; - } - // ************************************************************************ // Automatic Threshold Filter // This filter essentially chooses the optimum place to threshold the object. // It also indirectly will count the number of objects for you. @@ -92,26 +79,29 @@ itkThresholdMaximumConnectedComponentsImageFilterTest(int argc, char * argv[]) using ThresholdType = itk::ThresholdMaximumConnectedComponentsImageFilter; ThresholdType::Pointer automaticThreshold = ThresholdType::New(); + ITK_EXERCISE_BASIC_OBJECT_METHODS( + automaticThreshold, ThresholdMaximumConnectedComponentsImageFilter, ImageToImageFilter); + automaticThreshold->SetInput(reader->GetOutput()); automaticThreshold->SetMinimumObjectSizeInPixels(minimumPixelArea); + ITK_TEST_SET_GET_VALUE(minimumPixelArea, automaticThreshold->GetMinimumObjectSizeInPixels()); // For counting Myofibers, the inside value should be the minLabel // If you wanted to count a solid object (ie dapi nuclei) set the // inside value to minLabel. // automaticThreshold->SetInsideValue(minLabel); + ITK_TEST_SET_GET_VALUE(minLabel, automaticThreshold->GetInsideValue()); + automaticThreshold->SetOutsideValue(maxLabel); + ITK_TEST_SET_GET_VALUE(maxLabel, automaticThreshold->GetOutsideValue()); + + typename ThresholdType::PixelType upperBoundary = itk::NumericTraits::max(); + automaticThreshold->SetUpperBoundary(upperBoundary); + ITK_TEST_SET_GET_VALUE(upperBoundary, automaticThreshold->GetUpperBoundary()); + + ITK_TRY_EXPECT_NO_EXCEPTION(automaticThreshold->Update()); - try - { - automaticThreshold->Update(); - } - catch (const itk::ExceptionObject & err) - { - std::cerr << "Exception Caught!" << std::endl; - std::cerr << err << std::endl; - return EXIT_FAILURE; - } numberOfObjects = automaticThreshold->GetNumberOfObjects(); thresholdValue = automaticThreshold->GetThresholdValue(); @@ -119,25 +109,16 @@ itkThresholdMaximumConnectedComponentsImageFilterTest(int argc, char * argv[]) std::cout << "Number of Objects = " << numberOfObjects << std::endl; std::cout << "Threshold Value = " << thresholdValue << std::endl; - // ***************************************************************** - // Image File Writer + using WriterType = itk::ImageFileWriter; WriterType::Pointer writer = WriterType::New(); writer->SetInput(automaticThreshold->GetOutput()); - writer->SetFileName(argv[2]); - try - { - writer->Update(); - } - catch (const itk::ExceptionObject & err) - { - std::cerr << "Exception Caught!" << std::endl; - std::cerr << err << std::endl; - return EXIT_FAILURE; - } + ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); + + std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Segmentation/LevelSets/test/itkNarrowBandCurvesLevelSetImageFilterTest.cxx b/Modules/Segmentation/LevelSets/test/itkNarrowBandCurvesLevelSetImageFilterTest.cxx index ad6ab1ba910..757b888cb08 100644 --- a/Modules/Segmentation/LevelSets/test/itkNarrowBandCurvesLevelSetImageFilterTest.cxx +++ b/Modules/Segmentation/LevelSets/test/itkNarrowBandCurvesLevelSetImageFilterTest.cxx @@ -24,9 +24,6 @@ #include "itkFastMarchingImageFilter.h" #include "itkBinaryThresholdImageFilter.h" #include "itkSimilarityIndexImageFilter.h" - -/* Uncomment to write out image files */ - #include "itkRescaleIntensityImageFilter.h" #include "itkImageFileWriter.h" #include "itkTestingMacros.h" @@ -38,7 +35,8 @@ itkNarrowBandCurvesLevelSetImageFilterTest(int argc, char * argv[]) if (argc < 2) { - std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " OutputImage\n"; + std::cerr << "Missing Parameters." << std::endl; + std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " OutputImage" << std::endl; return EXIT_FAILURE; } @@ -56,10 +54,8 @@ itkNarrowBandCurvesLevelSetImageFilterTest(int argc, char * argv[]) ImageType::RegionType imageRegion; imageRegion.SetSize(imageSize); - /** - * Create an input image. - * A light square on a dark background. - */ + // Create an input image. + // A light square on a dark background. PixelType background = 0; PixelType foreground = 190; @@ -85,12 +81,10 @@ itkNarrowBandCurvesLevelSetImageFilterTest(int argc, char * argv[]) ++it; } - /** - * Create an edge potential map. - * First compute the image gradient magnitude using a derivative of - * gaussian filter. Then apply a sigmoid function to the gradient - * magnitude. - */ + // Create an edge potential map. + // First compute the image gradient magnitude using a derivative of + // Gaussian filter. Then apply a sigmoid function to the gradient + // magnitude. using CastFilterType = itk::CastImageFilter; CastFilterType::Pointer caster = CastFilterType::New(); caster->SetInput(inputImage); @@ -109,10 +103,8 @@ itkNarrowBandCurvesLevelSetImageFilterTest(int argc, char * argv[]) sigmoid->SetBeta(2.5); sigmoid->SetInput(gradMagnitude->GetOutput()); - /** - * Create an initial level. - * Use fast marching to create an signed distance from a seed point. - */ + // Create an initial level. + // Use fast marching to create an signed distance from a seed point. using FastMarchingFilterType = itk::FastMarchingImageFilter; FastMarchingFilterType::Pointer fastMarching = FastMarchingFilterType::New(); @@ -137,32 +129,34 @@ itkNarrowBandCurvesLevelSetImageFilterTest(int argc, char * argv[]) fastMarching->SetSpeedConstant(1.0); fastMarching->SetOutputSize(imageSize); - /** - * Set up and run the shape detection filter - */ + // Set up and run the shape detection filter using CurvesFilterType = itk::NarrowBandCurvesLevelSetImageFilter; CurvesFilterType::Pointer curvesFilter = CurvesFilterType::New(); - // set the initial level set + ITK_EXERCISE_BASIC_OBJECT_METHODS(curvesFilter, NarrowBandCurvesLevelSetImageFilter, NarrowBandLevelSetImageFilter); + + + bool reverseExpansionDirection = false; + ITK_TEST_SET_GET_BOOLEAN(curvesFilter, ReverseExpansionDirection, reverseExpansionDirection); + + // Set the initial level set curvesFilter->SetInput(fastMarching->GetOutput()); - // set the edge potential image + // Set the edge potential image curvesFilter->SetFeatureImage(sigmoid->GetOutput()); - // set the weights between the propagation, curvature and advection terms + // Set the weights between the propagation, curvature and advection terms curvesFilter->SetPropagationScaling(0.3); curvesFilter->SetCurvatureScaling(0.5); curvesFilter->SetAdvectionScaling(0.5); - // set the convergence criteria + // Set the convergence criteria curvesFilter->SetNumberOfIterations(50); curvesFilter->SetNumberOfWorkUnits(2); - /** - * Threshold the output level set to display the final contour. - */ + // Threshold the output level set to display the final contour. using ThresholdFilterType = itk::BinaryThresholdImageFilter; ThresholdFilterType::Pointer thresholder = ThresholdFilterType::New(); @@ -172,9 +166,7 @@ itkNarrowBandCurvesLevelSetImageFilterTest(int argc, char * argv[]) thresholder->SetOutsideValue(0); thresholder->SetInsideValue(255); - /** - * Compute overlap between the true shape and the segmented shape - */ + // Compute overlap between the true shape and the segmented shape using OverlapCalculatorType = itk::SimilarityIndexImageFilter; OverlapCalculatorType::Pointer overlap = OverlapCalculatorType::New(); @@ -182,14 +174,11 @@ itkNarrowBandCurvesLevelSetImageFilterTest(int argc, char * argv[]) overlap->SetInput2(thresholder->GetOutput()); overlap->Update(); - /** Printout useful information from the shape detection filter. */ + // Printout useful information from the shape detection filter. std::cout << "Max. no. iterations: " << curvesFilter->GetNumberOfIterations() << std::endl; std::cout << "No. elpased iterations: " << curvesFilter->GetElapsedIterations() << std::endl; std::cout << "Overlap: " << overlap->GetSimilarityIndex() << std::endl; - /** - * Uncomment to write out image files. - */ using WriterType = itk::ImageFileWriter; WriterType::Pointer writer = WriterType::New();