From bb1868680072e4d103e51cd81402329a14af9614 Mon Sep 17 00:00:00 2001 From: maekclena Date: Thu, 28 Mar 2019 13:59:26 +0100 Subject: [PATCH 1/2] ENH: Cleanup python wrapping tests --- .../Generators/Python/Tests/CMakeLists.txt | 83 +------- .../Python/Tests/FlatStructuringElement.py | 53 ----- .../Tests/OldStyleBinaryDilateImageFilter.py | 37 ---- ...trelFromImageGrayscaleDilateImageFilter.py | 40 ---- .../Python/Tests/exclude-filters.txt | 3 - .../Python/Tests/findEmptyClasses.py | 168 ++++++---------- .../Generators/Python/Tests/getNameOfClass.py | 4 +- .../Tests/notYetUsable/DicomSliceRead.py | 50 ----- .../Tests/notYetUsable/ImageRegistration3.py | 136 ------------- .../Tests/notYetUsable/ImageRegistration4.py | 139 ------------- .../Tests/notYetUsable/ImageRegistration5.py | 189 ------------------ .../Python/Tests/notYetUsable/ImageToArray.py | 43 ---- .../Tests/notYetUsable/VoronoiSegmentation.py | 49 ----- 13 files changed, 74 insertions(+), 920 deletions(-) delete mode 100644 Wrapping/Generators/Python/Tests/FlatStructuringElement.py delete mode 100644 Wrapping/Generators/Python/Tests/OldStyleBinaryDilateImageFilter.py delete mode 100644 Wrapping/Generators/Python/Tests/StrelFromImageGrayscaleDilateImageFilter.py delete mode 100644 Wrapping/Generators/Python/Tests/notYetUsable/DicomSliceRead.py delete mode 100644 Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration3.py delete mode 100644 Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration4.py delete mode 100644 Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration5.py delete mode 100644 Wrapping/Generators/Python/Tests/notYetUsable/ImageToArray.py delete mode 100644 Wrapping/Generators/Python/Tests/notYetUsable/VoronoiSegmentation.py diff --git a/Wrapping/Generators/Python/Tests/CMakeLists.txt b/Wrapping/Generators/Python/Tests/CMakeLists.txt index fd38fec55f5..7ebf5874228 100644 --- a/Wrapping/Generators/Python/Tests/CMakeLists.txt +++ b/Wrapping/Generators/Python/Tests/CMakeLists.txt @@ -9,21 +9,9 @@ endif() itk_python_add_test(NAME PythonImageIOCoverage COMMAND wrappingCoverage.py -b ImageIO -e ${CMAKE_CURRENT_SOURCE_DIR}/exclude-imageio.txt ${ITK_INCLUDE_DIRS}) itk_python_add_test(NAME PythonTransformCoverage COMMAND wrappingCoverage.py -b Transform -e ${CMAKE_CURRENT_SOURCE_DIR}/exclude-transform.txt ${ITK_INCLUDE_DIRS}) -execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "import numpy" - RESULT_VARIABLE _have_numpy_return_code - OUTPUT_QUIET - ERROR_QUIET - ) - -# These two tests can use up all of system memory when the are executed. -# TODO: find the root cause and re-enable them. See ITK-3006 on issues.itk.org. -#itk_python_add_test(PythonFindEmptyClasses findEmptyClasses.py) -if(_have_numpy_return_code EQUAL 0 AND ITK_BUILD_DEFAULT_MODULES) - # Currently unreliably fails. See Issue #96 - # itk_python_add_test(NAME PythonGetNameOfClass COMMAND getNameOfClass.py) - - itk_python_add_test(NAME PythonTiming COMMAND timing.py) -endif() +itk_python_add_test(NAME PythonFindEmptyClasses COMMAND findEmptyClasses.py) +itk_python_add_test(NAME PythonGetNameOfClass COMMAND getNameOfClass.py) +itk_python_add_test(NAME PythonTiming COMMAND timing.py) itk_python_add_test(NAME PythonVerifyGetOutputAPIConsistency COMMAND verifyGetOutputAPIConsistency.py) itk_python_add_test(NAME PythonVerifyTTypeAPIConsistency COMMAND verifyTTypeAPIConsistency.py) itk_python_add_test(NAME PythonComplex COMMAND complex.py) @@ -49,70 +37,13 @@ if(ITK_WRAP_unsigned_char AND WRAP_2) DATA{${WrapITK_SOURCE_DIR}/images/cthead1.png} 5 ) - if(_have_numpy_return_code EQUAL 0) - itk_python_add_test(NAME PythonExtrasTest - COMMAND extras.py - DATA{${WrapITK_SOURCE_DIR}/images/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/out.png ${ITK_TEST_OUTPUT_DIR} - ) - endif() + itk_python_add_test(NAME PythonExtrasTest + COMMAND extras.py + DATA{${WrapITK_SOURCE_DIR}/images/cthead1.png} ${ITK_TEST_OUTPUT_DIR}/out.png ${ITK_TEST_OUTPUT_DIR} + ) endif() - -# itk_python_add_test(NAME PythonStrelFromImageGrayscaleDilateImageFilter -# StrelFromImageGrayscaleDilateImageFilter.py -# DATA{${WrapITK_SOURCE_DIR}/images/cthead1.png} -# StrelFromImageGrayscaleDilateImageFilter.png -# DATA{${WrapITK_SOURCE_DIR}/images/StrelFromImage.png} -# --compare StrelFromImageGrayscaleDilateImageFilter.png DATA{${WrapITK_SOURCE_DIR}/images/StrelFromImageGrayscaleDilateImageFilter.png} -# ) - -# itk_python_add_test(NAME PythonFlatStructuringElementBall -# FlatStructuringElement.py -# Ball-5.png -# Ball -# 5 -# --compare Ball-5.png DATA{${WrapITK_SOURCE_DIR}/images/Ball-5.png} -# ) - -# itk_python_add_test(NAME PythonFlatStructuringElementBox -# FlatStructuringElement.py -# Box-5.png -# Box -# 5 -# --compare Box-5.png DATA{${WrapITK_SOURCE_DIR}/images/Box-5.png} -# ) - -# itk_python_add_test(NAME PythonFlatStructuringElementFromImage -# FlatStructuringElement.py -# StrelFromImage.png -# FromImage -# DATA{${WrapITK_SOURCE_DIR}/images/StrelFromImage.png} -# --compare StrelFromImage.png DATA{${WrapITK_SOURCE_DIR}/images/StrelFromImage.png} -# ) -endif() - -if(ITK_WRAP_float AND WRAP_2) -# itk_python_add_test(NAME PythonGeodesicActiveContourWhiteMatterTest -# --compare GeodesicActiveContourWhiteMatterTest.png -# DATA{${WrapITK_SOURCE_DIR}/images/GeodesicActiveContourWhiteMatterTest.png} -# -- -# GeodesicActiveContourImageFilter.py -# DATA{${WrapITK_SOURCE_DIR}/images/BrainProtonDensitySlice.png} -# GeodesicActiveContourWhiteMatterTest.png -# 56 92 5.0 1.0 -0.3 2.0 10.0 -# ) - -# itk_python_add_test(NAME PythonGeodesicActiveContourGrayMatterTest -# --compare GeodesicActiveContourGrayMatterTest.png -# DATA{${WrapITK_SOURCE_DIR}/images/GeodesicActiveContourGrayMatterTest.png} -# -- -# GeodesicActiveContourImageFilter.py -# DATA{${WrapITK_SOURCE_DIR}/images/BrainProtonDensitySlice.png} -# GeodesicActiveContourGrayMatterTest.png -# 40 90 5.0 .5 -0.3 2.0 10.0 -# ) endif() - UNIQUE(types "${WRAP_ITK_SCALAR};UC") # signed char can't be used to store an image with values up to 255 list(REMOVE_ITEM types SC) diff --git a/Wrapping/Generators/Python/Tests/FlatStructuringElement.py b/Wrapping/Generators/Python/Tests/FlatStructuringElement.py deleted file mode 100644 index 26b6c46b810..00000000000 --- a/Wrapping/Generators/Python/Tests/FlatStructuringElement.py +++ /dev/null @@ -1,53 +0,0 @@ -#========================================================================== -# -# Copyright Insight Software Consortium -# -# 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. -# -#==========================================================================*/ - -from __future__ import print_function - -import itk -from sys import argv, exit -itk.auto_progress(2) - -if argv[2] == "Ball": - print("Ball") - strel = itk.FlatStructuringElement[2].Ball(int(argv[3])) -elif argv[2] == "Box": - print("Box") - strel = itk.FlatStructuringElement[2].Box(int(argv[3])) -elif argv[2] == "FromImage": - print("FromImage") - reader = itk.ImageFileReader.IUC2.New(FileName=argv[3]) - strel = itk.FlatStructuringElement[2].FromImageUC(reader.GetOutput()) -else: - print("invalid arguement: " + argv[2]) - exit(1) - -img = strel.GetImageUC() -size = itk.size(img) -for y in range(0, size.GetElement(1)): - for x in range(0, size.GetElement(0)): - if img.GetPixel([x, y]): - print("X") - else: - print(" ") - print("\n") - -itk.write(img, argv[1]) - -# writer = itk.ImageFileWriter.IUC2.New(FileName=argv[1], Input=img ) -# itk.echo(writer) -# writer.Update() diff --git a/Wrapping/Generators/Python/Tests/OldStyleBinaryDilateImageFilter.py b/Wrapping/Generators/Python/Tests/OldStyleBinaryDilateImageFilter.py deleted file mode 100644 index bb01f4ffea9..00000000000 --- a/Wrapping/Generators/Python/Tests/OldStyleBinaryDilateImageFilter.py +++ /dev/null @@ -1,37 +0,0 @@ -#========================================================================== -# -# Copyright Insight Software Consortium -# -# 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. -# -#==========================================================================*/ - -# -# Example on the use of the BinaryDilateImageFilter -# - -from InsightToolkit import * -from sys import argv - -reader = itkImageFileReaderIUC2.New() -reader.SetFileName(argv[1]) -kernel = itkFlatStructuringElement2.Ball(5) -filter = itkBinaryDilateImageFilterIUC2IUC2SE2.New() -filter.SetInput(reader.GetOutput()) -filter.SetDilateValue(200) -filter.SetKernel(kernel) -writer = itkImageFileWriterIUC2.New() -writer.SetInput(filter.GetOutput()) -writer.SetFileName(argv[2]) - -writer.Update() diff --git a/Wrapping/Generators/Python/Tests/StrelFromImageGrayscaleDilateImageFilter.py b/Wrapping/Generators/Python/Tests/StrelFromImageGrayscaleDilateImageFilter.py deleted file mode 100644 index 758828e8336..00000000000 --- a/Wrapping/Generators/Python/Tests/StrelFromImageGrayscaleDilateImageFilter.py +++ /dev/null @@ -1,40 +0,0 @@ -#========================================================================== -# -# Copyright Insight Software Consortium -# -# 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. -# -#==========================================================================*/ - -# -# Example on the use of the GrayscaleDilateImageFilter -# and Box strucutring element -# - -import itk -from sys import argv -itk.auto_progress(2) - -dim = 2 -IType = itk.Image[itk.US, dim] -OIType = itk.Image[itk.UC, dim] - -reader = itk.ImageFileReader[IType].New(FileName=argv[1]) -reader2 = itk.ImageFileReader[OIType].New(FileName=argv[3]) -kernel = itk.FlatStructuringElement[dim].FromImageUC(reader2.GetOutput()) -grayscaleFilter = itk.GrayscaleDilateImageFilter[IType, IType, kernel] -grayscaleFilter = grayscaleFilter.New(reader, Kernel=kernel) -cast = itk.CastImageFilter[IType, OIType].New(grayscaleFilter) -writer = itk.ImageFileWriter[OIType].New(cast, FileName=argv[2]) - -writer.Update() diff --git a/Wrapping/Generators/Python/Tests/exclude-filters.txt b/Wrapping/Generators/Python/Tests/exclude-filters.txt index 4addb8a8a69..8ad66df0227 100644 --- a/Wrapping/Generators/Python/Tests/exclude-filters.txt +++ b/Wrapping/Generators/Python/Tests/exclude-filters.txt @@ -3,7 +3,6 @@ ReconstructionImageFilter ObjectMorphologyImageFilter MovingHistogramDilateImageFilter MovingHistogramErodeImageFilter -MovingHistogramImageFilter MovingHistogramMorphologicalGradientImageFilter MovingHistogramMorphologyImageFilter MorphologyImageFilter @@ -37,9 +36,7 @@ MiniPipelineSeparableImageFilter VanHerkGilWermanDilateImageFilter VanHerkGilWermanErodeDilateImageFilter VanHerkGilWermanErodeImageFilter -InterpolateImageFilter MaskedMovingHistogramImageFilter -MeshToMeshFilter VectorFuzzyConnectednessImageFilter WarpJacobianDeterminantFilter MatrixIndexSelectionImageFilter diff --git a/Wrapping/Generators/Python/Tests/findEmptyClasses.py b/Wrapping/Generators/Python/Tests/findEmptyClasses.py index 93b3d677030..b75e319b7c9 100644 --- a/Wrapping/Generators/Python/Tests/findEmptyClasses.py +++ b/Wrapping/Generators/Python/Tests/findEmptyClasses.py @@ -19,110 +19,70 @@ from __future__ import print_function import itk -import re import sys -# itk.auto_progress(True) - from itkTemplate import itkTemplate -# sets are not in builtin with python older than 2.4 -import sets -set = sets.Set - -# dirty but easier: a global var to count the empty classes -empty = set() - - -def exploreTpl(tpl): - for cl in tpl.itervalues(): - print(cl) - exploreMethods(cl) - # try to instanciate the class - try: - obj = cl.New() - exploreMethods(obj) - except: - pass - try: - exploreMethods(cl()) - except: - pass - - -def exploreMethods(obj): - global count - excludeList = ['this', 'thisown'] - attrNameList = [i for i in dir( - obj) if isinstance(i, str) and i[0].isupper() and i not in excludeList] - if attrNameList == []: - empty.add(obj) - - -excluded = set([ - "PeriodicBoundaryCondition", - "BandNode", - "DefaultDynamicMeshTraits", - "DefaultStaticMeshTraits", - "NormalBandNode", - "ZeroFluxNeumannBoundaryCondition", - "SparseFieldLevelSetNode", - "ParallelSparseFieldLevelSetNode", - "PySwigIterator", - "SwigPyIterator", - "COLORS", - "VECTOR_REALS", - "SCALARS", - "ALL_TYPES", - "COMPLEX_REALS", - "RGBS", - "RGBAS", - "REALS", - "USIGN_INTS", - "DIMS", - "SIGN_INTS", - "VECTORS", - "INTS", - "COV_VECTOR_REALS", - "FFTComplexToComplexImageFilter", - "QuadEdgeMeshCellTraitsInfo", - "QuadEdgeMeshTraits", - "OnesMatrixCoefficients", - "ConformalMatrixCoefficients", - "InverseEuclideanDistanceMatrixCoefficients", - "AuthalicMatrixCoefficients", - "IntrinsicMatrixCoefficients", - "InverseEuclideanDistanceMatrixCoefficients", - "OnesMatrixCoefficients", - "ConformalMatrixCoefficients", - "AuthalicMatrixCoefficients", - "MatrixCoefficients", -]) - - -attrNameList = set( - [i for i in dir(itk) if i[0].isupper() and len(i) > 2]) - excluded - -for name in attrNameList: - # use it because of lazy loading - exec "attr = itk." + name - print("-----------", name, "-----------") - if isinstance(attr, itkTemplate): - exploreTpl(attr) - else: - exploreMethods(attr) - try: - exploreMethods(cl.New()) - except: - pass - try: - exploreMethods(cl()) - except: - pass - -print() -print() -print(len(empty), "empty classes found") -for c in empty: - print(c) - -sys.exit(len(empty)) +itk.auto_progress(2) + +itk.force_load() + +def isEmpty(o): + for i in dir(o): + if i[0].isupper(): + return False + return True + + +exclude = ["AuthalicMatrixCoefficients", + "MatrixCoefficients", + "OnesMatrixCoefficients", + "IntrinsicMatrixCoefficients", + "HarmonicMatrixCoefficients", + "ConformalMatrixCoefficients", + "InverseEuclideanDistanceMatrixCoefficients", + "BandNode", + "NormalBandNode", + "CellTraitsInfo", + "DefaultDynamicMeshTraits", + "DefaultStaticMeshTraits", + "ParallelSparseFieldLevelSetNode", + "SparseFieldLevelSetNode", + "QuadEdgeMeshCellTraitsInfo", + "QuadEdgeMeshTraits", + "complex", + "list", + "map", + "numeric_limits", + "set", + "vector", + "vnl_c_vector", + "vnl_diag_matrix", + "vnl_matrix", + "vnl_matrix_fixed", + "vnl_matrix_fixed_ref", + "vnl_matrix_fixed_ref_const", + "vnl_matrix_ref", + "vnl_vector", + "vnl_vector_ref", + "vnl_file_matrix", + "vnl_file_vector", + "vnl_fortran_copy", + ] + +total = 0 +empty = 0 + +for t in dir(itk): + if t not in exclude: + T = itk.__dict__[t] + if isinstance(T, itkTemplate): + for I in T.values(): + total += 1 + if isEmpty(I): + empty += 1 + print("%s: empty class" % I) + +print("%s classes checked." % total) +if empty: + print("%s empty classes found" % empty, file=sys.stderr) + sys.exit(1) diff --git a/Wrapping/Generators/Python/Tests/getNameOfClass.py b/Wrapping/Generators/Python/Tests/getNameOfClass.py index 2af8c297233..2c97c763705 100644 --- a/Wrapping/Generators/Python/Tests/getNameOfClass.py +++ b/Wrapping/Generators/Python/Tests/getNameOfClass.py @@ -39,7 +39,9 @@ "templated_class", "HalfHermitianToRealInverseFFTImageFilter", "RealToHalfHermitianForwardFFTImageFilter", - "CustomColormapFunction"] + "CustomColormapFunction", + "ScanlineFilterCommon" # Segfault + ] wrongName = 0 totalName = 0 diff --git a/Wrapping/Generators/Python/Tests/notYetUsable/DicomSliceRead.py b/Wrapping/Generators/Python/Tests/notYetUsable/DicomSliceRead.py deleted file mode 100644 index 5df27985121..00000000000 --- a/Wrapping/Generators/Python/Tests/notYetUsable/DicomSliceRead.py +++ /dev/null @@ -1,50 +0,0 @@ -#========================================================================== -# -# Copyright Insight Software Consortium -# -# 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. -# -#==========================================================================*/ - -# -# Example on the use of DicomImageIO for reading a single DICOM slice, rescale -# the intensities and save it in a different file format. -# - -from InsightToolkit import * - -from sys import argv - -# -# Reads an image in 16bits/pixel -# and save it as 8bits/pixel -# -reader = itkImageFileReaderUS2_New() -writer = itkImageFileWriterUC2_New() - -dicomIO = itkDicomImageIO_New() - -reader.SetImageIO(dicomIO) - -filter = itkRescaleIntensityImageFilterUS2UC2_New() - -filter.SetOutputMinimum(0) -filter.SetOutputMaximum(255) - -filter.SetInput(reader.GetOutput()) -writer.SetInput(filter.GetOutput()) - -reader.SetFileName(argv[1]) -writer.SetFileName(argv[2]) - -writer.Update() diff --git a/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration3.py b/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration3.py deleted file mode 100644 index 4caa99a81db..00000000000 --- a/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration3.py +++ /dev/null @@ -1,136 +0,0 @@ -#========================================================================== -# -# Copyright Insight Software Consortium -# -# 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. -# -#==========================================================================*/ - -from InsightToolkit import * - -from sys import argv - - -# -# Read the fixed and moving images using filenames -# from the command line arguments -# -fixedImageReader = itkImageFileReaderF2_New() -movingImageReader = itkImageFileReaderF2_New() - -fixedImageReader.SetFileName(argv[1]) -movingImageReader.SetFileName(argv[2]) - -fixedImageReader.Update() -movingImageReader.Update() - -fixedImage = fixedImageReader.GetOutput() -movingImage = movingImageReader.GetOutput() - - -# -# Instantiate the classes for the registration framework -# -registration = itkImageRegistrationMethodF2F2_New() -imageMetric = itkMeanSquaresImageToImageMetricF2F2_New() -transform = itkTranslationTransform2_New() -optimizer = itkRegularStepGradientDescentOptimizer_New() -interpolator = itkLinearInterpolateImageFunctionF2D_New() - - -registration.SetOptimizer(optimizer) -registration.SetTransform(transform) -registration.SetInterpolator(interpolator) -registration.SetMetric(imageMetric) -registration.SetFixedImage(fixedImage) -registration.SetMovingImage(movingImage) - -registration.SetFixedImageRegion(fixedImage.GetBufferedRegion()) - -transform.SetIdentity() -initialParameters = transform.GetParameters() - -registration.SetInitialTransformParameters(initialParameters) - -# -# Iteration Observer -# - - -def iterationUpdate(): - currentParameter = transform.GetParameters() - print "M: %f P: %f %f " % (optimizer.GetValue(), - currentParameter.GetElement(0), - currentParameter.GetElement(1)) - -iterationCommand = itkPyCommand_New() -iterationCommand.SetCommandCallable(iterationUpdate) -optimizer.AddObserver(itkIterationEvent(), iterationCommand.GetPointer()) - - -# -# Define optimizer parameters -# -optimizer.SetMaximumStepLength(4.00) -optimizer.SetMinimumStepLength(0.01) -optimizer.SetNumberOfIterations(200) - - -print "Starting registration" - -# -# Start the registration process -# - -registration.Update() - - -# -# Get the final parameters of the transformation -# -finalParameters = registration.GetLastTransformParameters() - -print "Final Registration Parameters " -print "Translation X = %f" % (finalParameters.GetElement(0),) -print "Translation Y = %f" % (finalParameters.GetElement(1),) - - -# -# Now, we use the final transform for resampling the -# moving image. -# -resampler = itkResampleImageFilterF2F2_New() -resampler.SetTransform(transform) -resampler.SetInput(movingImage) - -region = fixedImage.GetLargestPossibleRegion() - -resampler.SetSize(region.GetSize()) - -resampler.SetOutputSpacing(fixedImage.GetSpacing()) -resampler.SetOutputOrigin(fixedImage.GetOrigin()) -resampler.SetDefaultPixelValue(100) - -outputCast = itkRescaleIntensityImageFilterF2US2_New() -outputCast.SetOutputMinimum(0) -outputCast.SetOutputMaximum(65535) -outputCast.SetInput(resampler.GetOutput()) - -# -# Write the resampled image -# -writer = itkImageFileWriterUS2_New() - -writer.SetFileName(argv[3]) -writer.SetInput(outputCast.GetOutput()) -writer.Update() diff --git a/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration4.py b/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration4.py deleted file mode 100644 index b6616c5b45c..00000000000 --- a/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration4.py +++ /dev/null @@ -1,139 +0,0 @@ -#========================================================================== -# -# Copyright Insight Software Consortium -# -# 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. -# -#==========================================================================*/ - -from InsightToolkit import * - -from sys import argv - - -# -# Read the fixed and moving images using filenames -# from the command line arguments -# -fixedImageReader = itkImageFileReaderF2_New() -movingImageReader = itkImageFileReaderF2_New() - -fixedImageReader.SetFileName(argv[1]) -movingImageReader.SetFileName(argv[2]) - -fixedImageReader.Update() -movingImageReader.Update() - -fixedImage = fixedImageReader.GetOutput() -movingImage = movingImageReader.GetOutput() - - -# -# Instantiate the classes for the registration framework -# -registration = itkImageRegistrationMethodF2F2_New() -imageMetric = itkMattesMutualInformationImageToImageMetricF2F2_New() -transform = itkTranslationTransform2_New() -optimizer = itkRegularStepGradientDescentOptimizer_New() -interpolator = itkLinearInterpolateImageFunctionF2D_New() - - -imageMetric.SetNumberOfHistogramBins(20) -imageMetric.SetNumberOfSpatialSamples(10000) - -registration.SetOptimizer(optimizer) -registration.SetTransform(transform) -registration.SetInterpolator(interpolator) -registration.SetMetric(imageMetric) -registration.SetFixedImage(fixedImage) -registration.SetMovingImage(movingImage) - -registration.SetFixedImageRegion(fixedImage.GetBufferedRegion()) - -transform.SetIdentity() -initialParameters = transform.GetParameters() - -registration.SetInitialTransformParameters(initialParameters) - -# -# Iteration Observer -# - - -def iterationUpdate(): - currentParameter = transform.GetParameters() - print "M: %f P: %f %f " % (optimizer.GetValue(), - currentParameter.GetElement(0), - currentParameter.GetElement(1)) - -iterationCommand = itkPyCommand_New() -iterationCommand.SetCommandCallable(iterationUpdate) -optimizer.AddObserver(itkIterationEvent(), iterationCommand.GetPointer()) - - -# -# Define optimizer parameters -# -optimizer.SetMaximumStepLength(4.00) -optimizer.SetMinimumStepLength(0.01) -optimizer.SetNumberOfIterations(200) - - -print "Starting registration" - -# -# Start the registration process -# - -registration.Update() - - -# -# Get the final parameters of the transformation -# -finalParameters = registration.GetLastTransformParameters() - -print "Final Registration Parameters " -print "Translation X = %f" % (finalParameters.GetElement(0),) -print "Translation Y = %f" % (finalParameters.GetElement(1),) - - -# -# Now, we use the final transform for resampling the -# moving image. -# -resampler = itkResampleImageFilterF2F2_New() -resampler.SetTransform(transform) -resampler.SetInput(movingImage) - -region = fixedImage.GetLargestPossibleRegion() - -resampler.SetSize(region.GetSize()) - -resampler.SetOutputSpacing(fixedImage.GetSpacing()) -resampler.SetOutputOrigin(fixedImage.GetOrigin()) -resampler.SetDefaultPixelValue(100) - -outputCast = itkRescaleIntensityImageFilterF2US2_New() -outputCast.SetOutputMinimum(0) -outputCast.SetOutputMaximum(65535) -outputCast.SetInput(resampler.GetOutput()) - -# -# Write the resampled image -# -writer = itkImageFileWriterUS2_New() - -writer.SetFileName(argv[3]) -writer.SetInput(outputCast.GetOutput()) -writer.Update() diff --git a/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration5.py b/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration5.py deleted file mode 100644 index 651b43b1d5f..00000000000 --- a/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration5.py +++ /dev/null @@ -1,189 +0,0 @@ -#========================================================================== -# -# Copyright Insight Software Consortium -# -# 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. -# -#==========================================================================*/ - -# - -from InsightToolkit import * - -from sys import argv - -# -# Read the fixed and moving images using filenames -# from the command line arguments -# -fixedImageReader = itkImageFileReaderF2_New() -movingImageReader = itkImageFileReaderF2_New() - -fixedImageReader.SetFileName(argv[1]) -movingImageReader.SetFileName(argv[2]) - -fixedImageReader.Update() -movingImageReader.Update() - -fixedImage = fixedImageReader.GetOutput() -movingImage = movingImageReader.GetOutput() - -# -# Instantiate the classes for the registration framework -# -registration = itkImageRegistrationMethodF2F2_New() -imageMetric = itkMeanSquaresImageToImageMetricF2F2_New() -transform = itkCenteredRigid2DTransform_New() -optimizer = itkRegularStepGradientDescentOptimizer_New() -interpolator = itkLinearInterpolateImageFunctionF2D_New() - -registration.SetOptimizer(optimizer) -registration.SetTransform(transform) -registration.SetInterpolator(interpolator) -registration.SetMetric(imageMetric) -registration.SetFixedImage(fixedImage) -registration.SetMovingImage(movingImage) -registration.SetFixedImageRegion(fixedImage.GetBufferedRegion()) - - -# -# Initial transform parameters -# -transform.SetAngle(0.0) - -# center of the fixed image -fixedSpacing = fixedImage.GetSpacing() -fixedOrigin = fixedImage.GetOrigin() -fixedSize = fixedImage.GetLargestPossibleRegion().GetSize() - -centerFixed = ( - fixedOrigin.GetElement(0) + fixedSpacing.GetElement(0) * - fixedSize.GetElement(0) / 2.0, - fixedOrigin.GetElement(1) + fixedSpacing.GetElement(1) * - fixedSize.GetElement(1) / 2.0) - -# center of the moving image -movingSpacing = movingImage.GetSpacing() -movingOrigin = movingImage.GetOrigin() -movingSize = movingImage.GetLargestPossibleRegion().GetSize() - -centerMoving = ( - movingOrigin.GetElement(0) + movingSpacing.GetElement(0) * - movingSize.GetElement(0) / 2.0, - movingOrigin.GetElement(1) + movingSpacing.GetElement(1) * - movingSize.GetElement(1) / 2.0) - -# transform center -center = transform.GetCenter() -center.SetElement(0, centerFixed[0]) -center.SetElement(1, centerFixed[1]) - -# transform translation -translation = transform.GetTranslation() -translation.SetElement(0, centerMoving[0] - centerFixed[0]) -translation.SetElement(1, centerMoving[1] - centerFixed[1]) - -initialParameters = transform.GetParameters() - -print "Initial Parameters: " -print "Angle: %f" % (initialParameters.GetElement(0), ) -print "Center: %f, %f" % (initialParameters.GetElement(1), - initialParameters.GetElement(2)) -print "Translation: %f, %f" % (initialParameters.GetElement(3), - initialParameters.GetElement(4)) - -registration.SetInitialTransformParameters(initialParameters) - -# -# Define optimizer parameters -# - -# optimizer scale -translationScale = 1.0 / 1000.0 - -optimizerScales = itkArrayD(transform.GetNumberOfParameters()) -optimizerScales.SetElement(0, 1.0) -optimizerScales.SetElement(1, translationScale) -optimizerScales.SetElement(2, translationScale) -optimizerScales.SetElement(3, translationScale) -optimizerScales.SetElement(4, translationScale) - -optimizer.SetScales(optimizerScales) -optimizer.SetMaximumStepLength(0.1) -optimizer.SetMinimumStepLength(0.001) -optimizer.SetNumberOfIterations(200) - -# -# Iteration Observer -# - - -def iterationUpdate(): - currentParameter = transform.GetParameters() - print "M: %f P: %f %f %f %f %f " % (optimizer.GetValue(), - currentParameter.GetElement(0), - currentParameter.GetElement(1), - currentParameter.GetElement(2), - currentParameter.GetElement(3), - currentParameter.GetElement(4)) - -iterationCommand = itkPyCommand_New() -iterationCommand.SetCommandCallable(iterationUpdate) -optimizer.AddObserver(itkIterationEvent(), iterationCommand.GetPointer()) - -print "Starting registration" - -# -# Start the registration process -# - -registration.Update() - -# -# Get the final parameters of the transformation -# -finalParameters = registration.GetLastTransformParameters() - -print "Final Registration Parameters " -print "Angle in radians = %f" % finalParameters.GetElement(0) -print "Rotation Center X = %f" % finalParameters.GetElement(1) -print "Rotation Center Y = %f" % finalParameters.GetElement(2) -print "Translation in X = %f" % finalParameters.GetElement(3) -print "Translation in Y = %f" % finalParameters.GetElement(4) - -# Now, we use the final transform for resampling the moving image. -resampler = itkResampleImageFilterF2F2_New() - -resampler.SetTransform(transform) -resampler.SetInput(movingImage) - -region = fixedImage.GetLargestPossibleRegion() - -resampler.SetSize(region.GetSize()) -resampler.SetOutputSpacing(fixedImage.GetSpacing()) -resampler.SetOutputOrigin(fixedImage.GetOrigin()) -resampler.SetDefaultPixelValue(100) - -# -# Cast for output -# -outputCast = itkRescaleIntensityImageFilterF2US2_New() -outputCast.SetInput(resampler.GetOutput()) -outputCast.SetOutputMinimum(0) -outputCast.SetOutputMaximum(65535) - -writer = itkImageFileWriterUS2_New() - -writer.SetFileName(argv[3]) -writer.SetInput(outputCast.GetOutput()) -writer.Update() diff --git a/Wrapping/Generators/Python/Tests/notYetUsable/ImageToArray.py b/Wrapping/Generators/Python/Tests/notYetUsable/ImageToArray.py deleted file mode 100644 index 66ef5aa2a3b..00000000000 --- a/Wrapping/Generators/Python/Tests/notYetUsable/ImageToArray.py +++ /dev/null @@ -1,43 +0,0 @@ -#========================================================================== -# -# Copyright Insight Software Consortium -# -# 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. -# -#==========================================================================*/ - -from InsightToolkit import * -from numarray import * -from sys import argv - -reader = itkImageFileReaderUC2_New() - -connector = itkPyBufferUC2_New() - -reader.SetFileName(argv[1]) - -reader.Update() - -print "ready to convert image into array" - -buffer = connector.GetArrayFromImage(reader.GetOutput()) - -writer = itkImageFileWriterUC2_New() - -writer.SetFileName(argv[2]) - -print "ready to convert array into image" - -writer.SetInput(connector.GetImageFromArray(buffer)) - -writer.Update() diff --git a/Wrapping/Generators/Python/Tests/notYetUsable/VoronoiSegmentation.py b/Wrapping/Generators/Python/Tests/notYetUsable/VoronoiSegmentation.py deleted file mode 100644 index 4b8f655c9c9..00000000000 --- a/Wrapping/Generators/Python/Tests/notYetUsable/VoronoiSegmentation.py +++ /dev/null @@ -1,49 +0,0 @@ -#========================================================================== -# -# Copyright Insight Software Consortium -# -# 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. -# -#==========================================================================*/ - -# -# Example on the use of the VoronoiSegmentationImageFilter. -# - -from InsightToolkit import * - -from sys import argv - - -readerInput = itkImageFileReaderUC2_New() -readerPrior = itkImageFileReaderUC2_New() - -readerInput.SetFileName(argv[1]) -readerPrior.SetFileName(argv[2]) - -readerInput.Update() -readerPrior.Update() - -filter = itkVoronoiSegmentationImageFilterUC2UC2UC2_New() - -filter.SetInput(readerInput.GetOutput()) -filter.TakeAPrior(readerPrior.GetOutput()) - -filter.SetMeanPercentError(eval(argv[4])) -filter.SetSTDPercentError(eval(argv[5])) - -writer = itkImageFileWriterUC2_New() -writer.SetFileName(argv[3]) -writer.SetInput(filter.GetOutput()) - -writer.Update() From a82bb00110f1bf1e7c3fe984a0d397e2ea8c3289 Mon Sep 17 00:00:00 2001 From: maekclena Date: Fri, 29 Mar 2019 18:45:02 +0100 Subject: [PATCH 2/2] ENH: Address review comments --- .../test/CMakeLists.txt | 12 +++++ .../test/FlatStructuringElementTest.py | 33 ++++++++++++++ .../Generators/Python/Tests/getNameOfClass.py | 45 +++++++++---------- 3 files changed, 66 insertions(+), 24 deletions(-) create mode 100644 Modules/Filtering/MathematicalMorphology/test/FlatStructuringElementTest.py diff --git a/Modules/Filtering/MathematicalMorphology/test/CMakeLists.txt b/Modules/Filtering/MathematicalMorphology/test/CMakeLists.txt index 92481c445fe..0f732ef309a 100644 --- a/Modules/Filtering/MathematicalMorphology/test/CMakeLists.txt +++ b/Modules/Filtering/MathematicalMorphology/test/CMakeLists.txt @@ -524,6 +524,18 @@ itk_add_test(NAME itkRankImageFilterTest10 # some tests will fail if dim=2 and unsigned short are not wrapped list(FIND ITK_WRAP_IMAGE_DIMS 2 wrap_2_index) if(ITK_WRAP_unsigned_char AND wrap_2_index GREATER -1) + itk_python_add_test(NAME PythonFlatStructuringElementBall + TEST_DRIVER_ARGS + COMMAND FlatStructuringElementTest.py + Ball + 5 + ) + itk_python_add_test(NAME PythonFlatStructuringElementBox + TEST_DRIVER_ARGS + COMMAND FlatStructuringElementTest.py + Box + 5 + ) itk_python_add_test(NAME PythonGrayscaleDilateImageFilterTest TEST_DRIVER_ARGS --compare ${ITK_TEST_OUTPUT_DIR}/PythonGrayscaleDilateImageFilterTest.png diff --git a/Modules/Filtering/MathematicalMorphology/test/FlatStructuringElementTest.py b/Modules/Filtering/MathematicalMorphology/test/FlatStructuringElementTest.py new file mode 100644 index 00000000000..8c12ee086f6 --- /dev/null +++ b/Modules/Filtering/MathematicalMorphology/test/FlatStructuringElementTest.py @@ -0,0 +1,33 @@ +#========================================================================== +# +# Copyright Insight Software Consortium +# +# 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. +# +#==========================================================================*/ + +from __future__ import print_function + +import itk +from sys import argv, exit +itk.auto_progress(2) + +if argv[1] == "Ball": + print("Ball") + strel = itk.FlatStructuringElement[2].Ball(int(argv[2])) +elif argv[1] == "Box": + print("Box") + strel = itk.FlatStructuringElement[2].Box(int(argv[2])) +else: + print("invalid arguement: " + argv[1]) + exit(1) diff --git a/Wrapping/Generators/Python/Tests/getNameOfClass.py b/Wrapping/Generators/Python/Tests/getNameOfClass.py index 2c97c763705..01799e1d36b 100644 --- a/Wrapping/Generators/Python/Tests/getNameOfClass.py +++ b/Wrapping/Generators/Python/Tests/getNameOfClass.py @@ -28,6 +28,15 @@ itk.force_load() # itk.ImageToImageFilter + +def wrongClassName(cl, name): + o = cl.New() + # be sure that the type of the instantiated object is the same + # than the one of the class. It can be different if the class + # is an "abstract" one and don't provide any New() method. + # In that case, the one of the superclass is used. + return o.GetNameOfClass() != name and itk.class_(o) == cl + # a list of classes to exclude. Typically, the classes with a custom New() # method, which return a subclass of the current class exclude = ["ForwardFFTImageFilter", @@ -56,31 +65,19 @@ i = T.values()[0] # GetNameOfClass() is a virtual method of the LightObject class, # so we must instantiate an object with the New() method - if 'New' in dir(i): - I = i.New() - # be sure that the type of the instantiated object is the same - # than the one of the class. It can be different if the class - # is an "abstract" one and don't provide any New() method. - # In that case, the one of the superclass is used. - if 'GetNameOfClass' in dir(I): - # print("Checking", t) - totalName += 1 - n = I.GetNameOfClass() - if n != t and itk.class_(I) == i: - msg = "%s: wrong class name: %s" % (t, n) - print(msg, file=sys.stderr) - wrongName += 1 + if 'New' in dir(i) and 'GetNameOfClass' in dir(i): + totalName += 1 + if wrongClassName(i, t): + msg = "%s: wrong class name: %s" % (t, n) + print(msg, file=sys.stderr) + wrongName += 1 else: - if 'New' in dir(T): - I = T.New() - if 'GetNameOfClass' in dir(I): - # print("Checking", t) - totalName += 1 - n = I.GetNameOfClass() - if n != t and itk.class_(I) == T: - msg = "%s: wrong class name: %s" % (t, n) - print(msg, file=sys.stderr) - wrongName += 1 + if 'New' in dir(T) and 'GetNameOfClass' in dir(T): + totalName += 1 + if wrongClassName(T, t): + msg = "%s: wrong class name: %s" % (t, n) + print(msg, file=sys.stderr) + wrongName += 1 print("%s classes checked." % totalName) if wrongName: